// Headless / command-line entry paths for the SDL front end (extracted from app/main.cpp, Task 4): // city resolution and the non-interactive verification renders that CI and agents drive // (--snapshot / --rendercmp) plus the capture overlay keyword parses. None of these touch window state — they run // before (or instead of) run_window. Kept in sc2k::app and pulled in unqualified via `using namespace sc2k::app;`. #pragma once #include #include #include #include #include #include #include #include #include #include "gpu_world.hpp" // sc2k::app::GpuWorld (--rendercmp GPU path) #include "snapshot_layout.hpp" #include "sc2k/debug/overlay.hpp" // sc2k::debug::OverlayField (--overlay keyword → index; not SC2K_DEBUG-gated) #include "sc2k/city.hpp" #include "sc2k/hydrology/transform.hpp" #include "sc2k/io/native_city.hpp" #include "sc2k/render/asset_loader.hpp" // sc2k_root #include "sc2k/render/city_renderer.hpp" // CityRenderer, Camera #include "sc2k/render/connection_arrow.hpp" #include "sc2k/render/iso_projection.hpp" // ScreenPos, origin_centering_tile #include "sc2k/render/palette.hpp" #include "sc2k/render/rotate.hpp" // rotate_city #include "sc2k/structure/legacy_import.hpp" #include "sc2k/structure/transform.hpp" #include "sc2k/terrain/legacy_import.hpp" #include "sc2k/terrain/transform.hpp" #include "sc2k/ui/layers_dialog.hpp" namespace sc2k { namespace app { using namespace sc2k::render; inline bool exists(const std::string& p) { std::ifstream f(p); return f.good(); } // Pick the city to show: an explicit path, else the first well-known test city under the data root. inline std::string resolve_city(const std::string& arg) { if (!arg.empty()) return arg; const std::string root = sc2k_root(); for (const char* name : {"TOKYO.SC2", "LONDON.SC2", "NEWYORK.SC2", "PARIS.SC2", "BAYVIEW.SC2", "DEFAULT.SC2"}) { const std::string p = root + "/CITIES/" + name; if (exists(p)) return p; } return {}; } inline int run_snapshot(const City& city, const CityRenderer& renderer, const std::string& out, int rotation, bool underground = false, const io::NativeCityDocument* document = nullptr) { const City view = rotate_city(city, rotation); std::optional terrainCache; if (document && document->active_terrain()) { const terrain::Model* sourceTerrain = document->active_terrain(); if (std::optional rotated = terrain::rotate_clockwise(*sourceTerrain, static_cast(rotation))) { const std::optional rotatedStructures = document->active_structures() ? structure::rotate_clockwise(*document->active_structures(), static_cast(rotation)) : std::nullopt; const std::optional rotatedHydrology = document->active_hydrology() ? hydrology::rotate_clockwise(*document->active_hydrology(), static_cast(rotation)) : std::nullopt; terrainCache = render::TerrainRenderCache::create(*rotated, view, rotatedHydrology ? &*rotatedHydrology : nullptr, rotatedStructures ? &*rotatedStructures : nullptr, document->preserves_classic_water_topology()); } } const SnapshotLayout layout = snapshot_layout(city.dimension()); Framebuffer fb(layout.width, layout.height); const render::ViewToggles tg{.underground = underground}; // all features on; --underground → x-ray view renderer.render(view, fb, Camera{layout.cameraX, layout.cameraY}, ((rotation % 4) + 4) % 4, 0, 2, tg, {}, {}, terrainCache ? &*terrainCache : nullptr); if (!fb.write_bmp(out.c_str())) { std::fprintf(stderr, "could not write %s\n", out.c_str()); return 1; } std::printf("wrote %s (%dx%d, rotation %d)\n", out.c_str(), fb.width(), fb.height(), ((rotation % 4) + 4) % 4); return 0; } // --rendercmp: NUMERIC verification of the GPU world path against the software compositor (the // verify-tile-rendering methodology — never eyeballed). Both paths run the SAME CityRenderer template // over the same scenes; at scale ×1 (zfrac=1 over the large bank) the GPU quads are texel-aligned and // NEAREST-sampled, so the readback must match the software Framebuffer pixel-for-pixel. Tolerance ±2 // per channel absorbs only the GPU shadow multiply (160/255 vs the CPU's exact ·5/8 on aircraft // shadows); everything else must be exact. Palette-cycle animation never runs here (one static frame). // Headless: SDL_VIDEODRIVER=dummy works — the readback comes from a render-target texture. inline int run_rendercmp(const City& city, const CityRenderer& renderer, Palette& animPal, const io::NativeCityDocument* document = nullptr) { SDL_SetMainReady(); if (!SDL_Init(SDL_INIT_VIDEO)) { std::fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); return 1; } const int W = 1280, H = 800; SDL_Window* win = SDL_CreateWindow("rendercmp", W, H, SDL_WINDOW_HIDDEN); SDL_Renderer* ren = win ? SDL_CreateRenderer(win, nullptr) : nullptr; SDL_Texture* target = ren ? SDL_CreateTexture(ren, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_TARGET, W, H) : nullptr; if (!target) { std::fprintf(stderr, "rendercmp: %s\n", SDL_GetError()); return 1; } sc2k::app::GpuWorld gpu(ren, animPal); if (!gpu.ok()) { std::fprintf(stderr, "rendercmp: GPU atlas unavailable on this renderer\n"); return 1; } struct Scene { const char* name; int rot; bool ug; int ctrRow, ctrCol; bool highlight = false; }; const int middle = (city.dimension() - 1) / 2; const int skirt = std::max(0, city.dimension() - 8); int highlightRow = middle, highlightCol = middle; int highlightDistance = city.dimension() * 2; for (int row = 0; row < city.dimension(); ++row) for (int col = 0; col < city.dimension(); ++col) { if (!xbld::is_building(city.xbld.at(row, col)) || !(city.xzon.at(row, col) & xzon::kCornerTR)) continue; const int distance = std::abs(row - middle) + std::abs(col - middle); if (distance >= highlightDistance) continue; highlightDistance = distance; highlightRow = row; highlightCol = col; } std::vector scenes = { {"rot0", 0, false, middle, middle}, {"rot1", 1, false, middle, middle}, {"rot2", 2, false, middle, middle}, {"rot3", 3, false, middle, middle}, {"highlight", 0, false, highlightRow, highlightCol, true}, {"underground", 0, true, middle, middle}, {"skirt", 0, false, skirt, skirt}, // south/east map edge: skirt + cliff columns }; auto add_object_highlight = [&](const char* name, sim::DemolitionTargetKind kind, bool underground = false) { sim::DemolitionTarget nearest; int nearest_distance = city.dimension() * 2; auto matches_seed = [&](std::uint8_t code) { switch (kind) { case sim::DemolitionTargetKind::Bridge: return xbld::is_bridge(code); case sim::DemolitionTargetKind::Highway: return xbld::is_highway(code); case sim::DemolitionTargetKind::Pier: return code == xbld::kPier || code == xbld::kCrane; case sim::DemolitionTargetKind::Runway: return code == xbld::kRunway || code == xbld::kRunwayCross; case sim::DemolitionTargetKind::Tunnel: return xbld::is_tunnel(code); case sim::DemolitionTargetKind::None: return false; } return false; }; for (int row = 0; row < city.dimension(); ++row) for (int col = 0; col < city.dimension(); ++col) { const std::uint8_t code = city.xbld.at(row, col); if (!matches_seed(code)) continue; const sim::DemolitionTarget candidate = sim::demolition_target(city, row, col); if (candidate.kind != kind) continue; const int distance = std::abs(candidate.owner_row - middle) + std::abs(candidate.owner_col - middle); if (distance >= nearest_distance) continue; nearest_distance = distance; nearest = candidate; } if (nearest) scenes.push_back({name, 0, underground, nearest.owner_row, nearest.owner_col, true}); }; add_object_highlight("bridge-highlight", sim::DemolitionTargetKind::Bridge); add_object_highlight("highway-highlight", sim::DemolitionTargetKind::Highway); add_object_highlight("pier-highlight", sim::DemolitionTargetKind::Pier); add_object_highlight("runway-highlight", sim::DemolitionTargetKind::Runway); add_object_highlight("tunnel-highlight", sim::DemolitionTargetKind::Tunnel); add_object_highlight("tunnel-xray", sim::DemolitionTargetKind::Tunnel, true); int subway_row = -1, subway_col = -1, subway_distance = city.dimension() * 2; for (int row = 0; row < city.dimension(); ++row) for (int col = 0; col < city.dimension(); ++col) { const std::uint8_t xund = city.xund.at(row, col); if (!((xund >= 1 && xund <= 15) || xund == 31 || xund == 32)) continue; if (city.xbld.at(row, col) != 0 || (city.xbit.at(row, col) & 0x20)) continue; const int distance = std::abs(row - middle) + std::abs(col - middle); if (distance >= subway_distance) continue; subway_distance = distance; subway_row = row; subway_col = col; } if (subway_row >= 0) scenes.push_back({"subway-highlight", 0, true, subway_row, subway_col, true}); int basement_row = -1, basement_col = -1, basement_distance = city.dimension() * 2; for (int row = 0; row < city.dimension(); ++row) for (int col = 0; col < city.dimension(); ++col) { if (!(city.xzon.at(row, col) & xzon::kCornerTR) || !sim::underground_structure_visible(city, row, col, true, true)) continue; const int distance = std::abs(row - middle) + std::abs(col - middle); if (distance >= basement_distance) continue; basement_distance = distance; basement_row = row; basement_col = col; } if (basement_row >= 0) scenes.push_back({"basement-highlight", 0, true, basement_row, basement_col, true}); int failed = 0; for (const Scene& sc : scenes) { const City view = rotate_city(city, sc.rot); std::optional terrainCache; if (document && document->active_terrain()) if (std::optional rotated = terrain::rotate_clockwise(*document->active_terrain(), static_cast(sc.rot))) { const std::optional rotatedHydrology = document->active_hydrology() ? hydrology::rotate_clockwise(*document->active_hydrology(), static_cast(sc.rot)) : std::nullopt; const std::optional rotatedStructures = document->active_structures() ? structure::rotate_clockwise(*document->active_structures(), static_cast(sc.rot)) : std::nullopt; terrainCache = render::TerrainRenderCache::create(*rotated, view, rotatedHydrology ? &*rotatedHydrology : nullptr, rotatedStructures ? &*rotatedStructures : nullptr, document->preserves_classic_water_topology()); } const render::TerrainRenderCache* terrainView = terrainCache ? &*terrainCache : nullptr; const render::ViewToggles tg{.underground = sc.ug}; std::vector arrow_decals; if (document && document->regionalState) { const render::ConnectionArrowVisibility visibility{ .transportation = true, .power_lines = true, .underground = sc.ug, .water_pipes = sc.ug, }; const render::TerrainRenderView terrain_view(view, terrainView); const auto arrows = render::describe_connection_arrows( std::span(document->regionalState->connections), city.dimension(), sc.rot, 2, visibility, 0, [&](int row, int column) { return terrain_view.tile(row, column).base_height - (sc.ug ? 1 : 0); }); arrow_decals = render::connection_arrow_decals(arrows, 2); } const int alt = render::TerrainRenderView(view, terrainView).tile(sc.ctrRow, sc.ctrCol).base_height; const ScreenPos o = origin_centering_tile(sc.ctrRow, sc.ctrCol, alt, 2, W / 2, H / 2); const Camera cam{o.x, o.y}; const render::ObjectSelection highlight = sc.highlight ? render::ObjectSelection{sc.ctrRow, sc.ctrCol} : render::ObjectSelection{}; Framebuffer sw(W, H); renderer.render(view, sw, cam, sc.rot, 0, 2, tg, arrow_decals, {}, terrainView, highlight); // software compositor renderer.render(view, gpu, Camera{0, 0}, sc.rot, 0, 2, tg, arrow_decals, {}, terrainView, highlight); // GPU record (camera-free) SDL_SetRenderTarget(ren, target); gpu.replay(1.f, float(cam.x), float(cam.y), W, H, highlight); SDL_Surface* raw = SDL_RenderReadPixels(ren, nullptr); SDL_SetRenderTarget(ren, nullptr); SDL_Surface* surf = raw ? SDL_ConvertSurface(raw, SDL_PIXELFORMAT_ABGR8888) : nullptr; if (raw) SDL_DestroySurface(raw); if (!surf) { std::fprintf(stderr, "rendercmp %s: readback failed: %s\n", sc.name, SDL_GetError()); ++failed; continue; } long nDiff = 0, nBad = 0; int maxD = 0; Framebuffer gp(W, H); // keep the readback for a BMP on failure for (int y = 0; y < H; ++y) { const auto* row = static_cast(surf->pixels) + std::size_t(y) * surf->pitch; for (int x = 0; x < W; ++x) { const std::uint8_t* p = row + std::size_t(x) * 4; // r,g,b,a in memory gp.set(x, y, render::Rgba{p[0], p[1], p[2], 0xFF}); const render::Rgba s = sw.at(x, y); const int d = std::max({std::abs(int(p[0]) - s.r), std::abs(int(p[1]) - s.g), std::abs(int(p[2]) - s.b)}); if (d > 0) ++nDiff; if (d > 2) ++nBad; // beyond the shadow-rounding budget maxD = std::max(maxD, d); } } SDL_DestroySurface(surf); const bool ok = nBad == 0; std::printf("rendercmp %-11s %s diff>0: %ld px (%.4f%%) diff>2: %ld px max %d (%zu cmds, %zu page%s)\n", sc.name, ok ? "OK " : "FAIL", nDiff, 100.0 * double(nDiff) / (double(W) * H), nBad, maxD, gpu.command_count(), gpu.page_count(), gpu.page_count() == 1 ? "" : "s"); if (!ok) { ++failed; std::string base = std::string("rendercmp_") + sc.name; sw.write_bmp((base + "_sw.bmp").c_str()); gp.write_bmp((base + "_gpu.bmp").c_str()); } } SDL_DestroyTexture(target); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return failed ? 1 : 0; } // Map a --overlay keyword (or raw index) to a debug::OverlayField index; 0 = off. Always available // (OverlayField itself isn't debug-gated); only acted on in a SC2K_DEBUG build. inline int overlay_index_from_arg(const std::string& a) { if (!a.empty() && (a[0] == '-' || (a[0] >= '0' && a[0] <= '9'))) return std::atoi(a.c_str()); if (a == "fire") return int(debug::OverlayField::Fire); if (a == "police") return int(debug::OverlayField::Police); if (a == "crime") return int(debug::OverlayField::Crime); if (a == "pollution") return int(debug::OverlayField::Pollution); if (a == "value" || a == "landvalue") return int(debug::OverlayField::LandValue); if (a == "traffic") return int(debug::OverlayField::Traffic); if (a == "density") return int(debug::OverlayField::Density); if (a == "growth") return int(debug::OverlayField::Growth); if (a == "power") return int(debug::OverlayField::Power); if (a == "water") return int(debug::OverlayField::Water); return 0; } // Map a --layer keyword (or raw MapView ordinal) to one of the player-facing data layers exposed by // View City Layers. Unlike --overlay, this selects the release live-map/minimap path and its diagnostic // legend. Unknown and non-player-facing MapView values fail closed so an oracle never silently captures // the plain city view under a misspelled label. inline std::optional data_layer_index_from_arg(const std::string& a) { int view = -1; if (!a.empty() && (a[0] == '-' || (a[0] >= '0' && a[0] <= '9'))) { char* end = nullptr; const long parsed = std::strtol(a.c_str(), &end, 10); if (end && *end == '\0' && parsed >= 0 && parsed < int(render::MapView::Count)) view = int(parsed); } else if (a == "crime") view = int(render::MapView::Crime); else if (a == "density") view = int(render::MapView::Density); else if (a == "power" || a == "electricity") view = int(render::MapView::Power); else if (a == "water") view = int(render::MapView::Water); else if (a == "value" || a == "landvalue" || a == "land-value") view = int(render::MapView::Value); else if (a == "pollution") view = int(render::MapView::Pollution); else if (a == "traffic") view = int(render::MapView::Traffic); else if (a == "flammability") view = int(render::MapView::Flammability); else if (a == "desirability") view = int(render::MapView::Desirability); else if (a == "fire" || a == "fire-coverage") view = int(render::MapView::FireCoverage); else if (a == "police" || a == "police-coverage") view = int(render::MapView::PoliceCoverage); else if (a == "water-pollution" || a == "waterpollution") view = int(render::MapView::WaterPollution); else if (a == "satisfaction") view = int(render::MapView::Satisfaction); else if (a == "disruptions" || a == "service-disruptions") view = int(render::MapView::Disruptions); if (view < 0) return std::nullopt; for (const ui::LayersDialog::DataView& candidate : ui::LayersDialog::kData) if (candidate.mapView == view) return view; return std::nullopt; } } // namespace app } // namespace sc2k