// things.cpp — out-of-line bodies for sc2k/sim/things.hpp (see the header for the RE notes + contracts). // Split out of the header so editing an implementation recompiles just this TU (Task 5). #include "sc2k/sim/things.hpp" namespace sc2k::sim { int thing_speed(int type) { // per-type speed table static const std::uint8_t s[16] = {0, 16, 8, 4, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8}; return (type >= 0 && type < 16) ? s[type] : 0; } } // namespace sc2k::sim namespace sc2k::sim { int thing_alloc(const City& c) { for (int i = 1; i < thg::kCount; ++i) if (thing_field(c, i, thg::Type) == 0) return i; return 0; } } // namespace sc2k::sim namespace sc2k::sim { namespace { std::uint8_t thing_owner_marker(int idx) { return static_cast(static_cast(xtxt::kThingFirst) + static_cast(idx)); } bool thing_owns_cell(const City& c, int idx, int x, int y) { return c.on_map(x, y) && c.xtxt.at(x, y) == thing_owner_marker(idx); } } // namespace void thing_despawn(City& c, int idx) { if (idx <= 0 || idx >= thg::kCount) return; const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); thing_field(c, idx, thg::Type) = 0; if (thing_owns_cell(c, idx, x, y)) { const std::uint8_t saved = thing_field(c, idx, thg::SavedTile); c.xtxt.at(x, y) = xtxt::is_thing(saved) ? xtxt::kNone : saved; } ship_nav_reset(idx); } } // namespace sc2k::sim namespace sc2k::sim { bool thing_relocate(City& c, int idx, int x, int y) { if (idx <= 0 || idx >= thg::kCount || !c.on_map(x, y)) return false; const int oldX = thing_field(c, idx, thg::X); const int oldY = thing_field(c, idx, thg::Y); if (!thing_owns_cell(c, idx, oldX, oldY)) return false; if (x == oldX && y == oldY) return true; if (xtxt::is_thing(c.xtxt.at(x, y))) return false; const std::uint8_t underlay = c.xtxt.at(x, y); c.xtxt.at(oldX, oldY) = thing_field(c, idx, thg::SavedTile); thing_field(c, idx, thg::X) = static_cast(x); thing_field(c, idx, thg::Y) = static_cast(y); thing_field(c, idx, thg::SavedTile) = underlay; c.xtxt.at(x, y) = thing_owner_marker(idx); return true; } } // namespace sc2k::sim namespace sc2k::sim { bool thing_move(City& c, int type, int idx, int dir) { const int step = thing_speed(type); int nx = step * kThingDX[dir & 7] + thing_field(c, idx, thg::Xsub); int ny = step * kThingDY[dir & 7] + thing_field(c, idx, thg::Ysub); int carry = 0, dtx = 0, dty = 0; if (nx > 16) { nx -= 16; carry = 1; dtx = 1; } if (nx < 0) { nx += 16; carry = 1; dtx = -1; } if (ny > 16) { ny -= 16; carry = 1; dty = 1; } if (ny < 0) { ny += 16; carry = 1; dty = -1; } thing_field(c, idx, thg::Xsub) = std::uint8_t(nx); thing_field(c, idx, thg::Ysub) = std::uint8_t(ny); if (!carry) return true; const int ox = thing_field(c, idx, thg::X), oy = thing_field(c, idx, thg::Y); if (!thing_owns_cell(c, idx, ox, oy)) { thing_despawn(c, idx); return false; } int tx = ox + dtx, ty = oy + dty; c.xtxt.at(ox, oy) = thing_field(c, idx, thg::SavedTile); // restore vacated cell if (!c.on_map(tx, ty)) { thing_despawn(c, idx); return false; } while (c.xtxt.at(tx, ty) >= 0xC9) { // slide past other things' cells thing_field(c, idx, thg::X) = std::uint8_t(tx); thing_field(c, idx, thg::Y) = std::uint8_t(ty); tx = thing_field(c, idx, thg::X) + dtx; ty = thing_field(c, idx, thg::Y) + dty; if (!c.on_map(tx, ty)) { thing_despawn(c, idx); return false; } } thing_field(c, idx, thg::X) = std::uint8_t(tx); thing_field(c, idx, thg::Y) = std::uint8_t(ty); thing_field(c, idx, thg::SavedTile) = c.xtxt.at(tx, ty); c.xtxt.at(tx, ty) = std::uint8_t(idx - 55); // claim it (idx + 0xC9, as a byte) return true; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_tornado(City& c, MsRand& rng, int x, int y, const terrain::Model* terrainModel) { for (int i = 1; i < thg::kCount; ++i) if (thing_field(c, i, thg::Type) == thg::kTornado) return 0; x = std::clamp(x, 0, c.dimension() - 1); y = std::clamp(y, 0, c.dimension() - 1); if (xtxt::is_thing(c.xtxt.at(x, y))) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = thg::kTornado; thing_field(c, idx, thg::Dir) = std::uint8_t(rng.next() & 7); thing_field(c, idx, thg::X) = std::uint8_t(x); thing_field(c, idx, thg::Y) = std::uint8_t(y); thing_field(c, idx, thg::Frame) = std::uint8_t(terrain::Query(c, terrainModel).base_level({x, y})); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::DestX) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::DestY) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::SavedTile) = c.xtxt.at(x, y); thing_field(c, idx, thg::State) = 0; c.xtxt.at(x, y) = std::uint8_t(idx - 55); // claim the cell return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool tornado_step(City& c, MsRand& rng, DisasterSim& d, int idx, const terrain::Model* terrainModel) { const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); const int under = c.xbld.at(x, y); if (under > 5) detail::demolish(c, d, x, y, /*lightFire=*/false, terrainModel); // the funnel flattens it int dir = (thing_field(c, idx, thg::Dir) + (rng.next() % 3) - (rng.next() % 3)) & 7; thing_field(c, idx, thg::Dir) = std::uint8_t(dir); if (!thing_move(c, thg::kTornado, idx, dir)) return false; // ran off the map if ((rng.next() & 0xFF) == 0) { thing_despawn(c, idx); return false; } if (under < 0x0D) { // faster over open ground: a 2nd hop dir = (thing_field(c, idx, thg::Dir) + (rng.next() & 1) - (rng.next() & 1)) & 7; thing_field(c, idx, thg::Dir) = std::uint8_t(dir); if (!thing_move(c, thg::kTornado, idx, dir)) return false; if ((rng.next() & 0xFF) == 0) { thing_despawn(c, idx); return false; } } return true; } } // namespace sc2k::sim namespace sc2k::sim { int thing_bearing(int x, int y, int tx, int ty) { const int dx = tx - x, dy = ty - y; const int adx = dx < 0 ? -dx : dx, ady = dy < 0 ? -dy : dy; if ((ady + 1) / 2 > adx) return dy < 0 ? 0 : 4; // mostly vertical → N / S if (dx >= 0) return (adx + 1) / 2 <= ady ? (dy < 0 ? 1 : 3) : 2; // east: NE / SE / E return (adx + 1) / 2 <= ady ? (dy < 0 ? 7 : 5) : 6; // west: NW / SW / W } } // namespace sc2k::sim namespace sc2k::sim { int thing_jitter(MsRand& rng, int dir, int n) { if (rng.next() % n == 0) return (int(rng.next() % 3) + dir - 1) & 7; return dir; } } // namespace sc2k::sim namespace sc2k::sim { int thing_step_toward_dir(int cur, int tgt) { cur &= 7; tgt &= 7; if (tgt >= cur) return ((tgt - cur) <= 4) ? (cur + 1) & 7 : (cur - 1) & 7; return ((cur - tgt) <= 4) ? (cur - 1) & 7 : (cur + 1) & 7; } } // namespace sc2k::sim namespace sc2k::sim { int thing_steer(int cur, int x, int y, int tx, int ty) { const int b = thing_bearing(x, y, tx, ty); cur &= 7; if (b == cur) return cur; if (b >= cur) return ((b - cur) <= 4) ? (cur + 1) & 7 : (cur - 1) & 7; return ((cur - b) <= 4) ? (cur - 1) & 7 : (cur + 1) & 7; } } // namespace sc2k::sim namespace sc2k::sim { int thing_bearing4(int x, int y, int tx, int ty) { const int dx = tx - x, dy = ty - y; if (dx == 0) return dy < 0 ? 0 : 4; if (dx > 0) return dy < 0 ? 1 : (dy > 0 ? 3 : 2); return dy > 0 ? 5 : (dy < 0 ? 7 : 6); } } // namespace sc2k::sim namespace sc2k::sim { bool aircraft_dir_blocked(const City& c, int idx, int dir) { static const int adx[8] = {0, 3, 3, 3, 0, -3, -3, -3}; // per-heading deltas static const int ady[8] = {-3, -3, 0, 3, 3, 3, 0, -3}; dir &= 7; const int x = thing_field(c, idx, thg::X) + adx[dir], y = thing_field(c, idx, thg::Y) + ady[dir]; return detail::inb(c, x, y) && c.xbld.at(x, y) >= 0xFB; } } // namespace sc2k::sim namespace sc2k::sim { void aircraft_avoid_water(City& c, int idx) { const int dir = thing_field(c, idx, thg::Dir); if (!aircraft_dir_blocked(c, idx, dir)) return; static const int spiral[8] = {1, 7, 2, 6, 3, 5, 4, 0}; // heading-search order int heading = dir; for (int i = 0; i < 7; ++i) { heading = (spiral[i] + dir) & 7; if (!aircraft_dir_blocked(c, idx, heading)) break; } thing_field(c, idx, thg::Dir) = std::uint8_t(heading); } } // namespace sc2k::sim namespace sc2k::sim { bool ship_water_at(const City& c, int x, int y) { // navigable WATER (ignoring Thing occupancy) if (!detail::inb(c, x, y) || !detail::is_water(c, x, y)) return false; // XBIT 0x04 surface water const int t = c.xter.at(x, y); if (t < 0x10 || t >= 0x20) return false; // deep-water terrain band (big ships keep to the channel) // Block only SOLID obstacles standing in the water: a pier (0xDF), the marina (0xF8), or a building. A // ship sails UNDER bridges / elevated highways / power lines, so any other XBLD on a water tile passes. // (The original's navigability whitelist is too narrow — it rejects the highway 0x49/0x4a that crosses // FourCities' harbour, which wrongly islanded the seaport from the open water; the sailboat check // the original's berth test is exactly this lenient — pier/marina only — confirming ships pass under overhead structures.) const int b = c.xbld.at(x, y); return b != 0xDF && b != 0xF8 && b < 0x70; } } // namespace sc2k::sim namespace sc2k::sim { bool ship_can_enter(const City& c, int x, int y) { return ship_water_at(c, x, y) && c.xtxt.at(x, y) < 0xC9; // …and unoccupied by another Thing } } // namespace sc2k::sim namespace sc2k::sim { bool ship_dir_clear(const City& c, int idx, int dir) { dir &= 7; const int cx = thing_field(c, idx, thg::X), cy = thing_field(c, idx, thg::Y); const int x = cx + kThingDX[dir], y = cy + kThingDY[dir]; if (detail::inb(c, x, y) && !ship_can_enter(c, x, y)) return false; // the target tile // NO CORNER-CUTTING on a diagonal: ship_move's 12-grid carries ONE axis at a time, so a diagonal step // lands on an ORTHOGONAL neighbour mid-move — if that's a shoal/shore the ship grounds (it slipped past // this check onto a tile we never validated). Both shared orthogonals must be navigable. (The A* route // already forbids corner-cuts; this stops the gradual STEER from picking one and wrecking — user: a ship // grounding while threading past a shoal corner.) if (kThingDX[dir] && kThingDY[dir]) { if (detail::inb(c, cx + kThingDX[dir], cy) && !ship_can_enter(c, cx + kThingDX[dir], cy)) return false; if (detail::inb(c, cx, cy + kThingDY[dir]) && !ship_can_enter(c, cx, cy + kThingDY[dir])) return false; } return true; } } // namespace sc2k::sim namespace sc2k::sim { bool ship_move(City& c, int idx, int dir) { static const int sdx[8] = {0, 3, 4, 3, 0, -3, -4, -3}; // sail deltas static const int sdy[8] = {-4, -3, 0, 3, 4, 3, 0, -3}; dir &= 7; const int oldXsub = thing_field(c, idx, thg::Xsub); const int oldYsub = thing_field(c, idx, thg::Ysub); int nx = sdx[dir] + oldXsub, ny = sdy[dir] + oldYsub; int carry = 0, dtx = 0, dty = 0; if (nx > 12) { nx -= 12; carry = 1; dtx = 1; } if (nx < 0) { nx += 12; carry = 1; dtx = -1; } if (ny > 12) { ny -= 12; carry = 1; dty = 1; } if (ny < 0) { ny += 12; carry = 1; dty = -1; } thing_field(c, idx, thg::Xsub) = std::uint8_t(nx); thing_field(c, idx, thg::Ysub) = std::uint8_t(ny); if (!carry) return true; const int ox = thing_field(c, idx, thg::X), oy = thing_field(c, idx, thg::Y); if (!thing_owns_cell(c, idx, ox, oy)) { thing_despawn(c, idx); return false; } const int tx = ox + dtx, ty = oy + dty; if (!detail::inb(c, tx, ty)) { c.xtxt.at(ox, oy) = thing_field(c, idx, thg::SavedTile); thing_despawn(c, idx); return false; } if (!ship_can_enter(c, tx, ty)) { thing_field(c, idx, thg::Xsub) = static_cast(oldXsub); thing_field(c, idx, thg::Ysub) = static_cast(oldYsub); return true; } c.xtxt.at(ox, oy) = thing_field(c, idx, thg::SavedTile); // restore the vacated cell thing_field(c, idx, thg::X) = std::uint8_t(tx); thing_field(c, idx, thg::Y) = std::uint8_t(ty); thing_field(c, idx, thg::SavedTile) = c.xtxt.at(tx, ty); c.xtxt.at(tx, ty) = std::uint8_t(idx - 55); // claim the new cell return true; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_monster(City& c, MsRand& rng, int x, int y) { for (int i = 1; i < thg::kCount; ++i) if (thing_field(c, i, thg::Type) == 5) return 0; x = std::clamp(x, 0, c.dimension() - 1); y = std::clamp(y, 0, c.dimension() - 1); if (xtxt::is_thing(c.xtxt.at(x, y))) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = 5; thing_field(c, idx, thg::Dir) = 2; thing_field(c, idx, thg::X) = std::uint8_t(x); thing_field(c, idx, thg::Y) = std::uint8_t(y); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::DestX) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::DestY) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::Frame) = 15; thing_field(c, idx, thg::SavedTile) = c.xtxt.at(x, y); thing_field(c, idx, thg::State) = 0; thing_field(c, idx, thg::Link) = (rng.next() & 1) ? 0 : std::uint8_t(rng.next() % 3 + 1); c.xtxt.at(x, y) = std::uint8_t(idx - 55); return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool monster_step(City& c, MsRand& rng, DisasterSim& d, int idx) { using namespace detail; // The monster tick's head — a loose monster SHOOTS DOWN aircraft: every live plane is thrown into the crash // spiral (state 7, the same state the Air Crash disaster uses) and every helicopter into state 5, // each tick while the monster lives. (Heli state 5 is not yet a distinct behaviour in this port — // it patrols on — but the plane spiral is fully implemented, so planes now tumble out of the sky.) for (int t = 1; t < thg::kCount; ++t) { const int tt = thing_field(c, t, thg::Type); if (tt == 1) thing_field(c, t, thg::State) = 7; else if (tt == 2) thing_field(c, t, thg::State) = 5; } const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); int dir = thing_field(c, idx, thg::Dir); switch (thing_field(c, idx, thg::State)) { case 0: { // rise — count the body up to size, then rampage; aim at the city centre const int f = thing_field(c, idx, thg::Frame); if (f <= 8) thing_field(c, idx, thg::State) = 1; else thing_field(c, idx, thg::Frame) = std::uint8_t(f - 1); thing_field(c, idx, thg::DestX) = 0; thing_field(c, idx, thg::DestY) = 0; int cx, cy; city_centre(c, cx, cy); dir = thing_bearing(x, y, cx, cy); break; } case 1: { // rampage — wander and destroy the tile ahead (x+1,y+1) if (rng.next() % 0x19 == 0) thing_field(c, idx, thg::State) = 2; thing_field(c, idx, thg::DestX) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::DestY) = std::uint8_t(rng.next() % c.dimension()); dir = thing_jitter(rng, dir, 5); if (x < c.dimension() - 1 && y < c.dimension() - 1) { const int fx = x + 1, fy = y + 1, sub = thing_field(c, idx, thg::Link); if (sub) { if (!(c.xbit.at(fx, fy) & 4) && c.xbld.at(fx, fy) >= 0x0E && c.xbld.at(fx, fy) != 200) { demolish(c, d, fx, fy, false); if (sub == 1) (void)write_overlay_preserving_thing_owner(c, fx, fy, std::uint8_t((rng.next() & 3) + 9)); // smoulder sprite else if (sub == 3) c.xbld.at(fx, fy) = 200; // radioactive crater // sub==2 (flood) detail simplified to the demolition thing_field(c, idx, thg::DestX) |= 0x80; } } else if (c.xbld.at(fx, fy) >= 6 && ignite(c, d, fx, fy, 0)) { thing_field(c, idx, thg::DestX) |= 0x80; // started a fire } } break; } case 2: { // stomp — grow to full size, then either resume or leave const int f = thing_field(c, idx, thg::Frame); if (f >= 0x0F) thing_field(c, idx, thg::State) = (rng.next() % 3) ? 0 : 3; else thing_field(c, idx, thg::Frame) = std::uint8_t(f + 1); const int v = 9 * int(rng.next() & 7); thing_field(c, idx, thg::DestX) = std::uint8_t(v); thing_field(c, idx, thg::DestY) = std::uint8_t(v); dir = thing_jitter(rng, dir, 5); break; } case 3: // leave — settle, then 1-in-100 submerge & vanish thing_field(c, idx, thg::DestX) = 0; thing_field(c, idx, thg::DestY) = 0; if (rng.next() & 1) { thing_field(c, idx, thg::DestX) = 36; thing_field(c, idx, thg::DestY) = 36; } if (d.lfsrMod(100) == 0) { thing_despawn(c, idx); return false; } break; } // Move (LABEL_17): if walking into a landmark Thing (type 14), turn to leave instead. const int fx = x + kThingDX[dir & 7], fy = y + kThingDY[dir & 7]; if (thing_field(c, idx, thg::State) != 3 && inb(c, fx, fy)) { const int cell = c.xtxt.at(fx, fy); if (cell >= 0xC9 && cell < 0xF1 && thing_field(c, cell - 201, thg::Type) == 14) { thing_field(c, idx, thg::State) = 3; return true; } } thing_field(c, idx, thg::Dir) = std::uint8_t(dir); thing_move(c, 5, idx, dir); return thing_field(c, idx, thg::Type) == 5; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_explosion(City& c, int x, int y, std::uint8_t state, std::uint8_t subtype) { if (!detail::inb(c, x, y) || c.xtxt.at(x, y) >= 0xC9) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = 6; thing_field(c, idx, thg::Dir) = 0; // the fireball timer thing_field(c, idx, thg::X) = std::uint8_t(x); thing_field(c, idx, thg::Y) = std::uint8_t(y); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::Frame) = 0; thing_field(c, idx, thg::SavedTile) = c.xtxt.at(x, y); thing_field(c, idx, thg::Link) = subtype; thing_field(c, idx, thg::State) = state; c.xtxt.at(x, y) = std::uint8_t(idx - 55); return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool explosion_step(City& c, DisasterSim& d, int idx) { const int dir = thing_field(c, idx, thg::Dir); if (dir <= 1) { thing_field(c, idx, thg::Dir) = std::uint8_t(dir + 1); return true; } const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y), sub = thing_field(c, idx, thg::Link); thing_despawn(c, idx); // Faithful to the original's explosion tick: a fireball always despawns, but its chain-FIRE // only ignites if `link && (disasters enabled || a disaster is already deliberately running)` — the original // fires on `link && (!noDisasters || disasterActive)`. So under "No Disasters" an ambient plane crash // is a cosmetic fireball only (no spreading fire), while a menu/scenario disaster's blasts still burn. if (sub && (d.disastersEnabled || d.active)) { for (int k = 0; k < 4; ++k) { const int nx = x + d.lfsrMod(5) - 2, ny = y + d.lfsrMod(5) - 2; // ±2 jitter (LFSR) if (detail::inb(c, nx, ny)) detail::ignite(c, d, nx, ny, 1); } // An ambient crash that lit a fire isn't yet a "disaster" — promote it so the effect tick spreads it. if (!d.active) { d.active = true; d.type = 1; } } return false; } } // namespace sc2k::sim namespace sc2k::sim { bool start_air_crash(City& c, DisasterSim& d, MsRand& rng) { int x = 0, y = 0; bool found = false; const int span = c.dimension() / 2; const int inset = c.dimension() / 4; for (int tries = 0; tries < 4096 && !found; ++tries) { // the original loops until it hits one x = d.lfsrMod(span) + inset; y = d.lfsrMod(span) + inset; found = c.xtxt.at(x, y) == 0; } if (!found) return false; const int idx = thing_alloc(c); if (!idx) return false; // the original returns 0 on failure thing_field(c, idx, thg::Type) = 1; // a plane… thing_field(c, idx, thg::Dir) = std::uint8_t(rng.next() & 7); // (creator leaves Dir stale; seed it sanely) thing_field(c, idx, thg::X) = std::uint8_t(x); thing_field(c, idx, thg::Y) = std::uint8_t(y); thing_field(c, idx, thg::Frame) = 16; // …16 frames up thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::SavedTile) = 0; thing_field(c, idx, thg::State) = 7; // …falling out of the sky c.xtxt.at(x, y) = std::uint8_t(idx - 55); // claim the cell (idx + 0xC9) d.epiX = x; d.epiY = y; // j_SimulationPrepareDisaster + Auto-Goto target d.active = true; d.type = 0x12; return true; } } // namespace sc2k::sim namespace sc2k::sim { int thing_count(const City& c, int type) { int n = 0; for (int i = 1; i < thg::kCount; ++i) if (thing_field(c, i, thg::Type) == type) ++n; return n; } } // namespace sc2k::sim namespace sc2k::sim { void thing_place(City& c, int idx, int x, int y) { // claim the occupancy cell at (x,y) thing_field(c, idx, thg::X) = std::uint8_t(x); thing_field(c, idx, thg::Y) = std::uint8_t(y); thing_field(c, idx, thg::SavedTile) = c.xtxt.at(x, y); c.xtxt.at(x, y) = std::uint8_t(idx - 55); } } // namespace sc2k::sim namespace sc2k::sim { int spawn_airplane(City& c, MsRand& rng, int ax, int ay) { if (thing_count(c, 5) || thing_count(c, 1) >= 2) return 0; if (!detail::inb(c, ax, ay) || c.xtxt.at(ax, ay) >= 0xC9) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = 1; thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; if (rng.next() % 10 >= 5) { // 50%: climb out from the airport thing_field(c, idx, thg::DestX) = std::uint8_t(ax); thing_field(c, idx, thg::DestY) = std::uint8_t(ay); thing_field(c, idx, thg::Dir) = 2; thing_field(c, idx, thg::Frame) = 0; thing_field(c, idx, thg::State) = 0; thing_place(c, idx, ax, ay); } else { // 50%: fly in from a random edge → airport int x = ax, y = ay, dir = 2; const int edgeInset = std::min(10, (c.dimension() - 1) / 2); const int edgeSpan = std::min(100, c.dimension() - 2 * edgeInset); switch (rng.next() & 3) { case 0: x = 0; y = int(rng.next() % edgeSpan) + edgeInset; dir = 3; break; case 1: y = 0; x = int(rng.next() % edgeSpan) + edgeInset; dir = 5; break; case 2: x = c.dimension() - 1; y = int(rng.next() % edgeSpan) + edgeInset; dir = 7; break; default: y = c.dimension() - 1; x = int(rng.next() % edgeSpan) + edgeInset; dir = 1; break; } thing_field(c, idx, thg::Dir) = std::uint8_t(dir); thing_field(c, idx, thg::Frame) = 16; thing_field(c, idx, thg::State) = 3; thing_field(c, idx, thg::DestX) = std::uint8_t(ax); thing_field(c, idx, thg::DestY) = std::uint8_t(ay); if (c.xtxt.at(x, y) >= 0xC9) { thing_field(c, idx, thg::Type) = 0; return 0; } thing_place(c, idx, x, y); } return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool airplane_step(City& c, MsRand& rng, int idx) { using namespace detail; const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); const int under = c.xbld.at(x, y); if (under >= 0xFB) { // ditched in deep water → fireball thing_field(c, idx, thg::Type) = 6; thing_field(c, idx, thg::State) = 5; thing_field(c, idx, thg::Link) = (rng.next() & 0xF) ? 0 : 1; thing_field(c, idx, thg::Dir) = 0; return true; } const int dxv = thing_field(c, idx, thg::DestX), dyv = thing_field(c, idx, thg::DestY); switch (thing_field(c, idx, thg::State) & 0xF) { case 0: // climb out after takeoff thing_move(c, 1, idx, thing_field(c, idx, thg::Dir)); if (thing_field(c, idx, thg::Frame) >= 14) thing_field(c, idx, thg::State) = 2; else thing_field(c, idx, thg::Frame) = std::uint8_t(thing_field(c, idx, thg::Frame) + 1); break; case 1: // descend / land if (!thing_move(c, 1, idx, thing_field(c, idx, thg::Dir))) return false; if (c.xbld.at(thing_field(c, idx, thg::X), thing_field(c, idx, thg::Y)) == 0xDD) { thing_despawn(c, idx); return false; } break; case 2: // cruise (wander, but bank away from the open sea) thing_field(c, idx, thg::Dir) = std::uint8_t(thing_jitter(rng, thing_field(c, idx, thg::Dir), 5)); aircraft_avoid_water(c, idx); if (!thing_move(c, 1, idx, thing_field(c, idx, thg::Dir))) return false; break; case 3: // far approach — snap onto the 4-quadrant bearing, avoid the sea thing_field(c, idx, thg::Dir) = std::uint8_t(thing_bearing4(x, y, dxv, dyv)); aircraft_avoid_water(c, idx); if (!thing_move(c, 1, idx, thing_field(c, idx, thg::Dir))) return false; if (std::abs(int(thing_field(c, idx, thg::X)) - dxv) + std::abs(int(thing_field(c, idx, thg::Y)) - dyv) < 2) thing_field(c, idx, thg::State) = 4; break; case 7: { // CRASH SPIRAL (the original's case 7, the Air Crash const int f = thing_field(c, idx, thg::Frame); // disaster): sink a frame per tick, spinning one if (f) { // octant per tick; at 0 → impact fireball. thing_field(c, idx, thg::Frame) = std::uint8_t(f - 1); const int dir = thing_field(c, idx, thg::Dir); // move along the PRE-spin heading thing_field(c, idx, thg::Dir) = std::uint8_t((dir + 1) & 7); if (!thing_move(c, 1, idx, dir)) return false; // (the original plays sound 515 at Frame==8 — presentation, left to the caller) } else { thing_field(c, idx, thg::Type) = 6; // impact → explosion, chain-fire subtype thing_field(c, idx, thg::State) = 5; thing_field(c, idx, thg::Link) = 1; thing_field(c, idx, thg::Dir) = 0; } break; } default: // 4 — final approach: GRADUAL steer in, then line up & land thing_field(c, idx, thg::Dir) = std::uint8_t(thing_steer(thing_field(c, idx, thg::Dir), x, y, dxv, dyv)); if (!thing_move(c, 1, idx, thing_field(c, idx, thg::Dir))) return false; if (std::abs(int(thing_field(c, idx, thg::X)) - dxv) + std::abs(int(thing_field(c, idx, thg::Y)) - dyv) < 2) { thing_field(c, idx, thg::State) = 1; // → descend/land; snap onto the runway axis const int currentX = thing_field(c, idx, thg::X); const int currentY = thing_field(c, idx, thg::Y); int alignedX = currentX; int alignedY = currentY; if (std::abs(x - dxv) >= std::abs(y - dyv)) alignedY = dyv; else alignedX = dxv; (void)thing_relocate(c, idx, alignedX, alignedY); } break; } return thing_field(c, idx, thg::Type) == 1; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_helicopter(City& c, MsRand& rng, int ax, int ay) { if (thing_count(c, 5) || thing_count(c, 2) >= 1) return 0; if (!detail::inb(c, ax, ay) || c.xtxt.at(ax, ay) >= 0xC9) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = 2; thing_field(c, idx, thg::Dir) = 2; thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::DestX) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::DestY) = std::uint8_t(rng.next() % c.dimension()); thing_field(c, idx, thg::Frame) = 0; thing_field(c, idx, thg::State) = 0; thing_place(c, idx, ax, ay); return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool helicopter_step(City& c, MsRand& rng, int idx) { using namespace detail; if (c.xbld.at(thing_field(c, idx, thg::X), thing_field(c, idx, thg::Y)) >= 0xFB) { // deep water → ditch thing_field(c, idx, thg::Type) = 6; thing_field(c, idx, thg::State) = 5; thing_field(c, idx, thg::Link) = 0; thing_field(c, idx, thg::Dir) = 0; return true; } switch (thing_field(c, idx, thg::State)) { case 0: thing_field(c, idx, thg::Dir) = std::uint8_t((thing_field(c, idx, thg::Dir) + 1) & 7); if (thing_field(c, idx, thg::Frame) >= 0xA) thing_field(c, idx, thg::State) = 2; else thing_field(c, idx, thg::Frame) = std::uint8_t(thing_field(c, idx, thg::Frame) + 1); break; default: { // patrol — bank gradually toward the destination const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); const int dxv = thing_field(c, idx, thg::DestX), dyv = thing_field(c, idx, thg::DestY); thing_field(c, idx, thg::Dir) = std::uint8_t(thing_steer(thing_field(c, idx, thg::Dir), x, y, dxv, dyv)); aircraft_avoid_water(c, idx); if (!thing_move(c, 2, idx, thing_field(c, idx, thg::Dir))) return false; if (std::abs(x - dxv) + std::abs(y - dyv) < 2) { // arrived → new dest near centre int cx, cy; city_centre(c, cx, cy); thing_field(c, idx, thg::DestX) = std::uint8_t(std::clamp(cx + int(rng.next() & 0x3F) - 32, 0, c.dimension() - 1)); thing_field(c, idx, thg::DestY) = std::uint8_t(std::clamp(cy + int(rng.next() & 0x3F) - 32, 0, c.dimension() - 1)); } break; } } return thing_field(c, idx, thg::Type) == 2; } } // namespace sc2k::sim namespace sc2k::sim { bool ship_entry_from_seaport(const City& c, int ax, int ay, MsRand& rng, int& ox, int& oy) { ox = oy = -1; // same out-param contract as find_berth: always defined, even on false return // Reused BFS scratch (thread_local only to avoid reallocating 16 KB per call). Fully re-initialised by // the assign() below at the top of every call, so no state carries between calls or across a city load. static thread_local std::vector seen; seen.assign(c.tile_count(), 0); std::vector q, edges; auto push = [&](int r, int cc) { if (!detail::inb(c, r, cc)) return; const std::size_t k = c.index(r, cc); if (seen[k] || !ship_water_at(c, r, cc)) return; seen[k] = 1; q.push_back(r * c.dimension() + cc); if ((r == 2 || r == c.dimension() - 3 || cc == 2 || cc == c.dimension() - 3) && ship_can_enter(c, r, cc)) edges.push_back(r * c.dimension() + cc); }; for (int dr = -2; dr <= 2; ++dr) for (int dc = -2; dc <= 2; ++dc) push(ax + dr, ay + dc); // seaport-adjacent water for (std::size_t h = 0; h < q.size(); ++h) { const int r = q[h] / c.dimension(), cc = q[h] % c.dimension(); push(r + 1, cc); push(r - 1, cc); push(r, cc + 1); push(r, cc - 1); // 4-connected flood } if (edges.empty()) return false; const int e = edges[rng.next() % edges.size()]; ox = e / c.dimension(); oy = e % c.dimension(); return true; } } // namespace sc2k::sim namespace sc2k::sim { std::vector ship_water_flood(const City& c, const std::vector& seeds) { std::vector seen(c.tile_count(), 0); std::vector q; for (int s : seeds) { const int x = s / c.dimension(), y = s % c.dimension(); if (detail::inb(c, x, y) && !seen[s] && ship_water_at(c, x, y)) { seen[s] = 1; q.push_back(s); } } for (std::size_t h = 0; h < q.size(); ++h) { const int x = q[h] / c.dimension(), y = q[h] % c.dimension(); static const int nx[4] = {1, -1, 0, 0}, ny[4] = {0, 0, 1, -1}; for (int d = 0; d < 4; ++d) { const int ax = x + nx[d], ay = y + ny[d]; if (!detail::inb(c, ax, ay)) continue; const std::size_t kk = c.index(ax, ay); if (!seen[kk] && ship_water_at(c, ax, ay)) { seen[kk] = 1; q.push_back(int(kk)); } } } return seen; } } // namespace sc2k::sim namespace sc2k::sim { std::vector ship_edge_reachable(const City& c) { std::vector seeds; for (int i = 0; i < c.dimension(); ++i) for (int e : {0, 2, c.dimension() - 3, c.dimension() - 1}) { seeds.push_back(e * c.dimension() + i); seeds.push_back(i * c.dimension() + e); } return ship_water_flood(c, seeds); } } // namespace sc2k::sim namespace sc2k::sim { std::vector ship_workable_in(const City& c, const std::vector& reach, int openClear, int maxDepth) { const auto clr = nav::clearance_field(c, &ship_water_at); std::vector work(c.tile_count(), 0); std::vector q, dist(c.tile_count(), 0); for (int x = 0; x < c.dimension(); ++x) for (int y = 0; y < c.dimension(); ++y) { // open water = manoeuvring room, depth 0 const std::size_t k = c.index(x, y); if (reach[k] && clr[k] >= openClear) { work[k] = 1; q.push_back(int(k)); } } for (std::size_t h = 0; h < q.size(); ++h) { // …reach `maxDepth` tiles in from it const int x = q[h] / c.dimension(), y = q[h] % c.dimension(), d = dist[q[h]]; if (d >= maxDepth) continue; static const int nx[4] = {1, -1, 0, 0}, ny[4] = {0, 0, 1, -1}; for (int j = 0; j < 4; ++j) { const int ax = x + nx[j], ay = y + ny[j]; if (!detail::inb(c, ax, ay)) continue; const std::size_t kk = c.index(ax, ay); if (reach[kk] && !work[kk]) { work[kk] = 1; dist[kk] = d + 1; q.push_back(int(kk)); } } } return work; } } // namespace sc2k::sim namespace sc2k::sim { std::vector ship_accessible_water(const City& c, int openClear, int maxDepth) { return ship_workable_in(c, ship_edge_reachable(c), openClear, maxDepth); } } // namespace sc2k::sim namespace sc2k::sim { bool find_berth(const City& c, int shipX, int shipY, int seaX, int seaY, int& bx, int& by, int& px, int& py, const std::vector* reach, int R) { bx = by = px = py = -1; // CONTRACT: out-params are ALWAYS defined, even on a false return. Callers // declare these holders uninitialised and (correctly) read them only on a true return — a CROSS-FUNCTION // uninitialised-local that clang's -W{conditional,sometimes}-uninitialized can't see, so a future caller // that read them on false (or a build that speculated the load) would read stack garbage. Writing the // sentinels here closes that whole class at the source, so it can't resurface (it was the latent UB the // -ftrivial-auto-var-init=zero build flag was masking). Costs four stores; behaviour for correct callers // is unchanged (the search below overwrites all four on every true return). auto isP = [&](int ax, int ay) { return detail::inb(c, ax, ay) && c.xbld.at(ax, ay) == 0xDF; }; long bAlong = 1L << 30, bAny = 1L << 30; int aX = -1, aY = -1, aPX = -1, aPY = -1, nX = -1, nY = -1, nPX = -1, nPY = -1; for (int dr = -R; dr <= R; ++dr) for (int dc = -R; dc <= R; ++dc) { const int prx = seaX + dr, pry = seaY + dc; if (!isP(prx, pry)) continue; // a pier tile static const int nx[4] = {1, -1, 0, 0}, ny[4] = {0, 0, 1, -1}; for (int k = 0; k < 4; ++k) { const int wx = prx + nx[k], wy = pry + ny[k]; if (!ship_water_at(c, wx, wy)) continue; // open water beside the pier = a berth if (reach && !(*reach)[c.index(wx, wy)]) continue; // …but only if a ship can reach it if (!ship_water_at(c, wx + nx[k], wy + ny[k])) continue; // …and the slip is ≥2 WIDE — a ship is bigger const long d = std::abs(wx - shipX) + std::abs(wy - shipY); // than a tile and can't fit/turn in a 1-wide slip // "alongside" = the berth lies against the pier's LONG side (the pier continues perpendicular to the // berth→pier step), i.e. a slip — not the tip. Prefer those so the ship lies parallel in a slip, not // nosed against an end. (wx!=prx ⇒ berth→pier is along the row, so the long edge runs along the col.) const bool along = (wx != prx) ? (isP(prx, pry + 1) || isP(prx, pry - 1)) : (isP(prx + 1, pry) || isP(prx - 1, pry)); if (along && d < bAlong) { bAlong = d; aX = wx; aY = wy; aPX = prx; aPY = pry; } if (d < bAny) { bAny = d; nX = wx; nY = wy; nPX = prx; nPY = pry; } } } if (aX >= 0) { bx = aX; by = aY; px = aPX; py = aPY; return true; } // a proper slip berth if (nX >= 0) { bx = nX; by = nY; px = nPX; py = nPY; return true; } // else any berth (isolated pier / tip) return false; } } // namespace sc2k::sim namespace sc2k::sim { bool seaport_reachable_berth(const City& c, int sx, int sy, const std::vector& reach, int R) { int bx = -1, by = -1, px = -1, py = -1; // out-param holders: initialised (find_berth always writes them) return find_berth(c, sx, sy, sx, sy, bx, by, px, py, &reach, R); } } // namespace sc2k::sim namespace sc2k::sim { bool pier_has_usable_berth(const City& c, int px, int py, const std::vector& reach) { static const int nx[4] = {1, -1, 0, 0}, ny[4] = {0, 0, 1, -1}; for (int k = 0; k < 4; ++k) { const int wx = px + nx[k], wy = py + ny[k]; if (ship_water_at(c, wx, wy) && reach[c.index(wx, wy)] && ship_water_at(c, wx + nx[k], wy + ny[k])) return true; } return false; } } // namespace sc2k::sim namespace sc2k::sim { void ship_plan_route(City& c, int idx) { ShipNav& R = ship_nav(idx); const int sx = thing_field(c, idx, thg::X), sy = thing_field(c, idx, thg::Y); const int gx = thing_field(c, idx, thg::DestX), gy = thing_field(c, idx, thg::DestY); R.wp.clear(); R.cursor = 0; R.failed = false; R.rawGoalX = gx; R.rawGoalY = gy; nav::Point goal{-1, -1}; if (detail::inb(c, gx, gy) && c.xbld.at(gx, gy) == 0xE0) { // inbound → a REACHABLE berth alongside a pier const auto reach = ship_workable_in(c, ship_water_flood(c, {sx * c.dimension() + sy})); // size-aware, from the ship's water if (R.berthX >= 0 && reach[c.index(R.berthX, R.berthY)] // keep the chosen berth if still reachable && detail::inb(c, R.pierX, R.pierY) && c.xbld.at(R.pierX, R.pierY) == 0xDF) { goal = {R.berthX, R.berthY}; } else { int bx = -1, by = -1, px = -1, py = -1; // out-param holders: initialised, not stack garbage if (find_berth(c, sx, sy, gx, gy, bx, by, px, py, &reach)) { // nearest REACHABLE slip berth + its pier R.berthX = bx; R.berthY = by; R.pierX = px; R.pierY = py; goal = {bx, by}; } else { R.berthX = R.berthY = R.pierX = R.pierY = -1; } // seaport but no usable berth → drop the stale one } } else { R.berthX = R.berthY = R.pierX = R.pierY = -1; } // dest isn't a seaport (outbound / razed) → no berth if (goal.x < 0) goal = nav::nearest_navigable(c, &ship_water_at, gx, gy, 8); // outbound, or a seaport with no pier berth if (goal.x < 0) { R.failed = true; return; } const auto clr = nav::clearance_field(c, &ship_water_at); const auto raw = nav::find_path(c, &ship_water_at, {sx, sy}, goal, &clr); if (raw.empty()) { R.failed = true; return; } R.wp = nav::smooth_path(c, &ship_water_at, raw, &clr); R.cursor = R.wp.size() > 1 ? 1 : 0; // target the first waypoint AFTER the start tile } } // namespace sc2k::sim namespace sc2k::sim { int spawn_cargoship(City& c, MsRand& rng, int ax, int ay) { if (thing_count(c, 3) >= 1) return 0; int x = -1, y = -1; // out-param holders: initialised (read only on a true return) if (!ship_entry_from_seaport(c, ax, ay, rng, x, y)) return 0; // seaport land-locked → no ship (it could only wreck) const int idx = thing_alloc(c); if (!idx) return 0; ship_nav_reset(idx); // fresh slot → drop any stale route/trail thing_field(c, idx, thg::Type) = 3; thing_field(c, idx, thg::Dir) = std::uint8_t(thing_bearing(x, y, ax, ay)); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::DestX) = std::uint8_t(ax); thing_field(c, idx, thg::DestY) = std::uint8_t(ay); thing_field(c, idx, thg::State) = 0; // inbound (0x80 clear), sub-state 0 thing_field(c, idx, thg::Frame) = std::uint8_t(x); // remember the entry edge tile (Frame=x, Link=y) so the thing_field(c, idx, thg::Link) = std::uint8_t(y); // departing ship sails back OUT to a reachable point thing_place(c, idx, x, y); return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool cargoship_step(City& c, MsRand& rng, int idx) { using namespace detail; const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); #ifdef SC2K_DEBUG { ShipNav& R = ship_nav(idx); // breadcrumb trail (visited tiles) for the debug overlay if (R.trail.empty() || R.trail.back().x != x || R.trail.back().y != y) { R.trail.push_back({x, y}); if (R.trail.size() > 96) R.trail.erase(R.trail.begin()); } } #endif if (!inb(c, x, y) || !is_water(c, x, y)) { // ran aground → wreck (the original converts to explosion) thing_field(c, idx, thg::Type) = 6; thing_field(c, idx, thg::State) = 0; thing_field(c, idx, thg::Link) = 0; thing_field(c, idx, thg::Dir) = 0; return true; } const int dxv = thing_field(c, idx, thg::DestX), dyv = thing_field(c, idx, thg::DestY); const int dir = thing_field(c, idx, thg::Dir); const int leg = thing_field(c, idx, thg::State) & 0x80; // preserved across reroute/search (0=inbound, 0x80=outbound) const bool outbound = leg != 0; switch (thing_field(c, idx, thg::State) & 0x7F) { case 0: { // sail toward the destination (case 0) if (outbound && std::abs(x - dxv) + std::abs(y - dyv) < 3) { thing_despawn(c, idx); return false; } // left the map bool moved = false; // ── DELIBERATE DEVIATION: follow a global A* route (coast-averse, smoothed) with the original's // gradual ±1-octant steer, so the ship threads winding channels instead of ricocheting. Falls // through to the faithful greedy steering below when no route is usable. { ShipNav& R = ship_nav(idx); // Replan when the dest/leg changes, the route's gone, OR (inbound) the berth broke under us — its // PIER was bulldozed or the berth tile is no longer navigable: a port destroyed mid-approach. So // the ship recalculates instead of sailing on to a phantom dock (user: "gets confused if the // target pier is removed"). const bool berthBroken = !outbound && R.berthX >= 0 && (!inb(c, R.pierX, R.pierY) || c.xbld.at(R.pierX, R.pierY) != 0xDF || !ship_water_at(c, R.berthX, R.berthY)); if (R.rawGoalX != dxv || R.rawGoalY != dyv || (R.wp.empty() && !R.failed) || berthBroken) ship_plan_route(c, idx); // Inbound, but no berth could be planned (the seaport was razed, or its piers are all gone/sealed) // → the port is no longer dockable: give up and sail back out the way we came in. (A single pier // removed while the seaport stands → the replan above just retargets a surviving berth.) if (!outbound && R.berthX < 0) { thing_field(c, idx, thg::DestX) = thing_field(c, idx, thg::Frame); thing_field(c, idx, thg::DestY) = thing_field(c, idx, thg::Link); thing_field(c, idx, thg::State) = 0x80; // turn around, head home break; } if (!R.failed && !R.wp.empty()) { while (R.cursor < R.wp.size() && // pass waypoints we've reached std::max(std::abs(x - R.wp[R.cursor].x), std::abs(y - R.wp[R.cursor].y)) <= 1) ++R.cursor; if (R.cursor < R.wp.size()) { // off the plan (knocked off course, or a cache stale for this city)? replan once from here. if (!nav::line_of_sight(c, &ship_water_at, {x, y}, R.wp[R.cursor])) ship_plan_route(c, idx); if (!R.failed && R.cursor < R.wp.size()) { const nav::Point t = R.wp[R.cursor]; if (t.x != x || t.y != y) { // (never steer toward our own tile) const int nd = thing_steer(dir, x, y, t.x, t.y); // gradual turn toward the waypoint if (ship_dir_clear(c, idx, nd)) { thing_field(c, idx, thg::Dir) = std::uint8_t(nd); ship_move(c, idx, nd); moved = true; } else if (ship_dir_clear(c, idx, dir)) { ship_move(c, idx, dir); moved = true; } // hold heading, re-evaluate next tick } } } // cursor exhausted → at the final waypoint (beside the dock / at the edge); the greedy // last-tile nudge below finishes the approach so the dock / edge-despawn checks fire. } } if (!moved) { // ── faithful greedy local steering ── if (rng.next() % 10 == 0) { // occasionally bank one octant toward the dest const int nd = thing_steer(dir, x, y, dxv, dyv); if (ship_dir_clear(c, idx, nd)) thing_field(c, idx, thg::Dir) = std::uint8_t(nd); } if (ship_dir_clear(c, idx, thing_field(c, idx, thg::Dir))) ship_move(c, idx, thing_field(c, idx, thg::Dir)); else thing_field(c, idx, thg::State) = std::uint8_t(leg | 1); // shore ahead → reroute (no hard 180° flip) } if (!outbound) { // dock only on ARRIVAL at the chosen berth — NOT on the ShipNav& R = ship_nav(idx); // first pier brushed in passing (that abandoned the route if (R.berthX >= 0 && !R.failed) { // and parked the ship on the wrong side — user-reported). if (std::abs(x - R.berthX) + std::abs(y - R.berthY) <= 1) thing_field(c, idx, thg::State) = 3; } else for (int i = 0; i < 4; ++i) { // no berth / A* failed → faithful ±2 pier trigger static const int ddx[4] = {2, 0, -2, 0}, ddy[4] = {0, 2, 0, -2}; const int ax = x + ddx[i], ay = y + ddy[i]; if (inb(c, ax, ay) && c.xbld.at(ax, ay) == 0xDF) thing_field(c, idx, thg::State) = 3; } } break; } case 1: { // reroute: turn one octant toward the dest bearing const int b = thing_bearing(x, y, dxv, dyv); const int nd = thing_step_toward_dir(dir, b); thing_field(c, idx, thg::Dir) = std::uint8_t(nd); if (nd == b) thing_field(c, idx, thg::State) = std::uint8_t(leg | (ship_dir_clear(c, idx, nd) ? 0 : 2)); break; } case 2: { // search every heading (CW/CCW) for open water static const int cw[9] = {0, 1, 2, 3, 4, 5, 6, 7, 0}; // CW heading table static const int ccw[9] = {0, 7, 6, 5, 4, 3, 2, 1, 2}; // CCW heading table const int* tbl = (rng.next() & 1) ? cw : ccw; int nd = dir; bool found = false; for (int j = 0; j < 9; ++j) { nd = (dir + tbl[j]) & 7; if (ship_dir_clear(c, idx, nd)) { found = true; break; } } // Genuinely boxed in (no navigable heading) → despawn. NB the original's escape here is // effectively DEAD: its 9-entry search tables repeat a heading, so j never lands on 8 — a trapped // ship spins between states 0/1/2 forever. We free it instead (a deliberate fix, not a port). if (!found) { thing_despawn(c, idx); return false; } thing_field(c, idx, thg::Dir) = std::uint8_t(nd); thing_field(c, idx, thg::State) = std::uint8_t(leg | 0); break; } default: { // 3 — docked: lie alongside the pier (parallel), moor, then leave ShipNav& R = ship_nav(idx); int px = R.pierX, py = R.pierY; // the pier our berth lies against — STABLE (no per-tick "nearest" if (px < 0 || !inb(c, px, py) || c.xbld.at(px, py) != 0xDF) { // chase, which made the ship wander the finger piers). int bestd = 999; px = py = -1; // fallback (no stored pier): nearest pier for (int dx = -3; dx <= 3; ++dx) for (int dy = -3; dy <= 3; ++dy) { const int ax = x + dx, ay = y + dy; if (inb(c, ax, ay) && c.xbld.at(ax, ay) == 0xDF) { const int d = std::abs(dx) + std::abs(dy); if (d < bestd) { bestd = d; px = ax; py = ay; } } } } if (px < 0) { // our dock was BULLDOZED while we sat here loading and there's thing_field(c, idx, thg::DestX) = thing_field(c, idx, thg::Frame); // no other pier to moor against → cast off NOW, thing_field(c, idx, thg::DestY) = thing_field(c, idx, thg::Link); // don't sit out the dwell stuck in empty water thing_field(c, idx, thg::State) = 0x80; // (user: a ship gets stuck if the port is demolished thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; // while it's loading) R.dwell = 0; R.berthX = R.berthY = R.pierX = R.pierY = -1; break; } const int pd = (px >= 0) ? std::abs(x - px) + std::abs(y - py) : 999; bool moored = true; if (px >= 0 && pd > 1) { // not yet alongside → one step to the tile CLOSEST to the pier int bnd = -1, bnewd = pd; for (int d = 0; d < 8; ++d) { if (!ship_dir_clear(c, idx, d)) continue; const int nd2 = std::abs(x + kThingDX[d] - px) + std::abs(y + kThingDY[d] - py); if (nd2 < bnewd) { bnewd = nd2; bnd = d; } } if (bnd >= 0) { thing_field(c, idx, thg::Dir) = std::uint8_t(bnd); ship_move(c, idx, bnd); moored = false; } } if (moored) { // alongside: lie PARALLEL to the pier (not pointing AT it) if (px >= 0) { int dirP = (thing_bearing(x, y, px, py) + 2) & 7; // fallback (isolated pier): 90° off the ship→pier bearing auto isP = [&](int ax, int ay) { return inb(c, ax, ay) && c.xbld.at(ax, ay) == 0xDF; }; auto od = [](int a, int b) { const int dd = std::abs((a & 7) - (b & 7)); return std::min(dd, 8 - dd); }; const bool rowAxis = isP(px + 1, py) || isP(px - 1, py); // the pier (finger) runs along the row axis (dirs 2/6) const bool colAxis = isP(px, py + 1) || isP(px, py - 1); // …or the col axis (dirs 4/0) if (rowAxis && !colAxis) dirP = od(dir, 2) <= od(dir, 6) ? 2 : 6; // lie along the finger, nearest the approach heading else if (colAxis && !rowAxis) dirP = od(dir, 4) <= od(dir, 0) ? 4 : 0; thing_field(c, idx, thg::Dir) = std::uint8_t(dirP); // Nudge the sprite the rest of the way to the pier (it moors one full water tile off, so it // looks like it's hovering). The renderer glides by sub-offset (rest 8,8): screen ∝ (xsub−ysub), // (xsub+ysub); shifting toward the pier's screen position needs xsub←col-step, ysub←row-step. const int pdx = (px > x) - (px < x), pdy = (py > y) - (py < y); // unit step toward the pier thing_field(c, idx, thg::Xsub) = std::uint8_t(std::clamp(8 + 6 * pdy, 1, 15)); thing_field(c, idx, thg::Ysub) = std::uint8_t(std::clamp(8 + 6 * pdx, 1, 15)); } if (R.dwell <= 0) R.dwell = 150 + int(rng.next() % 300); // moor ~30–90 s at the 5 Hz Thing tick (was a ~6 s 1/30 flit) if (--R.dwell <= 0) { // dwell elapsed → cast off, back to the REACHABLE entry edge thing_field(c, idx, thg::DestX) = thing_field(c, idx, thg::Frame); thing_field(c, idx, thg::DestY) = thing_field(c, idx, thg::Link); thing_field(c, idx, thg::State) = 0x80; // outbound, sub-state 0 thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; // re-centre for the sail out R.dwell = 0; R.berthX = R.berthY = R.pierX = R.pierY = -1; // release the berth for the trip out } } break; } } return thing_field(c, idx, thg::Type) == 3; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_sailboat(City& c, MsRand& rng, int wx, int wy) { if (thing_count(c, 9) >= 4) return 0; if (!detail::inb(c, wx, wy) || c.xbld.at(wx, wy) || c.xtxt.at(wx, wy)) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = 9; thing_field(c, idx, thg::Dir) = std::uint8_t(rng.next() & 3); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::Frame) = 0; thing_field(c, idx, thg::State) = 0; thing_place(c, idx, wx, wy); return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool sailboat_move(City& c, int idx, int dir) { static const int sdx[4] = {0, 16, 0, -16}; // sub-tile step deltas static const int sdy[4] = {-16, 0, 16, 0}; dir &= 3; const int oldXsub = thing_field(c, idx, thg::Xsub); const int oldYsub = thing_field(c, idx, thg::Ysub); int nx = sdx[dir] + oldXsub, ny = sdy[dir] + oldYsub; int carry = 0, dtx = 0, dty = 0; if (nx > 16) { nx -= 16; carry = 1; dtx = 1; } if (nx < 0) { nx += 16; carry = 1; dtx = -1; } if (ny > 16) { ny -= 16; carry = 1; dty = 1; } if (ny < 0) { ny += 16; carry = 1; dty = -1; } thing_field(c, idx, thg::Xsub) = std::uint8_t(nx); thing_field(c, idx, thg::Ysub) = std::uint8_t(ny); if (!carry) return true; const int ox = thing_field(c, idx, thg::X), oy = thing_field(c, idx, thg::Y); if (!thing_owns_cell(c, idx, ox, oy)) { thing_despawn(c, idx); return false; } const int tx = ox + dtx, ty = oy + dty; if (tx < 0 || ty < 0 || tx >= c.dimension() - 1 || ty >= c.dimension() - 1) { c.xtxt.at(ox, oy) = thing_field(c, idx, thg::SavedTile); thing_despawn(c, idx); return false; } if (c.xtxt.at(tx, ty) != xtxt::kNone) { thing_field(c, idx, thg::Xsub) = static_cast(oldXsub); thing_field(c, idx, thg::Ysub) = static_cast(oldYsub); return true; } c.xtxt.at(ox, oy) = thing_field(c, idx, thg::SavedTile); thing_field(c, idx, thg::X) = std::uint8_t(tx); thing_field(c, idx, thg::Y) = std::uint8_t(ty); thing_field(c, idx, thg::SavedTile) = c.xtxt.at(tx, ty); c.xtxt.at(tx, ty) = std::uint8_t(idx - 55); return true; } } // namespace sc2k::sim namespace sc2k::sim { bool sailboat_can_go(const City& c, int idx, int dir) { static const int adx[4] = {0, 1, 0, -1}; // tile step deltas static const int ady[4] = {-1, 0, 1, 0}; dir &= 3; const int x = thing_field(c, idx, thg::X) + adx[dir], y = thing_field(c, idx, thg::Y) + ady[dir]; if (!c.on_map(x, y)) return true; const int b = c.xbld.at(x, y); if (b == 0xF8 || b == 0xDF) return false; // marina / pier → blocked return c.xtxt.at(x, y) == 0 && detail::is_water(c, x, y); } } // namespace sc2k::sim namespace sc2k::sim { bool sailboat_step(City& c, MsRand& rng, int idx) { using namespace detail; if (thing_field(c, idx, thg::State)) { // Nessie transitioning: 4/5 hold, 1/5 vanish if (rng.next() % 5 == 0) { thing_despawn(c, idx); return false; } return true; } if (rng.next() % 4) { // 3/4: sail one tile on the current heading (no turn) const int dir = thing_field(c, idx, thg::Dir); if (sailboat_can_go(c, idx, dir)) sailboat_move(c, idx, dir); return thing_field(c, idx, thg::Type) == 9; // (might have despawned at the edge) } // 1/4: re-orient. Must still be on water, else gone. const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); if (!inb(c, x, y) || !is_water(c, x, y)) { thing_despawn(c, idx); return false; } if ((rng.next() % 4000) == 0) thing_field(c, idx, thg::State) = 1; // the rare Loch Ness roll thing_field(c, idx, thg::Dir) = std::uint8_t((thing_field(c, idx, thg::Dir) + int(rng.next() % 3) - 1) & 3); return true; } } // namespace sc2k::sim namespace sc2k::sim { bool is_train_track(int b) { return (b >= 0x2C && b <= 0x3C) || (b >= 0x45 && b <= 0x4E) || b == 0x5A || b == 0x5B; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_train(City& c, MsRand& rng, int x, int y) { if (thing_count(c, 10) >= 5) return 0; if (!detail::inb(c, x, y) || !is_train_track(c.xbld.at(x, y)) || c.xtxt.at(x, y) >= 0xC9) return 0; int dir = -1; // a random start dir, then search all 4 for track const int start = int(rng.next()) & 3; for (int t = 0; t < 4; ++t) { const int d = (start + t) & 3, nx = x + kRailDX[d], ny = y + kRailDY[d]; if (detail::inb(c, nx, ny) && is_train_track(c.xbld.at(nx, ny))) { dir = d; break; } } if (dir < 0) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = 10; thing_field(c, idx, thg::Dir) = std::uint8_t(dir); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::State) = 0; thing_place(c, idx, x, y); return idx; } } // namespace sc2k::sim namespace sc2k::sim { bool train_step(City& c, MsRand& rng, int idx) { const int x = thing_field(c, idx, thg::X), y = thing_field(c, idx, thg::Y); if (!is_train_track(c.xbld.at(x, y))) { thing_despawn(c, idx); return false; } // track gone → derail const int dir = thing_field(c, idx, thg::Dir); auto track = [&](int d) { const int nx = x + kRailDX[d & 3], ny = y + kRailDY[d & 3]; return detail::inb(c, nx, ny) && is_train_track(c.xbld.at(nx, ny)); }; int nd; if (track(dir)) { // continue ahead, branching 1-in-4 at junctions nd = dir; if ((rng.next() & 3) == 0) { const int l = (dir + 3) & 3, r = (dir + 1) & 3; if (track(l) && (rng.next() & 1)) nd = l; else if (track(r)) nd = r; } } else { // blocked → turn, else reverse const int l = (dir + 3) & 3, r = (dir + 1) & 3; nd = track(l) ? l : track(r) ? r : (dir + 2) & 3; } thing_field(c, idx, thg::Dir) = std::uint8_t(nd); const int nx = x + kRailDX[nd], ny = y + kRailDY[nd]; if (!detail::inb(c, nx, ny)) { thing_despawn(c, idx); return false; } if (c.xtxt.at(nx, ny) >= 0xC9) return true; // another thing holds it — wait this frame if (!thing_owns_cell(c, idx, x, y)) { thing_despawn(c, idx); return false; } c.xtxt.at(x, y) = thing_field(c, idx, thg::SavedTile); // vacate, claim the next track tile thing_field(c, idx, thg::X) = std::uint8_t(nx); thing_field(c, idx, thg::Y) = std::uint8_t(ny); thing_field(c, idx, thg::SavedTile) = c.xtxt.at(nx, ny); c.xtxt.at(nx, ny) = std::uint8_t(idx - 55); return true; } } // namespace sc2k::sim namespace sc2k::sim { int spawn_deploy(City& c, int type, int x, int y) { if (!detail::inb(c, x, y) || c.xtxt.at(x, y) >= 0xC9) return 0; const int idx = thing_alloc(c); if (!idx) return 0; thing_field(c, idx, thg::Type) = std::uint8_t(type); thing_field(c, idx, thg::X) = std::uint8_t(x); thing_field(c, idx, thg::Y) = std::uint8_t(y); thing_field(c, idx, thg::Xsub) = 8; thing_field(c, idx, thg::Ysub) = 8; thing_field(c, idx, thg::SavedTile) = c.xtxt.at(x, y); c.xtxt.at(x, y) = std::uint8_t(idx - 55); return idx; } } // namespace sc2k::sim namespace sc2k::sim { void clear_dispatch_units(City& c) { for (int idx = 1; idx < thg::kCount; ++idx) { const int type = thing_field(c, idx, thg::Type); if (type == 7 || type == 8 || type == 14) thing_despawn(c, idx); } } } // namespace sc2k::sim namespace sc2k::sim { int repair_thing_ownership(City& c) { int repaired = 0; for (int row = 0; row < c.dimension(); ++row) { for (int column = 0; column < c.dimension(); ++column) { const std::uint8_t link = c.xtxt.at(row, column); if (!xtxt::is_thing(link)) continue; const int slot = int(link) - int(xtxt::kThingFirst); const bool valid = slot > 0 && slot < thg::kCount && thing_field(c, slot, thg::Type) != 0 && thing_field(c, slot, thg::X) == row && thing_field(c, slot, thg::Y) == column; if (valid) continue; c.xtxt.at(row, column) = xtxt::kNone; ++repaired; } } for (int slot = 1; slot < thg::kCount; ++slot) { if (thing_field(c, slot, thg::Type) == 0) continue; const int row = thing_field(c, slot, thg::X); const int column = thing_field(c, slot, thg::Y); const std::uint8_t expected_link = static_cast(slot - 55); if (c.on_map(row, column) && c.xtxt.at(row, column) == expected_link) continue; std::fill_n(c.xthg.begin() + static_cast(slot) * thg::kStride, thg::kStride, std::uint8_t{0}); ++repaired; } return repaired; } } // namespace sc2k::sim namespace sc2k::sim { int military_base_count(const City& c) { const int m = c.military_base(); return (m >= 2 && m <= 5) ? 1 : 0; // one dispatchable base → Military dispatch lights up } } // namespace sc2k::sim namespace sc2k::sim { int dispatch_provider_count(const City& c, int type) { int code, foot; switch (type) { case 7: code = 0xD2; foot = 9; break; // police station case 8: code = 0xD3; foot = 9; break; // fire station case 14: return military_base_count(c); // 0 for now → Military unavailable (faithful) default: return 0; } int tiles = 0; for (auto v : c.xbld.cells) if (static_cast(v) == code) ++tiles; return tiles / foot; } } // namespace sc2k::sim namespace sc2k::sim { bool move_deploy(City& c, int slot, int nx, int ny) { if (!detail::inb(c, nx, ny) || c.xtxt.at(nx, ny) >= 0xC9) return false; // off-map / a unit is already there const int ox = thing_field(c, slot, thg::X), oy = thing_field(c, slot, thg::Y); if (!thing_owns_cell(c, slot, ox, oy)) return false; c.xtxt.at(ox, oy) = thing_field(c, slot, thg::SavedTile); // restore the old cell thing_field(c, slot, thg::SavedTile) = c.xtxt.at(nx, ny); // save the new cell's contents c.xtxt.at(nx, ny) = std::uint8_t(slot - 55); // sprite-link marker at the new cell thing_field(c, slot, thg::X) = std::uint8_t(nx); thing_field(c, slot, thg::Y) = std::uint8_t(ny); return true; } } // namespace sc2k::sim namespace sc2k::sim { int dispatch_unit(City& c, int type, int x, int y, std::vector& order) { const int cap = dispatch_provider_count(c, type); if (cap <= 0) return 0; // no station/base → nothing to dispatch if (static_cast(order.size()) < cap) { // under the cap → field a fresh unit const int slot = spawn_deploy(c, type, x, y); if (slot) order.push_back(slot); return slot; // 0 if the tile was bad / table full } const int slot = order.front(); // at the cap → move the oldest, rotate to newest if (!move_deploy(c, slot, x, y)) return 0; order.erase(order.begin()); order.push_back(slot); return slot; } } // namespace sc2k::sim namespace sc2k::sim { void reset_ambient_things(City& c) { for (int i = 0; i < thg::kCount; ++i) { const int t = thing_field(c, i, thg::Type); if (t == 1 || t == 2 || t == 3 || t == 9 || t == 10 || t == 11 || t == 12 || t == 13) thing_despawn(c, i); } ship_nav_reset_all(); // the ship nav is thread_local (not in the save) — clear it so no route leaks across a city load } } // namespace sc2k::sim namespace sc2k::sim { void spawn_ambient(City& c, MsRand& rng) { // Airport(0xDD) / seaport(0xE0) are a handful of tiles — scan for them and roll their spawn gates. for (int r = 0; r < c.dimension(); ++r) for (int col = 0; col < c.dimension(); ++col) { const int b = c.xbld.at(r, col); if (b == 0xDD) { // airport runway / helipad (must be powered) if ((c.xbit.at(r, col) & 0x40) && (rng.next() % 30) == 0) { if (rng.next() % 10 < 4) spawn_helicopter(c, rng, r, col); else spawn_airplane(c, rng, r, col); } } else if (b == 0xE0 && (rng.next() & 3) == 0) { // seaport dock spawn_cargoship(c, rng, r, col); } } // Sailboats live on open water (cap 4). Sample a few random tiles rather than scan the whole sea, so // they appear spread across the lakes — the original rolls this on water tiles as they're scanned. if (thing_count(c, 9) < 4) for (int t = 0; t < 8; ++t) { const int r = rng.next() % c.dimension(), col = rng.next() % c.dimension(); if (detail::inb(c, r, col) && detail::is_water(c, r, col) && !c.xbld.at(r, col) && !c.xtxt.at(r, col) && (rng.next() & 7) == 0) { spawn_sailboat(c, rng, r, col); break; } } // Trains run the rail network (cap 5). Sample a few random tiles for track and roll the spawn gate. if (thing_count(c, 10) < 5) for (int t = 0; t < 8; ++t) { const int r = rng.next() % c.dimension(), col = rng.next() % c.dimension(); if (is_train_track(c.xbld.at(r, col)) && (rng.next() & 0x1F) == 0) { spawn_train(c, rng, r, col); break; } } } } // namespace sc2k::sim namespace sc2k::sim { int ambient_things_tick(City& c, MsRand& rng, DisasterSim& d) { int alive = 0; for (int idx = 1; idx < thg::kCount; ++idx) { switch (thing_field(c, idx, thg::Type)) { case 1: airplane_step(c, rng, idx); break; case 2: helicopter_step(c, rng, idx); break; case 3: cargoship_step(c, rng, idx); break; case 9: sailboat_step(c, rng, idx); break; case 10: train_step(c, rng, idx); break; default: break; } const int t = thing_field(c, idx, thg::Type); // A crashed plane/heli/ship turns its slot into a type-6 explosion (e.g. a plane hitting a central // arcology, XBLD≥0xFB). The disaster Thing tick (things_tick) only runs WHILE a disaster is active, // so advance any such orphaned explosion here too — otherwise it never despawns and the fireball // sprite lingers permanently, blooming a fixed cluster over time (the CENTERVL arcology bug). Once a // disaster IS active, things_tick owns it (avoid double-ticking). if (t == 6) { if (!d.active) explosion_step(c, d, idx); } else if (t == 1 || t == 2 || t == 3 || t == 9 || t == 10) ++alive; } spawn_ambient(c, rng); return alive; } } // namespace sc2k::sim namespace sc2k::sim { int things_tick(City& c, MsRand& rng, DisasterSim& d, const terrain::Model* terrainModel) { int alive = 0; for (int idx = 1; idx < thg::kCount; ++idx) { const int type = thing_field(c, idx, thg::Type); if (type == thg::kTornado) { tornado_step(c, rng, d, idx, terrainModel); if (thing_field(c, idx, thg::Type) == thg::kTornado) ++alive; } else if (type == 5) { monster_step(c, rng, d, idx); if (thing_field(c, idx, thg::Type) == 5) ++alive; } else if (type == 6) { if (explosion_step(c, d, idx)) ++alive; } } return alive; } } // namespace sc2k::sim