// Libreopolis front-end entry point — the SDL3 platform shell. This is the ONLY platform-specific code // (see docs/ref/re/reimpl/06-frontend-stack.md for the decision): the pure renderer composites the // city into an RGBA Framebuffer, and SDL2 does nothing but create a window, present that buffer as a // streaming texture, and deliver input. Swapping SDL2 for another backend touches only this file. // // build/libreopolis [CITY.SC2] interactive: drag/arrows/WASD pan, ',' / '.' rotate, Esc quits // build/libreopolis --snapshot out.bmp [CITY] headless render to a 24-bit BMP (no window; CI/agent safe) // --rotate N start at view rotation N (0..3, quarter-turns CW) // // Assets (Win95 LARGE.DAT + PAL_MSTR.BMP) load from the install root (env SC2K_DATA_DIR). #define SDL_MAIN_HANDLED #include #include // SDL_SetMainReady (SDL3 no longer pulls this in via SDL.h) // (Pinch-to-zoom uses SDL3's native SDL_EVENT_PINCH_* — macOS backs it with the trackpad magnify // gesture. The earlier SDL_gesture finger-event reconstruction never fired on macOS, where trackpad // finger events aren't delivered to non-touch windows.) #include #include #include #include #include "audio.hpp" #include "cli.hpp" // headless entry paths: resolve_city / run_snapshot / run_rendercmp / --overlay (Task 4) #include "commands.hpp" // menu/tool command→action dispatch helpers (extracted Task 4) #include "window.hpp" // struct RW — the interactive window state (Task 4 split) #include "view.hpp" // RW view/camera/pick methods (+ centre_camera) #include "dialogs_glue.hpp" // RW dialog-stack / save-load / options methods (+ base_name) #include "events.hpp" // RW tool/preview/editor/input-switch/tick/paint methods #include "debug_ui.hpp" // developer debug HUD / inspector (self-gated by SC2K_DEBUG) #include "gpu_world.hpp" // GPU world path (sprite atlas + quad replay; SDL render API) #include "sc2k/debug/log.hpp" // SC2K_LOG (real under SC2K_DEBUG, a no-op in release) #include "sc2k/config.hpp" // the surviving SC2K_* runtime switches (one place) #include "sc2k/render/overlay_draw.hpp" // in-world field overlay (Fire/Police coverage, …) #include "sc2k/io/sc2_file.hpp" #include "sc2k/io/options_ini.hpp" // app-wide [OPTIONS] persistence (Sound/Music/Speed; the original used the registry) #include "sc2k/render/asset_loader.hpp" #include "sc2k/render/bmp.hpp" // load_bmp — the original's TITLESCR.BMP front-end background #include "sc2k/render/city_renderer.hpp" #include "sc2k/render/sign_layout.hpp" // on-map sign-label geometry #include "sc2k/render/minimap.hpp" #include "sc2k/ui/icons.hpp" // replaceable icon set (assets/icons/.bmp overrides) #include "sc2k/sim/disasters.hpp" #include "sc2k/sim/disaster_sched.hpp" #include "sc2k/sim/things.hpp" #include "sc2k/sim/ordinances.hpp" #include "sc2k/sim/simulation.hpp" #include "sc2k/sim/terrain_gen.hpp" #include "sc2k/sim/terrain_edit.hpp" // editor brushes (stretch) + raise/lower/level #include "sc2k/sim/sea_level.hpp" // editor Raise/Lower Sea Level (reflood) #include "sc2k/sim/network_path.hpp" #include "sc2k/sim/network_commit.hpp" #include "sc2k/sim/neighbors.hpp" // SimNation edge neighbours + map-edge connections #include "sc2k/sim/highway_path.hpp" // faithful 2×2 highway solver + commit (Phase 5) #include "sc2k/sim/highway_bridge.hpp" // over-water highway bridges (styles 5/6) #include "sc2k/sim/inventions.hpp" // invention year-gating + reward/size progression #include "sc2k/sim/military.hpp" // military-base grant flow (ProposeMilitaryBase) #include "sc2k/ui/cursors.hpp" #include "sc2k/ui/data_views.hpp" #include "sc2k/ui/newspaper.hpp" // recent-headlines model + story-id text (Newspaper window 249) #include "sc2k/ui/dialog.hpp" #include "sc2k/ui/drag.hpp" #include "sc2k/ui/editor_panel.hpp" // map-editor random-map generator panel (editor controls) #include "sc2k/ui/font.hpp" #include "sc2k/ui/graph_view.hpp" #include "sc2k/ui/industry_view.hpp" #include "sc2k/ui/menu.hpp" #include "sc2k/ui/pick.hpp" #include "sc2k/ui/power_plants.hpp" #include "sc2k/ui/query.hpp" // Query tool: the tile-info dialog (tool 23) #include "sc2k/ui/rci_gauge.hpp" #include "sc2k/ui/resources.hpp" #include "sc2k/ui/toolbar.hpp" #include "sc2k/ui/tools.hpp" #include #include #include #include #include #include #include #include #include using namespace sc2k; using namespace sc2k::render; using namespace sc2k::app; // extracted front-end helpers (commands.hpp, cli.hpp, …) namespace sc2k::app { // (The hovered tile / footprint is highlighted with the cyan slope-following fill — see the render loop.) // The read-out dialog data-binding (Budget 102, Ordinances 119) lives in ui/data_views.hpp so it can be // unit-tested away from SDL: ui::budget_values / ui::ordinance_values / ui::ordinance_checks / ui::checkbox_bit. // maxFrames > 0 renders that many frames then exits — a headless smoke test of the SDL present path // (run with SDL_VIDEODRIVER=dummy). 0 = run until the user quits. rotation0 = initial view rotation. // Controls: right-drag / arrows / WASD pan · ',' '.' rotate · Ctrl+P/1/2/3/4 speed (Pause/Turtle/Llama/Cheetah/Swallow) · // d toggle live demand · b bulldoze · 1/2/3 zone R/C/I · 4 road · 5 power line · 6 power plant · // 0 none (left-drag pans) · left-click/drag applies the tool · r reset · Esc/q quit. // main() calls this: it builds the window state (RW) and runs the loop. RW::run() — the init + frame-loop // skeleton + teardown — is defined at the bottom of this file; every helper it calls is a method of RW, // defined in view.hpp / dialogs_glue.hpp / events.hpp. int run_window(City city, const CityRenderer& renderer, Palette& animPal, int maxFrames, int rotation0, const std::string& uiShot = "", int openDlg = 0, int openMenu = -1, int openFly = -1, int dbgOverlay = 0, bool dbgHud = false, bool startShell = false, int zoom0 = 2, bool startEditor = false, const std::string& bootPath = "", int hoverR = -1, int hoverC = -1, bool openLayers = false, bool startUnderground = false) { RW w(std::move(city), renderer, animPal, maxFrames, rotation0, uiShot, openDlg, openMenu, openFly, dbgOverlay, dbgHud, startShell, zoom0, startEditor, bootPath); w.hoverCapRow = hoverR; w.hoverCapCol = hoverC; w.layersDialogOpen = openLayers; // --openlayers: pre-open the layers dialog (UI capture) w.undergroundView = startUnderground; // --underground applies to --uishot captures too return w.run(); } int RW::run() { SDL_SetMainReady(); if (!SDL_Init(SDL_INIT_VIDEO)) { std::fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); return 1; } // SDL3: bool audio.open(render::assets_dir() + "/sounds"); // A direct .SC2 argument enters Play here (bypassing load_city_file), so drop the save's stale in-flight // vehicles here too — our spawners regenerate ambient traffic with correct behaviour (see reset_ambient_things). if (!startShell) sc2k::sim::reset_ambient_things(city); win = SDL_CreateWindow("Libreopolis", W, H, SDL_WINDOW_RESIZABLE); // SDL3: no x/y if (win) SDL_SetWindowPosition(win, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); ren = SDL_CreateRenderer(win, nullptr); // SDL3: accelerated by default, no flags/index if (!win || !ren) { std::fprintf(stderr, "SDL window/renderer: %s\n", SDL_GetError()); return 1; } SDL_SetRenderVSync(ren, 1); // SDL3: vsync is set on the renderer, not a creation flag // GPU world path (app/gpu_world.hpp): the default. The world is drawn as textured quads from a // sprite atlas by the SDL render API (Metal here), with the continuous zoom applied on the GPU — // the LARGE bank serves every zoom, replacing the LOD banks and the software area-average scale // pass. `fb` then holds only the UI CHROME on a transparent background, composited over the scaled // world via a premultiplied-alpha texture so it never scales. The pure-software compositor stays // the verification target and the fallback: SC2K_SOFTWARE_RENDER=1, a --uishot capture (it reads // the fully-composited fb), or any texture-creation failure all route back to it. if (!sc2k::config::software_render() && uiShot.empty()) { gpu.emplace(ren, animPal); if (!gpu->ok()) { gpu.reset(); std::fprintf(stderr, "gpu world: atlas texture unavailable — software renderer\n"); } } gpuMode = gpu.has_value(); // ABGR8888 little-endian == our Framebuffer's in-memory {r,g,b,a} byte order, so the upload is a // straight memcpy of pixels(). In GPU mode this texture carries the chrome layer: premultiplied // alpha (Framebuffer::blend accumulates premultiplied coverage) blended over the world. tex = make_tex(W, H); base = Framebuffer(W, H); fb = Framebuffer(W, H); // base = composited city; fb = base + hover overlay // Per-tool mouse cursors, decoded from the original's own cursor art (assets/cursors/*.scur, extract_cursors.py // → ui/cursors.hpp). Created lazily and cached by resource id; a missing file falls back to the system // arrow, so a build without extracted cursors still runs (just with the default pointer). arrowCursor = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); // UI text/dialogs/menu, all from the extracted assets (extract_assets.py). try { uiFont.emplace(render::assets_dir() + "/fonts/system.bmp", render::assets_dir() + "/fonts/system.txt"); } catch (const std::exception& e) { std::fprintf(stderr, "WARNING: UI font failed to load from %s/fonts/system.bmp: %s — UI text will not render\n", render::assets_dir().c_str(), e.what()); } try { dialogs.load(render::assets_dir() + "/ui/dialogs.txt"); } catch (const std::exception& e) { std::fprintf(stderr, "WARNING: dialog templates failed to load from %s/ui/dialogs.txt: %s — in-game dialogs may be unavailable\n", render::assets_dir().c_str(), e.what()); } // SimNation (157) is a control-less owner-draw window: the original's dialog template is a 146×22 stub that // the CWnd resizes to a ~204×160 national-map client at runtime. Give the stub that client // size so our frame + close box + the neighbour layout below all line up. if (ui::Dialog* d = dialogs.edit(157)) { d->w_dlu = 150; d->h_dlu = 104; } // City Map (246): the template's 80×36 listbox (449) can't hold the 12 data views. Widen the window and // grow the listbox into a tall column beside the minimap (445), so every view is one click to select. if (ui::Dialog* d = dialogs.edit(246)) { d->w_dlu = 232; for (auto& c : d->controls) { if (c.id == 448) { c.w = 224; c.h = 250; } // tab-control backdrop spans the wider window if (c.id == 449) { c.x = 150; c.y = 56; c.w = 78; c.h = 132; } // data-view list column, right of the minimap if (c.id == 457) { c.y = 200; c.w = 120; } // "Show on map" checkbox, under the minimap } } // The sub-budget / bonds windows carry a blank template title (the original sets it at runtime). Give // each a caption; the shared service window (184) is re-titled per service when its book button is used. for (auto [id, t] : {std::pair{120, "Taxes"}, {121, "Bonds"}, {183, "Bonds"}, {125, "Education Budget"}, {126, "Transit Budget"}, {184, "Police Budget"}}) if (ui::Dialog* d = dialogs.edit(id)) d->title = t; if (uiFont) { menu.load(render::assets_dir() + "/ui/menus.txt", 3); // the real main game menu (resource id 3) #ifdef SC2K_DEBUG // The Debug menu (cheats + extra disasters) only appears in a debug build — the original gated it // behind a flag as well, so a release menu bar stops at Help. menu.load(render::assets_dir() + "/ui/menus.txt", 223); #endif menu.layout(*uiFont); } if (uiFont) toolMenu.load(render::assets_dir() + "/ui/menus.txt", 136); // MENU 136: tool groups' sub-tools → toolbar flyouts menuH = uiFont ? menu.height(*uiFont) : 0; // The open flyout's sub-tools (MENU 136 items for `flyout`), excluding separators. if (openFly >= 0) flyout = openFly; // --openfly: pre-open a tool-group flyout (capture) // Open a dialog as a NEW top-level window (menu/toolbar): clears any stack, replacing whatever was open. // Open a dialog as a CHILD stacked on the current one (e.g. Bonds from Budget): the parent stays open // underneath and input routes to the child. Dismissing the child returns to the parent. // Dismiss the active dialog: pop back to its parent if stacked, else close the last window. // Is dialog `id` anywhere in the open stack (active or a parent)? if (openDlg) show_dialog_id(openDlg); // --opendlg: pre-open a dialog (UI capture) if (openMenu >= 0) menu.open_top(openMenu); // --openmenu: pre-open a dropdown (UI capture) // The current screen mode (declared early so the toolbar helpers can pick game-vs-editor). A city/ // scenario on the command line boots to Play; a bare launch sits at the front-end shell. cityMode = startShell ? CityMode::None : CityMode::Play; // Floating tool palette, built from BITMAP 2 — the real toolbar shape (a 3-column icon grid in a // titled floating window), sliced + laid out + dispatched per the game's own toolbar dispatcher. In the MAP // EDITOR the game toolbar is replaced by the editor's vertical sidebar (ui::EditorPanel): the generator // controls (Coast/River/sliders/MAKE) over a 2x8 tool grid, whose 16 icons come from BITMAP 207 //, then DONE. We slice the strip with build_grid and hand the icons to the panel. // MODERNISATION master switch (SC2K_CLASSIC_UI=1 reverts to the faithful Win95 shell): the modern // shell re-lays the sidebar (Selector button in; zoom/rotate/Centering/Map/Help out — the map panel // owns navigation) and materialises the replaceable per-icon files in assets/icons/ (ui/icons.hpp). modernPanel = !sc2k::config::classic_ui(); try { palette.build(render::load_ui_bitmap(2)); if (modernPanel) { const std::string iconsDir = render::assets_dir() + "/icons"; std::error_code ec; std::filesystem::create_directories(iconsDir, ec); auto icons = ui::build_icon_set(palette.icons(), iconsDir); ui::export_icon_set(icons, iconsDir); // write any missing override files (never clobbers) palette.rebuild_modern(std::move(icons)); } haveToolbar = palette.ready(); } catch (const std::exception& e) { std::fprintf(stderr, "WARNING: modern UI chrome failed to build: %s — falling back to the classic toolbar\n", e.what()); } // Modern chrome skin: nine-slice art from assets/skin/ (panel/button/button_pressed.bmp — rounded // corners, textures land as plain files, SC3K-style), or the flat NEUTRAL fallback until art exists. std::error_code skinEc; std::filesystem::create_directories(render::assets_dir() + "/skin", skinEc); uiSkin = ui::load_skin(render::assets_dir() + "/skin"); try { edToolbar.build_grid(render::load_ui_bitmap(207), 2, 16); } // editor tool icons catch (const std::exception& e) { std::fprintf(stderr, "WARNING: editor toolbar icons failed to load (ui bitmap 207): %s — the map-editor toolbar will be blank\n", e.what()); } tbY = menuH + 4; // top-left under the menu bar // CONTINUOUS zoom (MODERNISATION): the display scale is 2^zoom · zfrac — `zoom` (0..2) picks the // sprite LOD the world renders at, `zfrac` the compose-time scale between the world layer and the // chrome. DETAIL-FROM-ABOVE: between levels the world renders at the NEXT LOD UP and is bilinearly // DOWNSCALED (zfrac ∈ (0.5, 1]) — fractional zooms are made from higher-resolution art, not a // blowup of the lower bank. Only the top octave (past LOD 2, the classic pixel-doubled "extra // zoom") magnifies (zfrac ∈ (1, 2]). Total range [×1 .. ×8], no zoom levels — just min and max. // --zoom compat: 0..3 → total scale ×1/×2/×4/×8, decomposed the same way scale_view does // (LOD ≥ 1 always: ×1 = the medium bank at ½, not the retired small bank). switch (std::clamp(zoom0, 0, 3)) { case 0: zoom = 1; zfrac = 0.5f; break; case 1: zoom = 1; zfrac = 1.0f; break; case 2: zoom = 2; zfrac = 1.0f; break; case 3: zoom = 2; zfrac = 2.0f; break; } if (auto zf = sc2k::config::test_zoomfrac()) // headless verification hook for --uishot zfrac = std::clamp(*zf, 0.5f, 2.0f); // GPU mode: ONE bank. The world always renders at the LARGE (zoom-2) projection and the continuous // scale is applied per-quad on the GPU, so the whole 2^zoom·zfrac decomposition collapses onto // zoom = 2 with zfrac = total/4 ∈ [0.25 .. 2] — zfrac IS the GPU scale factor `g`, and every piece // of screen↔world math below (pick_at, centring, pan speed, the map-panel diamond) works unchanged. if (gpuMode) { zfrac = std::ldexp(zfrac, zoom - 2); zoom = 2; } rotation = ((rotation0 % 4) + 4) % 4; view = rotate_city(city, rotation); // the rotated layers we draw; recomputed on edit/rotate cam = centre_camera(int(W / zfrac), int(H / zfrac), zoom, view.altm.at(63, 63) & 0x1F); // centre the mid tile, altitude included // Pick the tile under DISPLAY (mx,my): unscale by zfrac into LOD screen space, then map into // zoom-2 space relative to the camera (the projection is linear in the camera-relative offset), // so the zoom-2 pick_tile is exact. This is the single screen→world funnel — every click, hover // and drag goes through it, so the continuous scale never touches the tool/pick math. #ifdef SC2K_DEBUG dbg.hudVisible = dbgHud; // --debughud / --overlay pre-set these (headless capture) if (dbgOverlay > 0 && dbgOverlay < int(debug::OverlayField::Count)) dbg.overlay = debug::OverlayField(dbgOverlay); #else (void)dbgOverlay; (void)dbgHud; #endif // Faithful to manual p.60: emergency units can only be dispatched DURING a disaster, and only one // per provider building (police/fire station; military base — none yet, so Military stays ghosted). sim.set_growth_enabled(true); // let zoned land develop while time runs sim.set_finance_enabled(true); // settle the budget each year (funds move at year-end) sim.set_demand_enabled(liveDemand); // demand responds to development ('d' toggles) sim.set_tech_enabled(true); // run the invention-discovery + reward-milestone clocks // ── Game speed (single setting, faithful to the original's single speed setting) ─────────────── // The original has ONE speed value, not a play/pause flag: 1=Pause 2=Turtle 3=Llama 4=Cheetah // 5=African Swallow. "Paused" is simply value 1, a member of the same menu radio group; each item's // check is SetCheck(speed==n) (the original's menu-update handlers), so exactly one // item is ticked at a time — Pause included. The setting is persisted like the original's INI // [OPTIONS] SPEED key (stored value = simSpeed-1) and restored on every // new/loaded city (the original's new-game reset), defaulting to Pause on first run. // App-wide user options, persisted exactly like the original's registry section OPTIONS (SOUND/MUSIC/ // SPEED — see io/options_ini.hpp). One store, loaded once; each toggle sets its key and flushes, so // saving one option never clobbers another. SOUND/MUSIC are seeded from it further below. // libreopolis.ini lives next to the executable (SDL_GetBasePath = the binary's own directory) — the natural // home for an app-wide config, independent of whatever city/data dir is in use. exeDir = SDL_GetBasePath(); // SDL-owned, process-lifetime; has a trailing separator opts.load(std::string(exeDir ? exeDir : "") + "libreopolis.ini"); simSpeed = load_speed_pref(); set_speed(simSpeed, false); // seed the radio from the persisted speed (overrides the resource's static check) // Annual budget popup (the original's year-rollover budget prompt): at each // fiscal-year rollover, if Auto-Budget is off, the budget window opens MODALLY (the sim pauses while // it's up). We remember the pre-popup speed and restore it when the dialog is dismissed. budgetPopupPrevSpeed = simSpeed; // ── Front-end shell (wCityMode::None) — the original's title screen + the startup dialog ───────────────── // Boot here when no city was given on the command line (the original's screen-state path through the // PRESENTS/TITLE screens to the startup CGameDialog 103, intro videos skipped). A city/scenario file // argument boots straight into Play, exactly like running the original game on a .SC2/.SCN. // (cityMode is declared earlier, before the toolbar helpers.) try { titleBg = render::load_bmp(render::sc2k_root() + "/BITMAPS/TITLESCR.BMP"); } catch (const std::exception& e) { std::fprintf(stderr, "WARNING: title background failed to load from %s/BITMAPS/TITLESCR.BMP: %s — the shell shows a plain background\n", render::sc2k_root().c_str(), e.what()); } // The startup CGameDialog (resource 103) with "Watch WillTV" (117, omitted per request) and the hidden // "Load Tile Set" (116, no WS_VISIBLE) dropped, and "Quit" (115) slid up to fill WillTV's slot so the // five live options sit contiguously. Labels/positions are the original's extracted template. if (const ui::Dialog* d = dialogs.get(103)) { startupDlg = *d; startupDlg.title = "Libreopolis"; startupDlg.h_dlu = 100; // hug the buttons (was 122, leaving WillTV/TileSet space) auto& cs = startupDlg.controls; cs.erase(std::remove_if(cs.begin(), cs.end(), [](const ui::Control& c) { return c.id == 116 || c.id == 117; }), cs.end()); for (auto& c : cs) if (c.id == 115) c.y = 82; // Quit → WillTV's old row (contiguous) } // Where the startup panel's CLIENT top-left sits: the whole panel (title bar + client) centred in the window. // The original drives the sim off REAL-TIME clocks, never once per render frame (RE'd from // the original's timer + idle upkeep + Thing tick): // • a 200 ms master timer (≈5 Hz) gates the growth tick AND the disaster effect-overlay spread // (the original's sim + disaster ticks, both via the same gate; 25 ticks = 1 month); // • moving Things (vehicles, tornado, monster — the original's Thing tick) run off a separate // ~30 ms GetTickCount deadline (≈33 Hz). // At ~60 fps vsync the old per-frame ticks ran the sim ~6× and the fire ~10× too fast. We reproduce both // cadences with wall-clock gates below. Disasters HONOUR pause AND game speed: the effect overlay spreads // at the same speed-scaled rate as the growth tick (Turtle slow … Cheetah fast), and pausing freezes the // whole disaster — effect overlay AND moving Things — both user-confirmed against the original. // ── Ambient/visual animation cadences. ALL wall-clock, NEVER per render frame (measured from the original game, 2026-06-22): // at 60–120 fps vsync the old frame-counter gates ran every one of these 3–24× too fast. Sources: // • Palette cycling = GDI AnimatePalette, driven straight off the 200 ms master-timer handler // (the original's palette-cycle tick): traffic indices 0xAB..+49 step EVERY tick (200 ms); // water 0xE0..+16 steps every 8th tick (`v0 % 8`) = 1600 ms — a slow shimmer, 8× the traffic period, NOT // the same rate. The master timer fires irrespective of game speed, so cars + water keep moving even while // *PAUSED* (the only speed gate in that handler is the growth advance-flag, never the palette flags). // • Ambient vehicles (planes/helis/ships/sailboats/trains) = the Thing tick: a GetTickCount // deadline of +45 ms in a quiet city (+30 ms during disasters), gated only by speed!=Pause, NEVER otherwise // speed-scaled. SimulationDoThingTick steps every live Thing once per fire, so 1 step ≈ 45 ms. // • Tile sprite animation (fire flame frames, airport-strip lights, pump arms, "active"/lit-tile blink) reads // a 4-phase counter (0..3 → bitmask LUT {0x80,0x10,0x20,0x40}) that the sim // map-scan steps once per pass; fire additionally re-rolls `396+(rand()&3)` per repaint. The // original only repaints on sim-invalidation (~5 Hz), so we advance the phase at the 200 ms master rate. // Native modal message boxes — the original gates a few actions behind AfxMessageBox (a blocking OS box): // the tunnel "Engineer's Report" Yes/No, its error popups, and (later) the neighbour-connection prompt. SDL3 // gives us the same native modal via SDL_ShowMessageBox, consistent with the SDL file picker we already use. // ── Document model: the .SC2 this city is bound to, and whether it has unsaved changes ─────────────── // docPath = the file we load from / File→Save overwrites ("" = a never-saved new city). cityDirty latches // on the first sim advance / edit (see mark_dirty) and clears on save/load/new, so quitting only prompts // when there's really something to lose. auto has_sc2_ext = [](const std::string& p) { // case-insensitive ".sc2" tail check if (p.size() < 4) return false; std::string e = p.substr(p.size() - 4); for (char& c : e) c = char(std::tolower(static_cast(c))); return e == ".sc2"; }; // Write the city to `path`, adopt it as the document, clear dirty. Conventional Save semantics: this // OVERWRITES the target file (unlike the old non-destructive saves/ writer). Serializer is round-trip- // exact (test_save). Returns success. // File → Save As — the async native SAVE picker (SDL_ShowSaveFileDialog, sibling of the open picker). // On completion the loop writes the city + adopts the chosen path; saveQuitAfter lets the close flow quit // once the write lands (and treats Cancel as "don't quit"). // File → Save — overwrite the bound file if we have one, else fall back to Save As (a fresh city with no // file picks one, exactly as requested). quitAfter propagates the close flow through the sync/async paths. // Autosave — silently overwrite the bound file (only ever called once docPath is set: "already saved"). // Save-on-close: ask before discarding unsaved changes (the original's "Save changes?" prompt). 3-way // native box → 1 Save / 2 Don't Save / 0 Cancel. // The single quit gate every "close the game" path routes through. At the shell, or with nothing unsaved, // it quits straight away; in a city with unsaved changes it prompts (Save writes then quits — synchronously // to the bound file, or via the async Save-As picker for a never-saved city). // Option toggles live in the menu's own checked-set (single source of truth, seeded from the resource). // (kMonth — the month abbreviations — is a static member of RW.) // Selecting a tool auto-switches the surface/underground view — the rule is the pure // ui::tool_underground_view (faithful to the toolbar dispatcher's tail). Pipes/Subway → // underground; any other surface tool → overground; Bulldoze & the underground-neutral sub-tools leave // it as-is. `group` is the toolbar group index (0..14), `sub` the sub-tool index (MENU-136 order). // Place a CITY (unrotated) tile at the centre of the view — the port's view centring: // rotate it into the current view, then set the scroll so it lands centre-screen *at its altitude* // (origin_centering_tile carries the −(3<height() + 8 : 0; // ── Modern map panel (MODERNISATION, SC3K-style; SC2K_CLASSIC_UI=1 hides it) ───────────────────── // An always-on dock above the status bar: the 128×128 minimap (with the camera's viewport diamond, // click/drag to move the camera — this supersedes the Centering Tool) over a 5-button strip — // zoom −/+, rotate ⟲/⟳ and LAYERS, which pops a picker out above the panel; the selected layer // tints BOTH the live map (draw_mapview_overlay) and the minimap. It reuses the faithful Map-window // machinery (render_minimap + the mapView/mapOverlayOn state that dialog 130's "Show on map" drove); // the floating Map window itself stays available in the Windows menu. kPanelRowH = uiFont ? uiFont->height() + 4 : 13; kPanelBtnH = uiFont ? uiFont->height() + 10 : 18; // Move the camera so the CITY tile under minimap pixel (mx,my) is centred (the minimap is drawn from // the unrotated city: pixel x = tile row, y = tile col — the exact index order of the original's map fill). During a // drag the ALTITUDE is sampled once at the press and held: center_on_tile's per-tile altitude term // made the view bounce vertically with every terrain step the pointer crossed (the reported jiggle). // Which tools paint a CONTINUOUS LINE when dragged (networks / terrain / bulldoze) vs. fill a RECTANGLE // (zoning). Faithful to the originals: the road/rail tools walk a Bresenham line from the press anchor to // the cursor (the original's line stepper), the terrain/bulldoze tools poll the mouse in a tight blocking loop // (never skipping a tile), and the zone tool fills the rectangle from the anchor. // SDL coalesces motion events, so without interpolation a fast drag skips tiles → a dotted, disconnected // network. We interpolate to restore the original's continuous draw. // Apply the active tool at ONE original-grid tile (the caller re-projects once per stroke, not per tile, so // a 50-tile drag is one rotate). Returns true if the tile changed. Building / Power-plant plops carry their // own cost; the bridge dialog is handled by apply_at (it's a single deliberate click, not a paint). // --- Network drag preview (Phase 3): solve on press/motion, commit on release (sim/network_commit.hpp). // Only the five line networks use it; other tools keep the live per-tile paint (faithful — terrain/zone // tools poll/commit live in the original; only the networks preview). A surface net pressed onto a // WATER anchor falls back to apply_at (bridge dialog / live span — bridges land in a later phase). // The route is "complete" only if the solved path actually reaches the tile the user is dragging to — // it stops short at water / a building / an untraversable cliff. We refuse to commit a partial line // (user feedback: don't lay a stub that can't make the whole route) and tint the ghost red when short. // A bridge is auto-spanned when a road/rail/power drag involves water — and (faithful to the original) it is // OFFERED ON RELEASE: you drag across the water, let go, and THEN the Select Bridge dialog appears. This // resolves WHERE the bridge launches from: the first water tile + launch direction. Two cases — the drag // STARTED on water (anchor water; dir chosen from the drag heading via the shoreline gate), or it reached // a shore (the solved land path stopped because the next tile in its heading is water — the original's tail case). // PROBE the crossing net_bridge_target points at, so the preview colour and the release commit agree on // whether a real bridge results. Returns true when a launch candidate exists (fills the probed span `sp` + // its span-gated style `mask`); a genuine bridge additionally needs sp.status==Ok && mask. No mutation. // Offer a SimNation neighbour connection when a road/rail/highway drag ran off a map edge — faithful to // the tail of the original's road/rail/highway tools. `er,ec` = the final placed tile (the block anchor for // highways); `pr,pc` = the previous tile on the path (== er,ec for a single-tile placement); `edgeMax` = // 127 for 1-wide nets, 126 for the 2-wide highway. The trigger is "the next tile in the last segment's // heading is off the map" (a single-tile placement on a border qualifies unconditionally — the original's // start==end clause). On accept, deduct the fee ($1000 road / $1500 rail+highway), stamp the border tile // XTXT 0xFA (250) so its signpost draws the neighbour's name, and count it toward the demand-cap bonus. // --- Highway drag preview (Phase 5): the 2×2-block analogue of the network preview. Solves a faithful // block path (sim/highway_path.hpp) from the even-snapped anchor, ghosts the blocks, commits on release. // Slopes ARE built now (elevated ramps 0x61-0x64) — the path is trimmed only at the first WATER block, so // over-water highway bridges remain the one deferred phase. // Does the even-snapped 2×2 block at (br,bc) touch open water? (any tile XBIT&4) — the bridge trigger. // Look ahead for an over-water crossing implied by the current highway drag, and PROBE it so both the // preview colour and the release commit agree on whether a real bridge will result. Case A: the anchor // block is itself on water → an interactive bridge (dir from the drag heading + the shoreline gate). Case B: // the solved land run stopped at a shore and the next block in its heading is water. Returns true when a // launch candidate exists (fills br/bc/bd + the probed span `sp`); a genuine bridge additionally needs // sp.status==Ok && sp.mask. No mutation — safe to call every frame. // --- Zone painting preview (rectangle): same press/drag/release as networks; commit zones every tile in // the rectangle the zone tool would actually affect (ui::zone_applicable / ui::apply_tool). // Sign tool: pick the clicked tile and open "Enter Sign Text" (162) on it (pre-filled if a sign is // already there, so a second click edits it). // New City dialog "Done": the name is MANDATORY — an empty field keeps the dialog open (a city must be // named, like the original, which won't proceed without one). Otherwise generate the map, stamp the name // (saved as the .SC2 CNAM chunk), and enter Play. // ── Map editor ("Edit New Map") ── // (editor_panel_origin is declared up by the toolbar helpers.) // Grey the game-only menu commands while editing (the original's menu mode-gate). File / Help / // the Map window / Sound / Music stay live; Speed, Options auto-*, Disasters, the data Windows, Newspaper go. // Generate: re-roll the terrain in place from the panel sliders (the original's Generate command). Keeps the // city's name/funds/options — only ALTM/XTER/XBLD-trees/XBIT are regenerated. // Enter the editor. regenerate = a fresh random map (front-end Edit New Map): install the original defaults // (coast off / hills 12 / water 5 / trees 15 / river on) and build a city to edit. regenerate = false // (in-game Edit New Map) keeps the CURRENT city's landscape but RAZES the city itself: the original's // editor bring-up wipes every layer except // terrain, water and trees — zones, buildings, networks, underground, signs, Things, coverage — before // the editor opens (wipe_city_to_terrain). Either way the sim is frozen (paused) and editing is free // (funds restored each frame from edEntryFunds). // Done: leave the editor and open the New City dialog to name the city + pick era/difficulty/funds, then // start the game ON the edited map (the original: editor Done → New City window; a latch keeps the // sculpted terrain). editorMapPending tells commit_new_city to keep the terrain instead of regenerating. // A click on the editor sidebar tool grid (slot 0..15, the original layout order). Persistent brushes set // the highlight (edPanel.activeSlot); momentary actions (sea level, zoom, rotate, help) don't. // On-map sign label for one (already-rotated VIEW) tile. Passed to renderer.render() as its sign hook // so the plaque + post composite INTO `base`, interleaved per-tile with the buildings (the sign draw is // the last op of every DrawTile): a nearer foreground building therefore OCCLUDES a sign behind it, // instead of the old final-pass loop that floated every sign on top of the whole map. Geometry + // 3D bevel are render::sign_layout / render::draw_sign_bevel (faithful to the original's sign draw + bevel). // Keep the Rewards submenu (appended to the Newspaper menu — logical submenu 5, faithful to the original) // in sync with the earned + not-yet-placed reward buildings. Cheap (4-code map scan); recomputed each frame. if (startEditor) enter_map_editor(true); // --editor: boot straight into a fresh map-editor session SDL_StartTextInput(win); // SDL3: text input is per-window (sign-text / new-city editors) for (; running;) { if (maxFrames > 0 && frame >= maxFrames) break; refresh_reward_menu(); // reflect newly-earned / just-placed reward buildings in the menu handle_events(); // The native open picker is async — collect its result once the callback has published one. if (dlg.open && dlg.done.load(std::memory_order_acquire)) { dlg.open = false; if (!dlg.path.empty()) load_city_file(dlg.path); // empty path = the user cancelled } // The native SAVE picker (File→Save As / a new city's first save) — same async handoff. if (savedlg.open && savedlg.done.load(std::memory_order_acquire)) { savedlg.open = false; if (!savedlg.path.empty()) { std::string p = savedlg.path; // ensure a .SC2 extension (the OS box may omit it) if (!has_sc2_ext(p)) p += ".SC2"; const bool ok = write_city_to(p); if (saveQuitAfter && ok) running = false; // save-on-close: quit once the write lands } // Cancelled a save-on-close → the quit is abandoned (stay in the city). saveQuitAfter resets either way. saveQuitAfter = false; } // The active tool's custom cursor over the map; the system arrow over the menu/toolbar/status, a // dialog, or the front-end shell (faithful to the original, which SetCursor()s the tool cursor only // over the city view). `hover.hit` is set only when the mouse is over the map. update_cursor((cityMode != CityMode::None && !showDialog && hover.hit) ? ui::cursor_id_for_tool(tool, (tool == ui::Tool::Building && buildSpec) ? buildSpec->code : 0) : 0); // Continuous keyboard pan (held arrows / WASD) — only in a city, never at the shell. if (cityMode != CityMode::None) { const bool* ks = SDL_GetKeyboardState(nullptr); // SDL3: const bool* (was const Uint8*) const int step = std::max(1, int(24 / zfrac)); // display-consistent speed at any scale int dx = (ks[SDL_SCANCODE_LEFT] || ks[SDL_SCANCODE_A]) - (ks[SDL_SCANCODE_RIGHT] || ks[SDL_SCANCODE_D]); int dy = (ks[SDL_SCANCODE_UP] || ks[SDL_SCANCODE_W]) - (ks[SDL_SCANCODE_DOWN] || ks[SDL_SCANCODE_S]); if (dx || dy) { cam.x += dx * step; cam.y += dy * step; baseDirty = true; } // Two-finger pan: ease half the pending target onto the camera each frame (vsync-locked). // This low-passes the trackpad's bursty wheel events into steady per-frame motion; the tail // under ~a pixel is applied outright so a glide ends crisply instead of asymptotically. if (panPendX != 0.f || panPendY != 0.f) { float sx = panPendX * 0.5f, sy = panPendY * 0.5f; if (std::fabs(panPendX) < 2.f) sx = panPendX; if (std::fabs(panPendY) < 2.f) sy = panPendY; const int ix = int(std::lround(sx)), iy = int(std::lround(sy)); panPendX -= float(ix); panPendY -= float(iy); if (std::fabs(panPendX) < 0.5f) panPendX = 0.f; if (std::fabs(panPendY) < 0.5f) panPendY = 0.f; if (ix || iy) { cam.x += ix; cam.y += iy; baseDirty = true; } } } audio.update_music(); // advance the MIDI playlist when a track ends (plays even when paused) advance_sim(); advance_disaster(); const std::vector decals = advance_animation(); paint(decals); SDL_UpdateTexture(tex, nullptr, fb.pixels().data(), W * 4); SDL_RenderClear(ren); if (gpuMode && cityMode != CityMode::None) { gpu->sync_palette(); // traffic/water/badge palette cycles → atlas rect re-uploads gpu->replay(zfrac, float(cam.x), float(cam.y), W, H); // the world, scaled on the GPU } SDL_RenderTexture(ren, tex, nullptr, nullptr); // SDL3: SDL_RenderCopy → SDL_RenderTexture (float rects) SDL_RenderPresent(ren); SDL_Delay(1); ++frame; } if (maxFrames > 0) { // headless capture: report the final top-level state (scriptable) std::printf("frontend: mode=%s date=%s %d funds=%d\n", cityMode == CityMode::None ? "shell" : cityMode == CityMode::Disaster ? "disaster" : cityMode == CityMode::Editor ? "editor" : "play", kMonth[sim.month()], sim.year(), city.funds()); std::printf("options: disasters=%s autoBudget=%s autoGoto=%s (MISC noDis@0x1000=%d budget@0xFF0=%d goto@0xFF4=%d)\n", disastersEnabled ? "on" : "OFF", menu.is_checked(32772) ? "on" : "off", menu.is_checked(32773) ? "on" : "off", city.misc_be32(sc2k::misc::kNoDisasters), city.misc_be32(sc2k::misc::kAutoBudget), city.misc_be32(sc2k::misc::kAutoGoto)); std::printf("options: sound=%s music=%s speed=%d (INI SOUND=%d MUSIC=%d SPEED=%d @ %s)\n", soundOn ? "on" : "off", musicOn ? "on" : "off", int(simSpeed), opts.get("SOUND", -1), opts.get("MUSIC", -1), opts.get("SPEED", -1), opts.path().c_str()); std::printf("document: path=%s dirty=%d autosaveYears=%d yearsSinceFounding=%d\n", docPath.empty() ? "(unsaved)" : docPath.c_str(), cityDirty ? 1 : 0, autosaveYears, sim.clock() / 300); } audio.close(); // tear down the mixer BEFORE SDL_Quit frees the audio subsystem SDL_SetCursor(arrowCursor); // detach any custom cursor before destroying them for (auto& [id, cur] : toolCursorCache) if (cur) SDL_DestroyCursor(cur); if (arrowCursor) SDL_DestroyCursor(arrowCursor); SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return 0; } // ── RW method definitions (moved from run(), Task 4 C2) ── SDL_Texture* RW::make_tex(int w, int h) { SDL_Texture* t = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, w, h); if (t && gpuMode) SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND_PREMULTIPLIED); return t; } SDL_Cursor* RW::tool_cursor(int id) { if (id <= 0) return arrowCursor; auto it = toolCursorCache.find(id); if (it != toolCursorCache.end()) return it->second ? it->second : arrowCursor; SDL_Cursor* cur = nullptr; const ui::CursorImage img = ui::load_cursor(render::assets_dir() + "/cursors/cur_" + std::to_string(id) + ".scur"); if (img.ok()) { // SDL copies the pixels in, so the surface/img can be freed straight after SDL_Surface* s = SDL_CreateSurfaceFrom(img.w, img.h, SDL_PIXELFORMAT_RGBA32, const_cast(img.rgba.data()), img.w * 4); if (s) { cur = SDL_CreateColorCursor(s, img.hotX, img.hotY); SDL_DestroySurface(s); } } toolCursorCache[id] = cur; // cache even null → never re-stat a missing file return cur ? cur : arrowCursor; } void RW::update_cursor(int wantId) { if (wantId == shownCursorId) return; shownCursorId = wantId; SDL_SetCursor(tool_cursor(wantId)); } } // namespace sc2k::app int main(int argc, char** argv) { std::string snapshot, cityArg, uiShot; int hoverR = -1, hoverC = -1; int frames = 0; // >0: render N frames then exit (headless smoke test of the window path) int rotation = 0; // initial view rotation (0..3), quarter-turns CW bool rotateSet = false; // --rotate given → override the save's own compass int initZoom = 2; // --zoom N: initial view zoom (0 far … 2 large … 3 extra/closest); for capture/verify bool underground = false; // --underground: render the snapshot in the x-ray pipes/subway view int openDlg = 0; // --opendlg ID: pre-open a dialog (for UI capture / verification) int openMenu = -1; // --openmenu N: pre-open dropdown N (for UI capture / verification) int openFly = -1; // --openfly G: pre-open tool-group G's flyout (for UI capture / verification) bool openLayers = false; // --openlayers: pre-open the View City Layers dialog (for UI capture / verification) int dbgOverlay = 0; // --overlay NAME|N: pre-select a debug field overlay (SC2K_DEBUG build) bool dbgHud = false; // --debughud: open the debug HUD on launch (SC2K_DEBUG build) bool forceShell = false;// --shell: start at the front-end shell even for a windowed capture bool startEditor = false;// --editor: boot straight into the map editor (a fresh generated map) bool renderCmp = false; // --rendercmp: numerically diff the GPU world path vs the software compositor for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--snapshot") == 0 && i + 1 < argc) snapshot = argv[++i]; else if (std::strcmp(argv[i], "--frames") == 0 && i + 1 < argc) frames = std::atoi(argv[++i]); else if (std::strcmp(argv[i], "--rotate") == 0 && i + 1 < argc) { rotation = std::atoi(argv[++i]); rotateSet = true; } else if (std::strcmp(argv[i], "--zoom") == 0 && i + 1 < argc) initZoom = std::atoi(argv[++i]); else if (std::strcmp(argv[i], "--underground") == 0) underground = true; // x-ray snapshot else if (std::strcmp(argv[i], "--uishot") == 0 && i + 1 < argc) { uiShot = argv[++i]; if (frames == 0) frames = 6; } else if (std::strcmp(argv[i], "--hover") == 0 && i + 1 < argc) { std::sscanf(argv[++i], "%d,%d", &hoverR, &hoverC); // fixed-tile hover highlight (oracle capture) } else if (std::strcmp(argv[i], "--opendlg") == 0 && i + 1 < argc) openDlg = std::atoi(argv[++i]); else if (std::strcmp(argv[i], "--openmenu") == 0 && i + 1 < argc) openMenu = std::atoi(argv[++i]); else if (std::strcmp(argv[i], "--openfly") == 0 && i + 1 < argc) openFly = std::atoi(argv[++i]); else if (std::strcmp(argv[i], "--openlayers") == 0) { openLayers = true; if (frames == 0) frames = 6; } else if (std::strcmp(argv[i], "--debughud") == 0) { dbgHud = true; if (frames == 0) frames = 6; } else if (std::strcmp(argv[i], "--overlay") == 0 && i + 1 < argc) { dbgOverlay = overlay_index_from_arg(argv[++i]); if (frames == 0) frames = 6; } else if (std::strcmp(argv[i], "--shell") == 0) forceShell = true; // force the front-end shell (capture via --uishot) else if (std::strcmp(argv[i], "--editor") == 0) { startEditor = true; if (frames == 0) frames = 6; } // boot the map editor else if (std::strcmp(argv[i], "--rendercmp") == 0) renderCmp = true; // GPU-vs-software pixel verification else cityArg = argv[i]; } // Boot straight into a city OR sit at the front-end shell — faithful to the original, which opens // its startup dialog unless a .SC2/.SCN was passed on the command line. We need a city loaded up front // when: a path was given, a --snapshot was requested (it always renders a city), or a --uishot capture // wants the in-game UI (no --shell). A bare `sc2k` (or `--shell`) starts at the shell with no city. const bool needCity = (!cityArg.empty() || !snapshot.empty() || renderCmp || (!uiShot.empty() && !forceShell)) && !startEditor; City city; std::string cityPath; // the file the city was loaded from (its document path) if (needCity) { cityPath = resolve_city(cityArg); if (cityPath.empty()) { std::fprintf(stderr, "usage: sc2k [--snapshot out.bmp] [--shell] [CITY.SC2|SCENARIO.SCN]\n" "(no city given and none found under %s/CITIES)\n", sc2k_root().c_str()); return 2; } if (const auto lr = io::load_sc2(cityPath, city); !lr.ok) { std::fprintf(stderr, "load %s: %s\n", cityPath.c_str(), lr.error.c_str()); return 1; } sc2k::sim::repair_neighbors_if_uninitialized(city); // seed edge neighbours for pre-feature / uninitialised saves sc2k::repair_city_header(city); // repair MISC header from early port saves: 0x1C class (else demand jams) + 0x04 wCityMode (else the real game opens it in map-editor mode) ui::detail::repair_power_plant_corners(city); // re-stamp XZON corner bits on plants saved without them (blank in the real game) sc2k::sim::repair_inventions_if_unseeded(city); // re-seed invention years for early port saves written all-zero (else year-gating can't engage) // Odd-compass saves store building mirror bits inverted — normalize to the compass-0 convention // and (unless --rotate asked for a specific view) open facing the saved compass, like the original. const int savedCompass = sc2k::normalize_save_compass(city); if (!rotateSet) rotation = savedCompass; std::printf("loaded %s (\"%s\", saved compass %d)\n", cityPath.c_str(), city.name.c_str(), savedCompass); } else { std::printf("no city given — starting at the front-end shell (title screen)\n"); } Assets assets; try { assets = load_assets(); } catch (const std::exception& ex) { std::fprintf(stderr, "assets: %s\n(set SC2K_DATA_DIR to your game install root)\n", ex.what()); return 1; } Palette animPal = assets.palette; // a mutable copy the renderer references, so the CityRenderer renderer(assets.bank, animPal); // traffic/water palette-cycle animation can drive it if (renderCmp) return run_rendercmp(city, renderer, animPal); // Snapshot path always renders the loaded city; the window path starts at the shell iff no city was loaded. return snapshot.empty() ? run_window(city, renderer, animPal, frames, rotation, uiShot, openDlg, openMenu, openFly, dbgOverlay, dbgHud, !needCity, initZoom, startEditor, cityPath, hoverR, hoverC, openLayers, underground) : run_snapshot(city, renderer, snapshot, rotation, underground); }