CiviSim

Artifact [4d029a0239]
Login

Artifact 4d029a0239d96186b459bea1e534b6bbbd3e60e03a2efa0613fffa4b8b0243d8:


Civisim — 3D Isometric Grid City Simulator

Civisim is a fully 3D isometric grid city simulation engine and tabletop sandbox that runs entirely in the modern web browser. Designed with a strict zero-dependency, zero-build philosophy, the entire game—simulation engine, procedural 2D canvas texture generator, procedural 3D mesh synthesizer, goal-directed AI city planner, Three.js tabletop renderer, and responsive UI—lives in a single standalone HTML file (index.html).

Civisim runs 100% offline as an installable Progressive Web App (PWA), requires no package manager or backend, and can be served from any static file server.


Table of Contents


Core Product Overview

The Gameplay Loop

You begin with a virgin landscape featuring a meandering river, an expansive lake, and wild old-growth woodlands. As mayor and city planner:

  1. Pave the Way: Lay streets, wide avenues, and multi-span bridges over water.
  2. Zone for Growth: Paint low- and high-density zones for Residential, Commercial, and Industrial expansion.
  3. Power & Connect: Build coal, solar, or nuclear power plants, water pumping and treatment facilities, sewage systems, and gigabit fiber Internet Points of Presence (POPs).
  4. Deploy Municipal Services: Provide fire protection, police coverage, tiered education (elementary, high school, university), 5G cellular arrays, rapid-transit subway networks, entertainment, and regional airports.
  5. Watch the City Evolve: Buildings spontaneously construct and upgrade across 4 architectural stages, eventually evolving into monumental self-contained mega-arcologies.

Key Simulation Principles


Simulation Capabilities

3D Tabletop Presentation & Atmosphere

Labor Market & Economic Equilibrium

Networks & 3-Manhattan-Tile Conduit Topology

Utilities & Civic Infrastructure

Autonomous Arcology Evolution

Autonomous AI City Planner (CityPlanner)

Hazards & Adversarial Disasters

Data Overlays & Tile Inspection

Persistence & Progressive Web App (PWA)


Simulation Specifications & Statistics

Grid & Spatial Scale

Parameter Value Description
Grid Dimensions 64 × 64 tiles Total of 4,096 addressable grid tiles
Tile Size 2.0 × 2.0 world units Total world footprint: 128.0 × 128.0 units
Coordinate System grid[z][x] Row-major: 0 ≤ z < 64 (rows), 0 ≤ x < 64 (columns)
World Bounds ±64.0 units Origin (0, 0, 0) is centered at the grid midpoint
Conduit Reach ≤ 3 Manhattan tiles Maximum distance from a road tile to receive utility access
Camera View Oblique Orthographic Azimuth: π/4 + k·π/2; Elevation: atan(1/√2) ≈ 35.264°

Temporal Cadence

Metric Equivalent Time Description
1 Sim Tick 1 Sim Week 1.25 seconds in real time at standard 1× simulation speed
4 Sim Ticks 1 Sim Month ~5.0 seconds in real time
48 Sim Ticks 1 Sim Year 12 sim months; ~60.0 seconds in real time
Sim Speeds 0×, 1×, 2×, 5× Pause (0×), Normal (1.25s), Fast (0.625s), Ultra (0.25s)
Autosave Cadence Every 30 seconds Also triggers on pagehide and visibility loss
AI Planner Beat Every 2 sim ticks Up to 4 atomic tool placement actions evaluated per beat

Demographics & Building Densities

