// 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 merge locally extracted classic files with project-authored loose-file overrides. #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/i18n.hpp" // string catalogs (assets/lang) — loaded before any UI is built #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/city_renderer.hpp" #include "sc2k/render/sign_layout.hpp" // on-map sign-label geometry #include "sc2k/render/minimap.hpp" #include "sc2k/render/pixel_change_tracker.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/dialog.hpp" #include "sc2k/ui/drag.hpp" #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/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 through the semantic Budget and Ordinance summaries. // 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, Assets assets, std::string terrainStyle, 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, int queryR = -1, int queryC = -1, io::NativeCityDocument bootDocument = {}, bool bootClassicImport = false, bool gpuUiShot = false, std::string localeOverride = {}, int dataLayer = -1) { RW w(std::move(city), std::move(assets), std::move(terrainStyle), maxFrames, rotation0, uiShot, openDlg, openMenu, openFly, dbgOverlay, dbgHud, startShell, zoom0, startEditor, bootPath, std::move(bootDocument), bootClassicImport, gpuUiShot, std::move(localeOverride)); w.hoverCapRow = hoverR; w.hoverCapCol = hoverC; w.queryCapRow = queryR; w.queryCapCol = queryC; w.layersDialogOpen = openLayers; // --openlayers: pre-open the layers dialog (UI capture) w.undergroundView = startUnderground; // --underground applies to --uishot captures too if (dataLayer >= 0) { w.mapView = dataLayer; w.mapOverlayOn = true; // --layer: release map/minimap overlay + legend } return w.run(); } int RW::run() { if (!startShell && !milestone4RuntimeReady) { std::fprintf(stderr, "Milestone 4 continuation state could not be activated; refusing to enter Play\n"); return 1; } SDL_SetMainReady(); if (!SDL_Init(SDL_INIT_VIDEO)) { std::fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); return 1; } // SDL3: bool audio.open(render::classic_assets_dir() + "/sounds"); // Direct native boots have already restored THNG in RW's owner. Classic/pre-THNG documents cross // the explicit sanitize/reset migration boundary before that owner is constructed. SDL_PropertiesID windowProps = SDL_CreateProperties(); SDL_SetStringProperty(windowProps, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "Libreopolis"); SDL_SetNumberProperty(windowProps, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, W); SDL_SetNumberProperty(windowProps, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, H); SDL_SetBooleanProperty(windowProps, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); SDL_SetBooleanProperty(windowProps, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true); win = SDL_CreateWindowWithProperties(windowProps); SDL_DestroyProperties(windowProps); 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; } pixelDensity = std::max(1.f, SDL_GetWindowPixelDensity(win)); SDL_GetWindowSizeInPixels(win, &W, &H); // all rendering uses native drawable pixels const bool vsyncEnabled = SDL_SetRenderVSync(ren, 1); // SDL3: renderer property, 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, an ordinary --uishot capture // (which reads the fully-composited fb), or any texture-creation failure all route back to it. // --uishot-gpu is the explicit full-composition parity probe and must never silently fall back. if (!sc2k::config::software_render() && (uiShot.empty() || gpuUiShot)) { gpu.emplace(ren, animPal); if (!gpu->ok()) { gpu.reset(); std::fprintf(stderr, "gpu world: atlas texture unavailable — software renderer\n"); } } gpuMode = gpu.has_value(); if (gpuUiShot && !gpuMode) { std::fprintf(stderr, "--uishot-gpu: SDL texture-command world path unavailable\n"); audio.close(); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return 1; } if (gpuMode) gpuSigns.emplace(ren); // 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 classic art or supplied as project-authored PNGs (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: the bundled vector face (assets/fonts/, ours — not an extracted resource). try { uiFont.emplace(render::assets_dir() + "/fonts/NotoSans-Regular.ttf"); } catch (const std::exception& e) { std::fprintf(stderr, "WARNING: UI font failed to load from %s/fonts/NotoSans-Regular.ttf: %s — UI text will not render\n", render::assets_dir().c_str(), e.what()); } reload_sign_font(); reload_industry_font(); #ifdef SC2K_DEBUG reload_debug_font(); #endif // App-wide user options (SOUND/MUSIC/AUTOSAVE — // see io/options_ini.hpp; string-valued LANGUAGE is ours). libreopolis.ini lives next to the // executable (SDL_GetBasePath = the binary's own directory). Loaded before any UI is built: the // persisted LANGUAGE decides which string catalog the menus resolve their keys against. exeDir = SDL_GetBasePath(); // SDL-owned, process-lifetime; has a trailing separator opts.load(std::string(exeDir ? exeDir : "") + "libreopolis.ini"); if (opts.erase("SPEED")) opts.save(); // retire the old global pace preference from existing installs // String catalogs: menu (and, as they migrate, dialog) texts are keys resolved at build time, so the // catalogs load before any UI is built. A missing catalog is not fatal — tr() then shows the raw // keys, which is deliberately visible rather than silently blank. if (!i18n::load_locale(render::assets_dir() + "/lang", "en")) std::fprintf(stderr, "WARNING: string catalog %s/lang/en.txt not found — UI text will show raw keys\n", render::assets_dir().c_str()); const std::string lang = localeOverride.empty() ? opts.get_str("LANGUAGE", "en") : localeOverride; if (lang != "en" && !i18n::load_locale(render::assets_dir() + "/lang", lang)) { if (!localeOverride.empty()) { std::fprintf(stderr, "--language: catalog '%s' not found in %s/lang\n", lang.c_str(), render::assets_dir().c_str()); return 1; } std::fprintf(stderr, "WARNING: LANGUAGE=%s has no catalog in %s/lang — using English\n", lang.c_str(), render::assets_dir().c_str()); } // RmlUi owns the application chrome and windows. The migration is complete enough that silently // dropping back to the retired classic engines would now expose a materially different interface; // fail startup visibly instead if the required UI runtime cannot initialise. rml = std::make_unique(); if (!rml->init(ren, win, W, H)) { std::fprintf(stderr, "ERROR: required RmlUi layer failed to initialise\n"); return 1; } rml->set_minimap_callbacks( [this](Framebuffer& surface) { paint_rml_hud_surface(surface); }, [this](float u, float v, bool start) { minimap_goto(u, v, start); }); rml->open_hud(); // persistent city instruments + status ticker rml->open_toolbox(); // persistent tool-family launcher rml->open_editor(); // dedicated new-map workspace if (uiFont) { menu.build_builtin(3); // the main menu bar (ui/menu_defs.hpp) menu.layout(*uiFont); } if (uiFont) toolMenu.build_builtin(136); // tool groups' sub-tools → toolbar flyouts refresh_language_menu(); // Options → the language list (one radio item per catalog) menuH = 0; // The open flyout's sub-tools (MENU 136 items for `flyout`), excluding separators. if (openFly >= 0) { if (rml) { if (openFly >= 0 && openFly < 9) { if (openFly == 8) rmlDebugMenuOpen = true; else rmlSidebarMenu = openFly; rml->toolbox_set_class("side-menu-" + std::to_string(openFly), "hidden", false); } } else { flyout = openFly; } } // 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. Finance 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 && (openDlg < 490 || openDlg > 495)) show_dialog_id(openDlg); // --opendlg: pre-open a dialog (UI capture) if (city.on_map(queryCapRow, queryCapCol)) { const int demand[3] = {city.demand(0), city.demand(1), city.demand(2)}; queryInfo = ui::build_query(city, queryCapRow, queryCapCol, demand, terrainWorldCache ? &*terrainWorldCache : nullptr, nativeDocument.regionalState ? std::span(nativeDocument.regionalState->connections) : std::span(), sim.commute_route_config()); if (queryInfo.queryable && rml->open_document("query")) { queryOpen = true; refresh_rml_query(); } } // --openmenu: pre-open a dropdown (UI capture). open_top refuses an out-of-range index (see menu.hpp), // so a bad id can't index tops_ out of bounds; catch the refusal here and fail the capture cleanly and // DETERMINISTICALLY — a non-zero exit with no BMP written — rather than emitting a misleading bare-bar // frame that the refactor oracle would silently record as this menu. bool menuArgInvalid = false; if (openMenu >= 0) { menu.open_top(openMenu); if (!menu.is_open()) { std::fprintf(stderr, "--openmenu %d: no such top-level menu (valid indices 0..%d)\n", openMenu, int(menu.tops().size()) - 1); menuArgInvalid = true; } } // 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 : bootClassicImport ? CityMode::Setup : !milestone4RuntimeReady ? CityMode::Setup : (disaster.active || prevDisasterActive) ? CityMode::Disaster : CityMode::Play; if (cityMode == CityMode::Play) reset_city_wire_notifications(); if (openDlg >= 490 && openDlg <= 495) show_dialog_id(openDlg); // fixtures require the post-reset live store // 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 // In EDITOR mode the game toolbar is replaced by the persistent RML terrain workspace. // The sidebar re-lays around the map panel (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). try { palette.build(render::load_ui_bitmap(2)); 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: UI chrome failed to build: %s\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"); 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); // ONE close sprite bank for both renderers. Collapse the compatibility --zoom decomposition onto // the large (zoom-2) projection with zfrac = total/4 ∈ [0.25 .. 2]. GPU replay scales each quad; // software renders the same close art to its world buffer and scales the composed result. zfrac = std::ldexp(zfrac, zoom - 2); zoom = 2; zfrac *= pixelDensity; // retain the same apparent world scale at native density rotation = ((rotation0 % 4) + 4) % 4; reproject(); // builds the rotated layers and their semantic terrain cache const int centreTile = (city.dimension() - 1) / 2; const int centreAltitude = render::TerrainRenderView(view, terrainViewCache ? &*terrainViewCache : nullptr) .tile(centreTile, centreTile) .base_height; const Camera centeredCamera = centre_camera(int(W / zfrac), int(H / zfrac), city.dimension(), zoom, centreAltitude); set_camera_position(centeredCamera.x, centeredCamera.y); // 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 (void)refresh_regional_context(); if (nativeDocument.powerTopologyRepairedOnLoad) { sim.recompute_power_delivery(); nativeDocument.powerTopologyRepairedOnLoad = false; } // ── Game speed ─────────────────────────────────────────────── // Pace belongs to the active document session. Startup and every document transition pause the // simulation; the first Play resumes at Turtle. Pausing within one city retains its selected pace. reset_speed_for_document(); // ── 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.) // The startup CGameDialog (resource 103), customised in rebuild_startup_dialog (shared with the // language switch, which re-derives it from the freshly relabelled set). if (rml && cityMode == CityMode::None) rml->open_document("startup"); if (bootClassicImport) { const std::string sourcePath = docPath; docPath.clear(); begin_classic_import(sourcePath, city, true); } // 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 (`tick % 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. // Confirmation workflows are progressively moving to the stacked RmlUi modal service. The asynchronous // platform file picker remains native; informational alerts already use in-game chrome throughout. // ── Document model: the native city file this session 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. // 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 // in-game modal → Save / Don't Save / 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; // ── Map panel (always-on dock above the status bar) ────────────────────────────────────────────── // An always-on dock above the status bar: the fixed-size 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 render_minimap + // mapView/mapOverlayOn machinery that the retired City Map window (dialog 246) used to drive. 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` = // dimension-1 for 1-wide nets, dimension-2 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 valid setup // advances to the terrain editor on the already-generated canonical map; accepting that terrain starts play. // ── New-city terrain editor ── // 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, and data windows go. // Generate: re-roll the canonical terrain from the centre/edge recipe and three amount controls. The // fixed compatibility surface arrays are derived for the current renderer; other editor state is retained. // The legacy direct-editor route can still create a fresh recipe or keep the current landscape while // razing the city itself. The latter 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). // In the normal New City flow, Accept starts the city on the edited map. The retained direct-editor route // opens setup after Accept because it began without a city name or difficulty selection. // 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 + // presentation are shared by render::sign_layout / render::draw_sign_plaque / render::draw_sign_post. 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) render::PixelChangeTracker chromeUploadTracker; Uint64 previousViewMotionNs = SDL_GetTicksNS(); for (; running && !menuArgInvalid;) { // a refused --openmenu id skips the loop entirely: no capture, clean error above if (maxFrames > 0 && frame >= maxFrames) break; const Uint64 viewMotionNs = SDL_GetTicksNS(); const double viewElapsedSeconds = std::clamp( double(viewMotionNs - previousViewMotionNs) / 1'000'000'000.0, 0.0, 0.05); previousViewMotionNs = viewMotionNs; 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. complete_save_dialog(); apply_ui_resume_speed_policy(); // The selected tool owns the playable canvas; any hit-tested persistent UI surface, including // panel backgrounds and icon children, owns the system arrow. Modal documents own it everywhere. update_cursor(ui::cursor_id_for_context(tool, (tool == ui::Tool::Building && buildSpec) ? buildSpec->code : 0, cityMode != CityMode::None, rml->document_open() || rml->hovering_ui_surface())); // Continuous keyboard pan (held arrows / WASD) — only in a city, never at the shell, and never // while the keyboard is captured by a text field or a modal dialog (typing a name must not pan; // W/A/S/D are letters too). This is a per-frame HELD-KEY poll, so consuming the key event isn't // enough — it has to be gated here as well. const bool keyboardCaptured = rml->document_open() || stadiumDlg.open; if (cityMode != CityMode::None && !keyboardCaptured) { const bool* ks = SDL_GetKeyboardState(nullptr); // SDL3: const bool* (was const Uint8*) 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) { constexpr double kKeyboardPanPixelsPerSecond = 1440.0; // former 24 px/frame speed at 60 Hz move_camera(dx * kKeyboardPanPixelsPerSecond * viewElapsedSeconds / zfrac, dy * kKeyboardPanPixelsPerSecond * viewElapsedSeconds / zfrac); } advance_view_motion(viewElapsedSeconds); } else if (keyboardCaptured) { viewMotion.cancel_pan(); viewMotion.cancel_zoom(std::ldexp(double(zfrac), zoom)); } audio.update_music(); // advance the MIDI playlist when a track ends (plays even when paused) advance_sim(); advance_disaster(); advance_city_wire(); apply_ui_resume_speed_policy(); // capture City Wire dialogs opened after this frame's simulation step const std::vector decals = advance_animation(); paint(decals); const render::PixelChangeRect chromeChanges = chromeUploadTracker.update(fb.pixels(), W, H); if (chromeChanges) { const SDL_Rect changed{chromeChanges.x, chromeChanges.y, chromeChanges.width, chromeChanges.height}; const render::Rgba* pixels = fb.pixels().data() + static_cast(changed.y) * W + changed.x; SDL_UpdateTexture(tex, &changed, pixels, 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, camera_x(), camera_y(), W, H, activeObjectHighlight); // subpixel camera motion on the GPU } SDL_RenderTexture(ren, tex, nullptr, nullptr); // SDL3: SDL_RenderCopy → SDL_RenderTexture (float rects) if (rml) { const bool cityChrome = (cityMode == CityMode::Play || cityMode == CityMode::Disaster) && rml->open_document_name() != "new_city"; rml->show_hud(cityChrome); rml->show_toolbox(cityChrome); rml->show_editor(cityMode == CityMode::Editor); refresh_rml_budget(); // live finance values when that document is open refresh_rml_ordinances(); refresh_rml_finance_history(); refresh_rml_settings(); refresh_rml_hud(); refresh_rml_toolbox(); refresh_rml_editor(); rml->update(); // update data bindings and custom element boxes rml->render(); // custom minimap renders in normal document order SDL_SetRenderViewport(ren, nullptr); // the backend may leave its final element's state active SDL_SetRenderClipRect(ren, nullptr); paint_rml_surface(); // owner-drawn content into the open document // Headless capture with the layer active: the classic path snapshots `fb`, which the // RmlUi pass never touches — read the presented frame back off the renderer instead. if (!uiShot.empty() && maxFrames > 0 && frame == maxFrames - 1) { const SDL_Rect captureRect{0, 0, W, H}; if (SDL_Surface* shot = SDL_RenderReadPixels(ren, &captureRect)) { SDL_SaveBMP(shot, uiShot.c_str()); SDL_DestroySurface(shot); } } } SDL_RenderPresent(ren); if (!vsyncEnabled) SDL_Delay(1); ++frame; } if (maxFrames > 0) { // headless capture: report the final top-level state (scriptable) std::printf("display: pixels=%dx%d density=%.2f\n", W, H, pixelDensity); std::printf("frontend: mode=%s date=%s %d funds=%d\n", cityMode == CityMode::None ? "shell" : cityMode == CityMode::Disaster ? "disaster" : cityMode == CityMode::Editor ? "editor" : cityMode == CityMode::Setup ? "setup" : "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-selected=%d speed-effective=%d ui-suspended=%d (session only) (INI SOUND=%d MUSIC=%d @ %s)\n", soundOn ? "on" : "off", musicOn ? "on" : "off", int(selectedSpeed), int(effective_speed()), ui_temporarily_pauses_simulation() ? 1 : 0, opts.get("SOUND", -1), opts.get("MUSIC", -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); } if (rmlSurfTex) SDL_DestroyTexture(rmlSurfTex); if (rml) rml->shutdown(); // release RmlUi's SDL textures before the renderer goes 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); gpuSigns.reset(); // release renderer-owned sign textures before the renderer gpu.reset(); // likewise release the world atlas while its renderer is live SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return menuArgInvalid ? 2 : 0; // a refused --openmenu id is a clean, deterministic failure } // ── 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; ui::CursorImage img; for (const std::string& layer : {render::assets_dir(), render::classic_assets_dir()}) { img = ui::load_cursor_from_directory(layer + "/cursors", id); if (img.ok()) break; } 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) { SDL_Cursor* wanted = tool_cursor(wantId); // RmlUi swaps SDL's cursor while a button/text field is hovered. Its cursor objects are independent // of this cache, so the remembered id can still match while SDL is actually showing RmlUi's arrow. // Compare the real SDL cursor as well and reclaim it on the next frame after leaving the control. if (wantId == shownCursorId && SDL_GetCursor() == wanted) return; shownCursorId = wantId; SDL_SetCursor(wanted); } } // namespace sc2k::app int main(int argc, char** argv) { std::string snapshot, cityArg, uiShot; std::string localeOverride; // --language CODE: session-only locale; never rewrites libreopolis.ini int hoverR = -1, hoverC = -1; int queryR = -1, queryC = -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 bool gpuUiShot = false; // --uishot-gpu: capture the full UI with the SDL texture-command world path int dataLayer = -1; // --layer NAME|N: release live-map/minimap data overlay for capture bool invalidDataLayer = false; 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]; gpuUiShot = false; if (frames == 0) frames = 6; } else if (std::strcmp(argv[i], "--uishot-gpu") == 0 && i + 1 < argc) { uiShot = argv[++i]; gpuUiShot = true; 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], "--openquery") == 0 && i + 1 < argc) { std::sscanf(argv[++i], "%d,%d", &queryR, &queryC); // centred Query dialog (UI 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], "--language") == 0) { if (i + 1 >= argc) { std::fprintf(stderr, "--language requires a catalogue code\n"); return 2; } localeOverride = argv[++i]; } else if (std::strcmp(argv[i], "--layer") == 0) { if (i + 1 >= argc) { std::fprintf(stderr, "--layer requires a player-facing data layer name or ordinal\n"); return 2; } const std::string argument(argv[++i]); if (const std::optional parsed = data_layer_index_from_arg(argument)) dataLayer = *parsed; else { std::fprintf(stderr, "--layer: unknown player-facing data layer '%s'\n", argument.c_str()); invalidDataLayer = 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]; } if (invalidDataLayer) return 2; if (dataLayer >= 0 && underground) { std::fprintf(stderr, "--layer and --underground select mutually exclusive city views\n"); return 2; } if (!localeOverride.empty() && !i18n::load_locale(render::assets_dir() + "/lang", localeOverride)) { std::fprintf(stderr, "--language: catalog '%s' not found in %s/lang\n", localeOverride.c_str(), render::assets_dir().c_str()); return 2; } // 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) io::NativeCityDocument bootDocument; bool bootClassicImport = false; if (needCity) { cityPath = resolve_city(cityArg); if (cityPath.empty()) { std::fprintf(stderr, "usage: libreopolis [--snapshot out.bmp] [--uishot out.bmp|--uishot-gpu out.bmp] [--language CODE] [--layer NAME|N] [--shell] [CITY.LCITY|CITY.SC2|SCENARIO.SCN]\n" "(no city given and none found under %s/CITIES)\n", sc2k_root().c_str()); return 2; } const io::FormatProbeResult format = io::probe_format(cityPath); if (format.format == io::PersistedFormat::Native) { auto loaded = io::load_native_city_file(cityPath); if (!loaded.ok()) { std::fprintf(stderr, "load %s: %s\n", cityPath.c_str(), loaded.message.c_str()); return 1; } bootDocument = std::move(loaded.value); city = bootDocument.city; if (!rotateSet) rotation = static_cast(bootDocument.viewRotation); } else if (format.format == io::PersistedFormat::Classic) { if (const auto loaded = io::load_sc2(cityPath, city); !loaded.ok) { std::fprintf(stderr, "load %s: %s\n", cityPath.c_str(), loaded.error.c_str()); return 1; } bootDocument.city = city; bootDocument.terrainAuthority = io::TerrainAuthority::Modern; bootDocument.operatingBudget = sim::migrate_legacy_operating_budget(city).value_or(sim::OperatingBudgetState{}); bootDocument.serviceDisruptions = sim::make_migrated_service_disruption_state(city); bootDocument.import = io::inspect_classic_import( cityPath, city.scen.empty() ? std::string("SC2") : std::string("SCN")); // Headless snapshots remain useful import diagnostics. Interactive boots must convert before play. bootClassicImport = snapshot.empty() && !renderCmp && (frames == 0 || (!uiShot.empty() && openDlg == 497)); } else { std::fprintf(stderr, "load %s: %s\n", cityPath.c_str(), format.error.c_str()); return 1; } sc2k::sim::repair_neighbors_if_uninitialized(city); // seed edge neighbours for pre-feature / uninitialised saves sc2k::sim::recount_arco_population(city); // resync the MISC arco-pop mirror to the records (early port saves left it 0) 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) // Native decode repairs known pre-STAD corner damage before lifecycle migration and leaves // FE10 exact. Classic inputs still cross that legacy repair boundary here. if (format.format == io::PersistedFormat::Classic) ui::detail::repair_building_corners(city); sc2k::sim::repair_inventions_if_unseeded(city); // re-seed invention years for early port saves written all-zero (else year-gating can't engage) sc2k::sim::repair_thing_ownership(city); // discard orphan XTHG records / dangling XTXT links if (format.format == io::PersistedFormat::Classic) { terrain::LegacyImportResult imported = terrain::import_legacy_terrain(city); bootDocument.canonicalTerrain = std::move(imported.terrain); bootDocument.canonicalStructures = structure::import_legacy_structures(city, bootDocument.canonicalTerrain ? &*bootDocument.canonicalTerrain : nullptr); bootDocument.canonicalHydrology = hydrology::import_legacy_hydrology(city, bootDocument.canonicalTerrain ? &*bootDocument.canonicalTerrain : nullptr, bootDocument.canonicalStructures ? &*bootDocument.canonicalStructures : nullptr); if (!bootDocument.canonicalTerrain || !bootDocument.canonicalStructures || !bootDocument.canonicalHydrology) { std::fprintf(stderr, "load %s: classic terrain conversion failed\n", cityPath.c_str()); return 1; } } // load_sc2 normalized the save's view-relative bits to compass 0; unless --rotate asked for a // specific view, open facing the saved compass, like the original. const int savedCompass = city.savedCompass; 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"); } const char* terrainOverride = std::getenv("LIBREOPOLIS_TERRAIN"); const std::string selectedTerrainStyle = terrainOverride && *terrainOverride ? terrain_style() : bootDocument.terrainStyle; Assets assets; try { assets = load_assets(assets_dir(), selectedTerrainStyle); } 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; } if (renderCmp || !snapshot.empty()) { Palette animPal = assets.palette; // mutable so traffic and compatibility sprites can palette-cycle CityRenderer renderer(assets.bank, animPal, assets.terrain_material ? &*assets.terrain_material : nullptr); if (renderCmp) return run_rendercmp(city, renderer, animPal, &bootDocument); return run_snapshot(city, renderer, snapshot, rotation, underground, &bootDocument); } return run_window(city, std::move(assets), selectedTerrainStyle, frames, rotation, uiShot, openDlg, openMenu, openFly, dbgOverlay, dbgHud, !needCity, initZoom, startEditor, cityPath, hoverR, hoverC, openLayers, underground, queryR, queryC, std::move(bootDocument), bootClassicImport, gpuUiShot, localeOverride, dataLayer); }