// app/debug_ui.hpp — the SDL-side developer debug UI: a paged HUD, the in-world overlay legend, and an // expanded tile inspector. Lives in app/ (next to audio.hpp) because it draws with ui::Font into the // Framebuffer; the pure cores it reads (snapshot / field_stats / overlay / log) live in include/sc2k/ // debug/. The WHOLE file is behind SC2K_DEBUG, so a release `make app` compiles none of it. // // Everything here is read-only: it renders the DebugSnapshot + city fields the caller hands it and // never advances the sim or its RNG. #pragma once #ifdef SC2K_DEBUG #include #include #include #include #include #include #include "sc2k/city.hpp" #include "sc2k/debug/commute_overlay.hpp" #include "sc2k/debug/field_stats.hpp" #include "sc2k/debug/log.hpp" #include "sc2k/debug/overlay.hpp" #include "sc2k/sim/building_sizes.hpp" #include "sc2k/sim/simulation.hpp" // DebugSnapshot #include "sc2k/sim/things.hpp" // thg field offsets + ship_nav (trail/route) #include "sc2k/render/framebuffer.hpp" #include "sc2k/render/iso_projection.hpp" // tile_to_screen (ship-trail overlay) #include "sc2k/render/rotate.hpp" #include "sc2k/render/palette.hpp" #include "sc2k/ui/commentary.hpp" #include "sc2k/ui/font.hpp" namespace sc2k::debug { using render::Framebuffer; using render::Rgba; // --- colours (a debug overlay, not a faithful dialog — readability over Win95 fidelity) --- inline constexpr Rgba kPanelBg{0x10, 0x10, 0x18, 0xFF}; // near-black, blended translucent inline constexpr Rgba kHdr{0xFF, 0xD0, 0x40, 0xFF}; // amber header inline constexpr Rgba kKey{0x88, 0xC0, 0xFF, 0xFF}; // blue labels inline constexpr Rgba kVal{0xF0, 0xF0, 0xF0, 0xFF}; // white values inline constexpr Rgba kDimTxt{0x90, 0x90, 0x90, 0xFF}; // dim / off inline constexpr Rgba kGood{0x60, 0xE0, 0x60, 0xFF}; // green (on / healthy) // --- persistent UI state (owned by main.cpp; fed nowMs each frame for the FPS counter) --- struct DebugUiState { static constexpr int kPages = 7; bool hudVisible = false; int hudPage = 0; OverlayField overlay = OverlayField::None; std::uint8_t overlayAlpha = 110; bool inspectorExpanded = false; bool showShipOverlay = false; // F9: ships (breadcrumb trail + A* route + head marker) + seaport diagnosis bool showCommuteOverlay = false; // F10: sampled accepted routes + failed origins from the growth scan // SDL-free FPS accumulator (caller passes SDL_GetTicks()). std::uint32_t lastFpsMs = 0; int frames = 0; double fps = 0.0; void cycle_page() { hudPage = (hudPage + 1) % kPages; } void cycle_overlay() { overlay = next_overlay(overlay); } void tick_fps(std::uint32_t nowMs) { if (lastFpsMs == 0) { lastFpsMs = nowMs; return; } ++frames; const std::uint32_t dt = nowMs - lastFpsMs; if (dt >= 500) { fps = frames * 1000.0 / dt; frames = 0; lastFpsMs = nowMs; } } }; inline const char* hud_page_name(int p) { switch (p) { case 0: return "Sim"; case 1: return "Finance"; case 2: return "Services"; case 3: return "Fields"; case 4: return "Disaster/Things"; case 5: return "Commentary"; default: return "Log"; } } // The 8 distinct scheduler phases (simulation.hpp tick()). Ticks 3..18 are the 16 growth-scan regions. inline std::string phase_label(int t) { if (t >= 3 && t <= 18) return "growth-scan " + std::to_string((t - 3) / 4) + "," + std::to_string((t - 3) % 4); switch (t) { case 0: return "month-rollover"; case 1: return "power"; case 2: return "fields"; case 19: return "traffic-decay"; case 20: return "water"; case 21: return "demand/econ"; case 22: return "scenario-check"; default: return "idle"; } } inline const char* season_name(int s) { switch (s) { case 0: return "Winter"; case 1: return "Spring"; case 2: return "Summer"; default: return "Autumn"; } } inline const char* commentary_block_name(ui::CommentaryBlockReason reason) { switch (reason) { case ui::CommentaryBlockReason::None: return "none"; case ui::CommentaryBlockReason::InvalidContext: return "invalid context"; case ui::CommentaryBlockReason::AlreadyEvaluatedMonth: return "already evaluated"; case ui::CommentaryBlockReason::EmergencyActive: return "emergency active"; case ui::CommentaryBlockReason::BeforeCadence: return "before cadence"; case ui::CommentaryBlockReason::NoEligibleRules: return "no eligible rules"; case ui::CommentaryBlockReason::WeightOverflow: return "weight overflow"; } return "unknown"; } inline const char* commentary_topic_name(ui::CommentTopic topic) { switch (topic) { case ui::CommentTopic::General: return "general"; case ui::CommentTopic::Construction: return "construction"; case ui::CommentTopic::CivicServices: return "civic services"; case ui::CommentTopic::Ordinances: return "ordinances"; case ui::CommentTopic::Finance: return "finance"; case ui::CommentTopic::Economy: return "economy"; case ui::CommentTopic::Population: return "population"; case ui::CommentTopic::Employment: return "employment"; case ui::CommentTopic::Education: return "education"; case ui::CommentTopic::Health: return "health"; case ui::CommentTopic::Environment: return "environment"; case ui::CommentTopic::Traffic: return "traffic"; case ui::CommentTopic::Utilities: return "utilities"; case ui::CommentTopic::Weather: return "weather"; case ui::CommentTopic::Disaster: return "disaster"; case ui::CommentTopic::Sport: return "sport"; case ui::CommentTopic::Technology: return "technology"; case ui::CommentTopic::Neighbors: return "neighbors"; case ui::CommentTopic::Count: break; } return "unknown"; } inline const char* commentary_disposition_name(ui::CommentRuleDisposition disposition) { switch (disposition) { case ui::CommentRuleDisposition::Eligible: return "eligible"; case ui::CommentRuleDisposition::Selected: return "selected"; case ui::CommentRuleDisposition::RejectedInvalidDefinition: return "invalid"; case ui::CommentRuleDisposition::RejectedTrigger: return "trigger"; case ui::CommentRuleDisposition::RejectedGate: return "gate"; case ui::CommentRuleDisposition::RejectedRuleCooldown: return "rule cooldown"; case ui::CommentRuleDisposition::RejectedTopicCooldown: return "topic cooldown"; case ui::CommentRuleDisposition::RejectedLowerPriority: return "lower priority"; } return "unknown"; } inline std::string commentary_diagnostic_ids(const ui::CommentaryDecision& decision, ui::CommentRuleDisposition disposition, bool showGate = false) { std::string result; int shown = 0; int total = 0; for (const ui::CommentRuleDiagnostic& diagnostic : decision.diagnostics) { if (diagnostic.disposition != disposition) continue; ++total; if (shown == 8) continue; if (!result.empty()) result += " "; result += std::to_string(diagnostic.id.value); if (showGate && diagnostic.failedGate != ui::kNoFailedCommentGate) result += ":g" + std::to_string(diagnostic.failedGate); ++shown; } if (total > shown) result += " +" + std::to_string(total - shown); return result.empty() ? "-" : result; } inline const char* month_abbr(int m) { static const char* k[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; return (m >= 0 && m < 12) ? k[m] : "?"; } // Disaster type → name (project-verified map; Libreopolis-disasters memory + trigger table in main.cpp). inline const char* disaster_type_name(int t) { switch (t) { case 1: return "Fire"; case 2: return "Flood"; case 3: return "Riot"; case 6: return "Earthquake"; case 7: return "Tornado"; case 8: return "Monster"; case 9: return "Meltdown"; case 10: return "Microwave"; case 0x0B: return "Volcano"; case 0x0D: return "Mass Riots"; case 0x10: return "Hurricane"; case 0x12: return "Air Crash"; default: return "?"; } } // XBIT flags decoded (the bits the codebase pins; unknown bits shown as raw hex). inline std::string xbit_flags(std::uint8_t b) { std::string s; auto add = [&](const char* n) { if (!s.empty()) s += " "; s += n; }; if (b & 0x02) add("mirror"); if (b & 0x04) add("water"); if (b & 0x10) add("watered"); if (b & 0x20) add("piped"); if (b & 0x40) add("powered"); if (b & 0x80) add("conductive"); if (s.empty()) s = "-"; return s; } // Coarse XBLD category band (no name table exists — this is an honest range classification, not a name). inline const char* xbld_band(int c) { if (c == 0) return "empty"; if (c <= 0x0D) return "terrain/feature"; if (c <= 0x1C) return "power line"; if (c <= 0x2B) return "road"; if (c <= 0x3A) return "rail"; if (c <= 0x6F) return "highway/bridge/tunnel"; if (c <= 0xC5) return "zoned building (R/C/I)"; return "civic/service/special"; } // Helper: a small key/value or section row used by the HUD pages. struct DbgRow { std::string a, b; Rgba color = kVal; }; struct DbgPanelGeometry { int x = 0; int y = 0; int width = 0; int height = 0; int padding = 0; int rowHeight = 0; int valueColumn = 0; }; inline DbgPanelGeometry debug_panel_geometry(const ui::Font& font, const std::string& header, const std::vector& rows, int rightEdge, int top, int minimumBaseWidth = 392, int leftEdge = 8) { const int fontScale = std::max(16, font.height()); const int pad = std::max(6, 6 * fontScale / 16); const int rowHeight = font.height() + std::max(2, 2 * fontScale / 16); const int gap = std::max(12, 12 * fontScale / 16); int labelWidth = 0; int valueWidth = 0; int fullWidth = font.text_width(header); for (const DbgRow& row : rows) { if (row.b.empty()) { fullWidth = std::max(fullWidth, font.text_width(row.a)); } else { labelWidth = std::max(labelWidth, font.text_width(row.a)); valueWidth = std::max(valueWidth, font.text_width(row.b)); } } const int valueOffset = std::max(150 * fontScale / 16, labelWidth + gap); const int requiredWidth = std::max({minimumBaseWidth * fontScale / 16, 2 * pad + fullWidth, 2 * pad + valueOffset + valueWidth}); const int availableWidth = std::max(1, rightEdge - leftEdge); const int width = std::min(requiredWidth, availableWidth); return {std::max(leftEdge, rightEdge - width), top, width, (int(rows.size()) + 1) * rowHeight + pad * 2, pad, rowHeight, valueOffset}; } // Draw a translucent panel of `rows` with `header`, top-left at (px,py). Two-tone: label in blue at // col 1, value in `row.color` at col 2; a row with an empty value is drawn full-width in its colour. inline void draw_panel(Framebuffer& fb, const ui::Font& font, const std::string& header, const std::vector& rows, int px, int py, int w) { const DbgPanelGeometry geometry = debug_panel_geometry(font, header, rows, px + w, py, w, px); const int fh = geometry.rowHeight, pad = geometry.padding; const int col2 = px + pad + geometry.valueColumn; const int h = geometry.height; fb.blend_rect(px, py, w, h, kPanelBg, 210); fb.blend_rect(px, py, w, fh + pad, Rgba{0, 0, 0, 0xFF}, 70); // header strip a touch darker int y = py + pad; font.draw(fb, px + pad, y, header, kHdr); y += fh; for (const auto& r : rows) { if (r.b.empty()) { font.draw(fb, px + pad, y, r.a, r.color); } else { font.draw(fb, px + pad, y, r.a, kKey); font.draw(fb, col2, y, r.b, r.color); } y += fh; } } // The paged HUD. `disasterActive`/`disasterType` come from the front end's DisasterSim (kept decoupled). inline void draw_debug_hud(Framebuffer& fb, const ui::Font& font, const City& city, const DebugSnapshot& s, const DebugUiState& st, const ui::CommentaryState& commentaryState, const ui::CommentaryDecision& commentaryDecision, std::int32_t commentaryDecisionMonth, bool disasterActive, int disasterType, int rightEdge, int py) { std::vector rows; auto kv = [&](std::string k, std::string v, Rgba c = kVal) { rows.push_back({std::move(k), std::move(v), c}); }; auto sec = [&](std::string t) { rows.push_back({std::move(t), "", kHdr}); }; auto onoff = [](bool b) { return b ? std::string("on") : std::string("off"); }; switch (st.hudPage) { case 0: // Sim kv("clock", std::to_string(s.clock)); kv("phase", std::to_string(s.tickPhase) + " " + phase_label(s.tickPhase)); kv("date", std::string(month_abbr(s.month)) + " " + std::to_string(s.year) + " (" + season_name(s.season) + ")"); kv("demand R/C/I", std::to_string(s.demand[0]) + " / " + std::to_string(s.demand[1]) + " / " + std::to_string(s.demand[2])); kv("satNum", std::to_string(s.satNum)); kv("population", std::to_string(10L * city.zone_pop(0))); kv("growth", onoff(s.growthEnabled), s.growthEnabled ? kGood : kDimTxt); kv("finance", onoff(s.financeEnabled), s.financeEnabled ? kGood : kDimTxt); kv("demand", onoff(s.demandEnabled), s.demandEnabled ? kGood : kDimTxt); break; case 1: { // Finance // clang-format off static const char* kRec[16] = {"R tax","C tax","I tax","Ordinances","Debt service","Police","Fire", "Health","Education","Transit","Upkeep10","Upkeep11","Upkeep12","Upkeep13","Upkeep14","Upkeep15"}; kv("funds", "$" + std::to_string(s.funds), s.funds < 0 ? Rgba{0xFF,0x60,0x60,0xFF} : kGood); sec("budget records (value / rate / rev)"); for (int i = 0; i < 16; ++i) kv(kRec[i], std::to_string(s.budget[i].value) + " / " + std::to_string(s.budget[i].rate) + " / " + std::to_string(s.budget[i].revenue)); break; } case 2: { // Services / coverage const FieldStats f = field_stats(city.xfir), p = field_stats(city.xplc); kv("Fire fund rate %", std::to_string(s.budget[6].rate)); kv("Police fund rate %", std::to_string(s.budget[5].rate)); kv("Sum XFIR", std::to_string(s.coverageFireSum), s.coverageFireSum ? kGood : kDimTxt); kv("Sum XPLC", std::to_string(s.coveragePoliceSum), s.coveragePoliceSum ? kGood : kDimTxt); sec("coverage fields (min/avg/max cells)"); kv("XFIR", std::to_string(f.min) + "/" + std::to_string(int(f.avg)) + "/" + std::to_string(f.max) + " " + std::to_string(f.nonzero)); kv("XPLC", std::to_string(p.min) + "/" + std::to_string(int(p.avg)) + "/" + std::to_string(p.max) + " " + std::to_string(p.nonzero)); break; } case 3: { // Fields (heat layers) sec("field min/avg/max active cells"); struct FE { const char* n; FieldStats s; }; // clang-format on const FE fes[] = { {"Crime", field_stats(city.xcrm)}, {"Pollution", field_stats(city.xplt)}, {"LandValue", field_stats(city.xval)}, {"Traffic", field_stats(city.xtrf)}, {"Density", field_stats(city.xpop)}, {"Growth", field_stats(city.xrog)}, }; for (const auto& e : fes) kv(e.n, std::to_string(e.s.min) + "/" + std::to_string(int(e.s.avg)) + "/" + std::to_string(e.s.max) + " " + std::to_string(e.s.nonzero)); sec("displayed-period commute routes"); kv("success / attempts", std::to_string(s.commute.successes) + " / " + std::to_string(s.commute.attempts)); kv("service-off / cost / work", std::to_string(s.commute.stops[static_cast(CommuteRouteStop::ServiceUnavailable)]) + " / " + std::to_string(s.commute.stops[static_cast(CommuteRouteStop::CostLimit)]) + " / " + std::to_string(s.commute.stops[static_cast(CommuteRouteStop::WorkLimit)])); kv("car / bus / rail / subway", std::to_string(s.commute.modeTrips[0]) + " / " + std::to_string(s.commute.modeTrips[1]) + " / " + std::to_string(s.commute.modeTrips[2]) + " / " + std::to_string(s.commute.modeTrips[3])); kv("service efficiency C/B/R/S", std::to_string(s.commuteServiceEfficiency.modeBasisPoints[0]) + " / " + std::to_string(s.commuteServiceEfficiency.modeBasisPoints[1]) + " / " + std::to_string(s.commuteServiceEfficiency.modeBasisPoints[2]) + " / " + std::to_string(s.commuteServiceEfficiency.modeBasisPoints[3])); kv("coverage efficiency P / F", std::to_string(s.publicSafetyServiceEfficiency[0]) + " / " + std::to_string(s.publicSafetyServiceEfficiency[1])); kv("condition crime / fire risk", std::to_string(s.publicSafetyConditionRatings[0]) + " / " + std::to_string(s.publicSafetyConditionRatings[1])); const auto disruption_phase = [](sim::ServiceDisruptionKind kind, const auto& episode) { switch (episode.phase) { case sim::ServiceDisruptionPhase::Stable: return std::string("stable"); case sim::ServiceDisruptionPhase::Warning: return std::string("warning"); case sim::ServiceDisruptionPhase::Active: if (static_cast(kind) < sim::kTransitDisruptionCount) return std::string("active ") + std::to_string(episode.activeIntervals) + "/" + std::to_string( sim::kTransitDisruptionMaximumActiveMonths); return std::string("active ") + std::to_string(episode.activeIntervals) + "/" + std::to_string( sim::kPublicSafetyDisruptionMaximumActiveDays) + "d"; } return std::string("invalid"); }; kv("disruption B / R / S", disruption_phase(sim::ServiceDisruptionKind::Bus, s.serviceDisruptions.episodes[0]) + " / " + disruption_phase(sim::ServiceDisruptionKind::Rail, s.serviceDisruptions.episodes[1]) + " / " + disruption_phase(sim::ServiceDisruptionKind::Subway, s.serviceDisruptions.episodes[2])); kv("disruption P / F", disruption_phase(sim::ServiceDisruptionKind::Police, s.serviceDisruptions.episodes[3]) + " / " + disruption_phase(sim::ServiceDisruptionKind::Fire, s.serviceDisruptions.episodes[4])); break; } case 4: { // Disaster + Things kv("disaster", disasterActive ? std::string(disaster_type_name(disasterType)) + " (type " + std::to_string(disasterType) + ")" : std::string("none"), disasterActive ? Rgba{0xFF, 0x80, 0x40, 0xFF} : kDimTxt); sec("live Things (XTHG: type @ x,y dir)"); int live = 0; for (int i = 1; i < sim::thg::kCount; ++i) { const int type = sim::thing_field(city, i, sim::thg::Type); if (type == 0) continue; ++live; kv("slot " + std::to_string(i), "t" + std::to_string(type) + " @ " + std::to_string(sim::thing_field(city, i, sim::thg::X)) + "," + std::to_string(sim::thing_field(city, i, sim::thg::Y)) + " d" + std::to_string(sim::thing_field(city, i, sim::thg::Dir))); } if (!live) kv("(none active)", "", kDimTxt); break; } case 5: { // Commentary const auto month = [](std::int32_t value) { return value == ui::kCommentMonthUnset ? std::string("unset") : std::to_string(value); }; kv("decision month", month(commentaryDecisionMonth)); kv("last evaluated", month(commentaryState.lastEvaluatedMonth)); kv("last emitted", month(commentaryState.lastEmittedMonth)); kv("next ambient", month(commentaryState.nextAmbientMonth)); kv("sequence", std::to_string(commentaryState.emissionSequence)); kv("block", commentary_block_name(commentaryDecision.blockReason), commentaryDecision.blockReason == ui::CommentaryBlockReason::None ? kGood : kDimTxt); if (commentaryDecision.selection) { const ui::CommentSelection& selected = *commentaryDecision.selection; kv("selected", "rule " + std::to_string(selected.rule.value) + " " + commentary_topic_name(selected.topic), kGood); kv("variant / priority", std::to_string(selected.variant) + " / " + std::to_string(selected.priority)); } else { kv("selected", "-", kDimTxt); } kv("rule roll / weight", std::to_string(commentaryDecision.ruleRoll) + " / " + std::to_string(commentaryDecision.totalWeight)); kv("variant roll", std::to_string(commentaryDecision.variantRoll)); kv("pending cues", std::to_string(commentaryState.pendingCues.size())); kv("active streaks", std::to_string(commentaryState.streaks.size())); kv("rule cooldowns", std::to_string(commentaryState.ruleCooldowns.size())); sec("decision diagnostics (rule IDs; g = failed gate)"); for (const ui::CommentRuleDisposition disposition : { ui::CommentRuleDisposition::Selected, ui::CommentRuleDisposition::Eligible, ui::CommentRuleDisposition::RejectedGate, ui::CommentRuleDisposition::RejectedTrigger, ui::CommentRuleDisposition::RejectedRuleCooldown, ui::CommentRuleDisposition::RejectedTopicCooldown, ui::CommentRuleDisposition::RejectedLowerPriority, ui::CommentRuleDisposition::RejectedInvalidDefinition}) { const std::string ids = commentary_diagnostic_ids(commentaryDecision, disposition, disposition == ui::CommentRuleDisposition::RejectedGate); if (ids != "-") kv(commentary_disposition_name(disposition), ids); } if (commentaryDecision.diagnostics.empty()) kv("(not evaluated)", "cadence or global blocker", kDimTxt); break; } default: { // Log console Logger& lg = Logger::instance(); sec(std::string("log (threshold ") + log_level_name(lg.threshold()) + ", " + std::to_string(lg.size()) + " lines)"); const int show = lg.size() < 22 ? lg.size() : 22; for (int i = lg.size() - show; i < lg.size(); ++i) rows.push_back({lg.line(i), "", kVal}); if (!lg.size()) kv("(empty — F8 raises level; logs at sim seams)", "", kDimTxt); break; } } char fps[24]; std::snprintf(fps, sizeof fps, "%.0f fps", st.fps); const std::string header = std::string("DEBUG ") + hud_page_name(st.hudPage) + " [" + std::to_string(st.hudPage + 1) + "/" + std::to_string(DebugUiState::kPages) + "] " + fps; const DbgPanelGeometry geometry = debug_panel_geometry(font, header, rows, rightEdge, py); draw_panel(fb, font, header, rows, geometry.x, geometry.y, geometry.width); } // A compact legend for the active in-world overlay: name + a low→high swatch + min/avg/max. inline void draw_overlay_legend(Framebuffer& fb, const ui::Font& font, OverlayField f, const FieldStats& st, const render::Palette& pal, int px, int py) { if (f == OverlayField::None) return; const int fh = font.height() + 2, pad = 6, w = 220, h = 2 * fh + 14 + pad * 2; fb.blend_rect(px, py, w, h, kPanelBg, 210); font.draw(fb, px + pad, py + pad, std::string("Overlay: ") + overlay_field_name(f), kHdr); // low→high swatch using the same 156..170 grey heat band the overlay paints. const int sx = px + pad, sy = py + pad + fh + 2, sw = w - 2 * pad; for (int i = 0; i < sw; ++i) { const int idx = 156 + i * 15 / sw; // 156..170 fb.fill_rect(sx + i, sy, 1, 10, pal[static_cast(idx)]); } font.draw(fb, sx, sy + 12, "low", kDimTxt); font.draw(fb, sx + sw - font.text_width("high"), sy + 12, "high", kDimTxt); font.draw(fb, px + pad, py + h - fh - pad + 2, "min/avg/max " + std::to_string(st.min) + "/" + std::to_string(int(st.avg)) + "/" + std::to_string(st.max), kVal); } inline void draw_commute_overlay_legend(Framebuffer& fb, const ui::Font& font, const CommuteRouteHistory& history, int px, int py) { const int fh = font.height() + 2, pad = 6, w = 310, h = 4 * fh + pad * 2; fb.blend_rect(px, py, w, h, kPanelBg, 210); font.draw(fb, px + pad, py + pad, "Commute routes: " + std::to_string(history.accepted().size()) + " accepted, " + std::to_string(history.failed().size()) + " failed", kHdr); const std::array, 4> modes = {{ {"car", CommuteTravelMode::Car}, {"bus", CommuteTravelMode::Bus}, {"rail", CommuteTravelMode::Rail}, {"subway", CommuteTravelMode::Subway}, }}; int x = px + pad; const int modeY = py + pad + fh; for (const auto& [name, mode] : modes) { fb.fill_rect(x, modeY + 2, 10, 8, commute_mode_color(mode)); font.draw(fb, x + 14, modeY, name, kVal); x += 70; } font.draw(fb, px + pad, py + pad + 2 * fh, "dashed grey = access/job leg white dot = destination", kDimTxt); font.draw(fb, px + pad, py + pad + 3 * fh, "failed origin: orange no access, red cost, magenta work", kDimTxt); } // The expanded on-screen tile inspector (F4). `orow,ocol` are ORIGINAL/unrotated tile coords (the caller // maps the hovered view tile back, as the title-bar inspector does). XMIC-per-tile is omitted: the // record→tile mapping isn't pinned in the codebase, and showing a guessed record would be worse than none. inline void draw_tile_inspector_panel(Framebuffer& fb, const ui::Font& font, const City& city, int orow, int ocol, int px, int py) { std::vector rows; auto kv = [&](std::string k, std::string v, Rgba c = kVal) { rows.push_back({std::move(k), std::move(v), c}); }; auto sec = [&](std::string t) { rows.push_back({std::move(t), "", kHdr}); }; const int xbld = city.xbld.at(orow, ocol), xzon = city.xzon.at(orow, ocol); const int alt = city.altm.at(orow, ocol); kv("XTER", std::to_string(city.xter.at(orow, ocol))); kv("XBLD", std::to_string(xbld) + " (" + xbld_band(xbld) + ", " + std::to_string(sim::building_sizes()[std::size_t(xbld)]) + "x)"); kv("XZON", "zone " + std::to_string(xzon & 0x0F) + " corners 0x" + [&] { char b[4]; std::snprintf(b,sizeof b,"%02X",(xzon>>4)&0x0F); return std::string(b); }()); kv("XUND", std::to_string(city.xund.at(orow, ocol))); kv("XTXT", std::to_string(city.xtxt.at(orow, ocol))); kv("XBIT", xbit_flags(std::uint8_t(city.xbit.at(orow, ocol)))); kv("ALTM", "alt " + std::to_string(alt & 0x1F) + (alt & 0x80 ? " +water" : "")); sec("coarse fields here"); kv("crime/poll/value", std::to_string(city.xcrm.at(orow / 2, ocol / 2)) + " / " + std::to_string(city.xplt.at(orow / 2, ocol / 2)) + " / " + std::to_string(city.xval.at(orow / 2, ocol / 2))); kv("traffic", std::to_string(city.xtrf.at(orow / 2, ocol / 2))); kv("police/fire", std::to_string(city.xplc.at(orow / 4, ocol / 4)) + " / " + std::to_string(city.xfir.at(orow / 4, ocol / 4))); kv("density/growth", std::to_string(city.xpop.at(orow / 4, ocol / 4)) + " / " + std::to_string(city.xrog.at(orow / 4, ocol / 4))); for (int i = 1; i < sim::thg::kCount; ++i) { if (sim::thing_field(city, i, sim::thg::Type) == 0) continue; if (sim::thing_field(city, i, sim::thg::X) != orow || sim::thing_field(city, i, sim::thg::Y) != ocol) continue; kv("XTHG here", "slot " + std::to_string(i) + " type " + std::to_string(sim::thing_field(city, i, sim::thg::Type)), kGood); } draw_panel(fb, font, "Tile (" + std::to_string(orow) + ", " + std::to_string(ocol) + ")", rows, px, py, 300); } // Read-only in-world SHIP overlay (F9) — answers both "where's my ship?" and "why isn't there one?": // • every SEAPORT (XBLD 0xE0) is boxed GREEN if a cargo ship can spawn there (a navigable water path // reaches a map edge — the exact `ship_entry_from_seaport` spawn test) or RED if it's land-locked. // No green box anywhere ⇒ no seaport ⇒ build one. (Mirrors the spawn gate, so the verdict is honest.) // • each LIVE cargo ship gets a bright head marker + its breadcrumb trail (cyan, fading old→new) + its // planned A* route (yellow, with pips). A green seaport but no ship marker = the cap-1 ship is just // between spawns. Run with SC2K_NO_SHIP_PATHFIND=1 to watch the trail saw back and forth vs. default. // Everything here is read-only — it never spawns or moves anything. Markers are stored in CANONICAL coords // (sim space), rotated to the current view tile then projected like the field overlay. inline void draw_ship_overlay(Framebuffer& fb, const City& city, int camX, int camY, int rotation, int zoom) { using render::ScreenPos; const int sea = std::clamp(city.water_level(), 0, 31); auto to_screen = [&](int cx, int cy) -> ScreenPos { int vr, vc; render::rotate_index_cw_n(city.dimension(), cx, cy, rotation, vr, vc); const int a = std::max(int(city.altm.at(cx, cy)) & 0x1F, sea); // rendered altitude (water → sea) ScreenPos p = render::tile_to_screen(vr, vc, a, zoom, camX, camY); p.x += 4 << zoom; p.y += 2 << zoom; // top-left anchor → diamond centre return p; }; auto dot = [&](ScreenPos p, Rgba c, int rad, std::uint8_t alpha) { for (int dy = -rad; dy <= rad; ++dy) for (int dx = -rad; dx <= rad; ++dx) if (dx * dx + dy * dy <= rad * rad) fb.blend(p.x + dx, p.y + dy, c, alpha); }; auto box = [&](ScreenPos p, Rgba c, int rad, std::uint8_t alpha) { // filled square (seaport marker) for (int dy = -rad; dy <= rad; ++dy) for (int dx = -rad; dx <= rad; ++dx) fb.blend(p.x + dx, p.y + dy, c, alpha); }; auto line = [&](ScreenPos a, ScreenPos b, Rgba c, std::uint8_t alpha) { // Bresenham, 2px wide int x0 = a.x, y0 = a.y; const int x1 = b.x, y1 = b.y; const int dx = std::abs(x1 - x0), dy = -std::abs(y1 - y0); const int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1; int err = dx + dy; for (;;) { fb.blend(x0, y0, c, alpha); fb.blend(x0 + 1, y0, c, alpha); if (x0 == x1 && y0 == y1) break; const int e2 = 2 * err; if (e2 >= dy) { err += dy; x0 += sx; } if (e2 <= dx) { err += dx; y0 += sy; } } }; const int rad = std::max(1, (1 << zoom) / 2); // Accessibility (green=usable, red=blocked). A dock is usable only if a ship can reach a BERTH — water // beside a PIER — there. A slip sealed off by other piers has no navigable exit to the open sea: it passes // the old "seaport's water touches an edge" test but is truly INACCESSIBLE (user-reported). So flood all // water reachable from a map edge, then: colour each PIER by whether it has an edge-reachable berth beside // it, and each SEAPORT (per cluster) by whether ANY nearby pier does. const Rgba kGreen{0x30, 0xF0, 0x40, 0xFF}, kRed{0xF0, 0x30, 0x30, 0xFF}; const auto reach = sim::ship_accessible_water(city); // size-aware: open water + a few tiles in for (int x = 0; x < city.dimension(); ++x) // piers (0xDF) for (int y = 0; y < city.dimension(); ++y) { if (city.xbld.at(x, y) != 0xDF) continue; const bool ok = sim::pier_has_usable_berth(city, x, y, reach); // reachable berth in a ≥2-wide slip box(to_screen(x, y), ok ? kGreen : kRed, std::max(1, rad - 1), 150); } std::vector seen(static_cast(city.tile_count()), 0); for (int x = 0; x < city.dimension(); ++x) // seaports (0xE0), one verdict per cluster for (int y = 0; y < city.dimension(); ++y) { if (city.xbld.at(x, y) != 0xE0 || seen[city.index(x, y)]) continue; std::vector cluster, q{static_cast(city.index(x, y))}; // BFS the contiguous 0xE0 footprint seen[city.index(x, y)] = 1; bool ok = false; for (std::size_t h = 0; h < q.size(); ++h) { const int cx = q[h] / city.dimension(), cy = q[h] % city.dimension(); cluster.push_back(q[h]); if (!ok && sim::seaport_reachable_berth(city, cx, cy, reach)) ok = true; static const int nx[4] = {1, -1, 0, 0}, ny[4] = {0, 0, 1, -1}; for (int k = 0; k < 4; ++k) { const int ax = cx + nx[k], ay = cy + ny[k]; if (!city.on_map(ax, ay)) continue; const std::size_t kk = city.index(ax, ay); if (!seen[kk] && city.xbld.at(ax, ay) == 0xE0) { seen[kk] = 1; q.push_back(int(kk)); } } } for (int cell : cluster) box(to_screen(cell / city.dimension(), cell % city.dimension()), ok ? kGreen : kRed, rad + 1, 170); } // Live cargo ships: trail + route + a bright head marker so it's findable even before a trail builds. for (int i = 1; i < sim::thg::kCount; ++i) { const std::size_t b = std::size_t(i) * 12; if (city.xthg[b + sim::thg::Type] != 3) continue; const sim::ShipNav& R = sim::ship_nav(i); const std::size_t n = R.trail.size(); for (std::size_t k = 0; k < n; ++k) { // breadcrumb: old dim → new bright const std::uint8_t a = std::uint8_t(40 + 180 * (k + 1) / std::max(1, n)); dot(to_screen(R.trail[k].x, R.trail[k].y), Rgba{0x30, 0xE0, 0xFF, 0xFF}, rad, a); } for (std::size_t k = 1; k < R.wp.size(); ++k) // planned route line(to_screen(R.wp[k - 1].x, R.wp[k - 1].y), to_screen(R.wp[k].x, R.wp[k].y), Rgba{0xFF, 0xE0, 0x30, 0xFF}, 170); for (std::size_t k = 0; k < R.wp.size(); ++k) dot(to_screen(R.wp[k].x, R.wp[k].y), Rgba{0xFF, 0xA0, 0x10, 0xFF}, 2, 220); const ScreenPos head = to_screen(city.xthg[b + sim::thg::X], city.xthg[b + sim::thg::Y]); // the ship itself dot(head, Rgba{0xFF, 0xFF, 0xFF, 0xFF}, rad + 3, 200); dot(head, Rgba{0x30, 0xE0, 0xFF, 0xFF}, rad + 1, 255); } } } // namespace sc2k::debug #endif // SC2K_DEBUG