Zone / Structure Footprint Density Max Population / Capacity Notes
Residential Low (R_LOW) 1 × 1 Low (1) 40 residents Detached single-family suburban homes
Residential High (R_HIGH) 1 × 1 High (2) 240 residents High-density multi-story apartment towers
Commercial Low (C_LOW) 1 × 1 Low (1) 50 jobs Neighborhood retail shops & diners
Commercial High (C_HIGH) 1 × 1 High (2) 300 jobs Glass corporate office skyscrapers
Industrial Low (I_LOW) 1 × 1 Low (1) 50 jobs Light workshops & storage warehouses
Industrial High (I_HIGH) 1 × 1 High (2) 300 jobs Heavy manufacturing plants & factories
Residential Arcology (ARCO_RES) 2 × 2 Mega (2) 2,000 residents Self-contained Solcosit biosphere
Commercial Arcology (ARCO_COM) 2 × 2 Mega (2) 2,500 jobs Darco cyber-monolith corporate complex
Industrial Arcology (ARCO_IND) 2 × 2 Mega (2) 2,400 jobs Eco-Forge automated bio-foundry
Civic Arcology (ARCO_CIVIC) 2 × 2 Wonder 50,000 capacity Stellar Citadel launch arcology (2,500 staff)

Utility & Service Capacity Registry

Structure ID Name Size Radius Capacity Upkeep Capital Cost Primary Function
ROAD_STREET Street 1 × 1 — 100 cap §1 / wk §10 Local low-density access
ROAD_AVENUE 4-Lane Avenue 1 × 1 — 300 cap §3 / wk §25 Arterial high-capacity thoroughfare
UTIL_POWER Thermal Power Plant 2 × 2 Grid 1,000 MW §80 / wk §1,500 Coal/Gas generator (heavy smog)
UTIL_SOLAR Solar & BESS Array 2 × 2 Grid 600 MW §45 / wk §2,200 Clean renewable energy
UTIL_NUCLEAR Nuclear Power Plant 2 × 2 Grid 2,400 MW §220 / wk §6,500 Clean high-output baseload basestation
UTIL_WATER Water Tower / Well 1 × 1 Grid 300 / 750* §15 / wk §350 Inland well (300) / Shore pump (750)
UTIL_WATER_PLANT Water Treatment Plant 2 × 2 Grid 2,400 / 5,000* §65 / wk §1,800 Industrial municipal filtration
UTIL_SEWAGE Sewage Treatment 1 × 1 Grid 650 / 800* §20 / wk §450 Inland (650) / Shore discharge (800)
UTIL_SEWAGE_RECYCLE Water Reclamation 2 × 2 Grid 4,000 / 5,500* §75 / wk §2,400 Advanced closed-loop bio-digesters
UTIL_INTERNET Gigabit POP Hub 1 × 1 Grid 1,000 Gbps §30 / wk §600 High-speed fiber network backbone
SERVICE_CELL 5G Cell Tower 1 × 1 9 8,000 §25 / wk §500 Mobile coverage & office growth speed
SERVICE_CELL_METRO Metro 6G Micro-Array 1 × 1 10 28,000 §60 / wk §1,200 Ultra-dense high-capacity connectivity
SERVICE_FIRE Fire Station 1 × 1 9 2,200 §35 / wk §600 Local fire dousing & protection
SERVICE_FIRE_HQ Metro Fire HQ 2 × 2 14 16,000 §120 / wk §2,400 Regional multi-apparatus station
SERVICE_POLICE Police Station 1 × 1 9 3,000 §30 / wk §550 Crime reduction & desirability boost
SERVICE_POLICE_HQ Metro Police HQ 2 × 2 14 18,000 §110 / wk §2,200 Centralized tactical headquarters
EDU_ELEM Elementary School 1 × 1 8 1,200 §30 / wk §500 Tier 1 education (residents only)
EDU_HIGH High School 1 × 1 11 1,600 §55 / wk §900 Tier 2 secondary education
EDU_COLLEGE University Campus 1 × 1 15 2,400 §110 / wk §2,000 Tier 3 higher education & research
SERVICE_SUBWAY Subway Station 1 × 1 8 14,000 §45 / wk §1,200 -75% road traffic, +12% TOD desirability
SERVICE_AIRPORT Metropolitan Airport 2 × 2 18 32,000 §160 / wk §7,500 +22% comm demand, +20% trade revenue
ENT_CONCERT Concert Hall 1 × 1 10 5,000 §40 / wk §850 Cultural venue & entertainment coverage
ENT_STADIUM Grand Stadium 2 × 2 16 20,000 §140 / wk §3,500 Major civic sports arena
PARK Urban Public Park 1 × 1 3 — §5 / wk §100 Buffers noise and mitigates pollution

*Note: Water and sewage utilities yield significantly boosted capacities when situated along shorelines.

Fiscal & Policy Parameters


Codebase Architecture & File Structure

Repository Layout

.
├── index.html        # Complete application: HTML markup, CSS styling, and JavaScript engine (~13,900 lines)
├── AGENTS.md         # Exhaustive architectural invariants and engineering instructions for human & AI agents
├── ECONOMICS.md      # Detailed mathematical specification for the optional city economic engine
├── AIBUILDER.md      # Algorithmic design and goal heuristics for the deterministic AI city planner
├── manifest.json     # PWA manifest declaring standalone display, themes, and screen orientations
├── sw.js             # Service Worker: precaching app shell, icons, and CDN Three.js library
├── icons/            # High-resolution application and PWA maskable icons
└── .fslckout         # Fossil checkout state database (version control repository at ../civisim.fossil)

Version Control Notice: Civisim is tracked using Fossil, not Git. Avoid assuming git commands will function in this repository.

Anatomy of index.html

The entire simulation is contained within index.html, structured into clear, self-contained sections marked by section banners:

index.html
├── Lines 1–43: Head & PWA metadata (viewport, icon links, theme declarations)
├── Lines 22–1650: CSS Stylesheet (theme tokens, HUD layout, responsive tool docks, popovers, mobile sheets)
├── Lines 1651–2325: HTML DOM Shell (top HUD, left tool dock, right inspector dock, budget & save modals)
└── Lines 2326–13911: ES Module (<script type="module">)
    ├── // 1. CONSTANTS & DEFINITIONS (~L2330)
    │   Registry of ZONE_DEFS, TOOL_ZONE_MAP, overlay configs, colorways, audio frequencies, and simulation constants.
    ├── // 2. PROCEDURAL 2D CANVAS TEXTURE FACTORY (~L2849)
    │   ProceduralTextureFactory: Generates dynamic canvas textures for building facades, road asphalt, curbs, and lot status badges.
    ├── // 3. PROCEDURAL 3D BUILDING, UTILITY & PROP GENERATOR (~L3380)
    │   ProceduralBuildingBuilder: Procedural 3D Three.js geometry synthesizer for residential/commercial skyscrapers,
    │   factories, power stations, airports, stadiums, subways, and modular 2x2 arcologies.
    ├── // 4. SIMULATION ENGINE (~L6023)
    │   CitySimulation: Grid management, map seeding, graph BFS road networks, utility stamping, service coverage,
    │   demographic labor equilibrium, growth evaluation, and fiscal accounting.
    ├── // 4b. AI CITY PLANNER (~L8001)
    │   CityPlanner: Goal-directed heuristic agent that surveys city deficits, optimizes road grids, resolves utility
    │   shortages, and places zones via applyTool().
    ├── // 5. THREE.JS 3D TABLETOP RENDERER (~L9893)
    │   CityRenderer: Orthographic camera controls, day/night lighting, shadow rendering, water shaders, vehicle
    │   traffic animations, airplane flight loops, and disaster particle visualizers.
    └── // 6. APPLICATION CONTROLLER & UI BINDINGS (~L12053)
        Event loop, mouse/touch raycasting, tool selection state, modal sheet controllers, HUD updating, and autosave management.

Unidirectional Data Flow

Civisim enforces a strict unidirectional data flow to prevent desynchronization between state and graphics:

     ┌────────────────────────────────────────────────────────┐
     │              Player Input & UI Events                   │
     │     (Mouse Clicks, Touch Gestures, Keyboard, HUD)      │
     └──────────────────────────┬─────────────────────────────┘
                                │
                                ▼
     ┌────────────────────────────────────────────────────────┐
     │            Simulation Engine (CitySimulation)          │
     │      - BFS Road & Conduit Topology                     │
     │      - Power, Water, Sewage & Internet Grids           │
     │      - Regional RCI Labor Equilibrium & Growth         │
     │      - Municipal Treasury & Economic Ledger            │
     └──────────────────────────┬─────────────────────────────┘
                                │ Callbacks:
                                │  • onTileVisualChanged(tile)
                                │  • onHazardEvent(msg, tile)
                                │  • onEconomyEvent(msg)
                                │  • onPlannerEvent(event)
                                ▼
     ┌────────────────────────────────────────────────────────┐
     │             Tabletop Renderer (CityRenderer)           │
     │      - Updates Three.js Meshes & Shaders               │
     │      - Animates Traffic Fleets & Airplane Loops        │
     │      - Re-renders Modified Tile Groups Only            │
     │      (Renderer NEVER mutates Simulation State)         │
     └────────────────────────────────────────────────────────┘

Contributor Guide (Humans & AI Agents)

Whether you are a human developer or an autonomous coding agent, follow these principles when contributing to Civisim:

Quick Start

Because there are no build steps, compiling, or package installations, you only need a simple static HTTP server:

# Serve the repository root over HTTP on port 8123
python3 -m http.server 8123 --bind 127.0.0.1

# Navigate in your browser:
# http://127.0.0.1:8123/index.html

(Serving over HTTP/HTTPS is required for the Service Worker to register and manage offline caching; opening directly via file:// works for basic testing but skips offline PWA registration).

Verification & Headless Testing

Civisim contains no external test runner (like Jest or Mocha). Verification is done by executing the application in a headless browser or inspecting model states via the debug hook:

# Smoke test with headless Chromium (dumping the post-JS execution DOM)
chromium --headless=new --no-sandbox --disable-gpu --enable-unsafe-swiftshader \
  --virtual-time-budget=6000 --dump-dom "http://127.0.0.1:8123/index.html"

The ?debug=1 Diagnostic Interface

For rigorous model inspection, appending ?debug=1 to the URL exposes the core simulation, renderer, and AI planner instances globally:

// Available in developer tools when URL has ?debug=1:
window.__civisim = { sim, renderer, planner };

// Verify headless planner determinism:
window.__civisim.sim.initGrid(42);
const results = window.__civisim.planner.runHeadless('successful', { seed: 100 });
console.log(results); // { goal, reason, ok, score, ticks, actions, population, funds, checks }

Critical Invariants & Sharp Edges

When writing code or refactoring, you must preserve these architectural invariants:

  1. Row-Major Grid Indexing: Always access the grid as grid[z][x]. Never index as grid[x][z].
  2. 2×2 Zone Footprints: For multi-tile structures (Power Plants, Water Treatment Plants, Sewage Reclamation, Stadiums, HQs, Airports, Arcologies), the top-left tile is the authoritative anchor (anchorX, anchorZ). Accumulation loops for capacity, upkeep, tax income, or pollution must skip non-anchor sub-tiles, or the structure will quadruple-count.
  3. The Economy Invariant: The economy gates construction, never growth. Insolvency may refuse a new tool placement, but it must never downgrade, destroy, darken, or shrink existing buildings.
  4. Tick Pipeline Order: The sequence within CitySimulation.stepTick() is delicate:
    1. Fire spread and flood recession dousing.
    2. Labor-market demand equilibrium calculation.
    3. Tile growth progression.
    4. Network and utility recalculation.
    5. Totals recalculation (including weekly economic ledger settlement).
  5. Tile Rebuilding Discipline: Whenever a tile's visual state changes, sim.onTileVisualChanged(tile) must be invoked so CityRenderer.updateSingleTileVisual(tile) disposes the old Three.js Group before mounting new meshes, preventing GPU memory leaks.
  6. No Phantom Utilities: Utilities require a road within 3 Manhattan tiles on a connected road network to distribute power, water, sewage, or internet. An unlinked utility produces zero output.
  7. Cache & Save File Versioning:
    • If you modify index.html or assets, bump CACHE_VERSION in sw.js.
    • If you add or modify persisted tile attributes, update SAVED_TILE_FIELDS in index.html and bump SAVE_FORMAT_VERSION.

Design Documents & Further Reading

For in-depth explanations of specific subsystems, consult the companion documents: