# AGENTIC BUILD PLAN — PROCEDURAL VOXEL ANCIENT ROMAN CITY CENTRE

This revised prompt is designed for an agentic coding environment. The agent should behave as a build orchestrator: it should decompose work into modules, maintain a live build plan, run validation and linting, parallelize independent tasks when available, and assemble the final offline artifact from those modules rather than hand-writing a single monolithic blob.

The visual and technical goal remains: create a breathtaking, high-definition, procedural voxel-art simulation of an Ancient Roman city centre anchored by a massive curved Colosseum, with solid terrain, hills, Tiber River, roads, monuments, dense insulae, vegetation, water, warm lighting, Day/Sunset modes, and at least 55 FPS using instanced Three.js rendering.

---

## 1. Agentic Execution Rules

You must operate as a disciplined agent/orchestrator with the following behavior:

- Work in modular source files and assemble the final offline artifact from modules.
- Maintain a live build plan in both human-readable and machine-readable forms.
- Prefer parallel execution whenever tasks are independent and file ownership does not overlap.
- Do not integrate a module until its unit tests, lint checks, and shader validation pass.
- Do not hand-edit the final generated artifact; regenerate it from source modules.
- Preserve the offline requirement: no network requests, no CDN assets, no remote fonts, models, images, audio, or libraries.
- Three.js is mandatory for the final runtime rendering layer.
- All GLSL shaders must be verified with a GLSL linter or deterministic lint script before integration.
- Keep scope stable. If visual or technical details conflict, record the decision in the build plan and choose the option closest to the user’s objective.

---

## 2. Project Deliverable

The final deliverable must be either:

1. A single self-contained offline HTML/JS artifact, preferably one file, with all Three.js code, app modules, CSS, shaders, and generated assets embedded; or
2. A local project bundle where every runtime dependency is included locally and no network fetch occurs.

The preferred final output is:

- `dist/rome-offline.html`  
  A single offline artifact containing the complete application.

The development source should still be modular and buildable from independent files:

- `src/core/`
- `src/worldgen/`
- `src/cityplanning/`
- `src/architecture/`
- `src/rendering/`
- `src/shaders/`
- `src/controls/`
- `src/ui/`
- `src/validation/`
- `src/app/`

The build system may use any locally available bundler or build tool, such as Vite, Rollup, esbuild, Webpack, TypeScript compiler plus a custom assembler, or an agent-environment equivalent. The final runtime output must remain offline and self-contained.

---

## 3. Live Build Plan Requirement

The agent must maintain the build plan continuously. This is not optional cleanup at the end.

### Required files

- `build-plan.json`
  - Machine-readable source of truth.
  - Used to schedule tasks, dependencies, status, test results, and decisions.
- `PLAN.md`
  - Human-readable summary generated or updated from the JSON plan.
- `test-reports/`
  - Optional folder for lint reports, GLSL validation output, performance logs, and self-test results.

### Build plan structure

The machine-readable build plan must contain, at minimum:

- `project`: title, objective, constraints, target runtime.
- `status`: one of `planning`, `in_progress`, `blocked`, `testing`, `ready_for_review`, `complete`.
- `updatedAt`: ISO timestamp or agent timestamp.
- `modules`: module names, paths, dependencies, status, tests.
- `tasks`: task IDs, titles, files owned, dependencies, parallel lane, status, acceptance checks, result.
- `parallelLanes`: lane names and currently active tasks.
- `decisions`: append-only log of important technical decisions.
- `risks`: known blockers or unresolved ambiguities.
- `testResults`: module tests, integration tests, GLSL lint status, FPS/draw-call checks.
- `changelog`: append-only list of task completions and plan updates.

### Task record format

Each task should include:

- `id`: stable identifier, for example `TERR-001`.
- `title`: concise description.
- `status`: `backlog`, `ready`, `in_progress`, `blocked`, `waiting_review`, `done`, or `failed`.
- `owner`: agent lane, sub-agent, orchestrator, or `null`.
- `modules`: affected modules.
- `files`: explicit file write scope when known.
- `dependsOn`: task IDs required first.
- `parallelizable`: true or false.
- `lane`: recommended parallel lane.
- `acceptance`: tests or checks that prove completion.
- `result`: short outcome once completed.

### Agent behavior for the build plan

- Update `build-plan.json` before starting a task and again after completing it.
- If a task is blocked, mark it blocked with reason and continue independent tasks.
- Do not delete completed tasks; mark them `done` and append to changelog.
- Record any major change as a decision, for example shader syntax choice, quality tier thresholds, or landmark coordinates.
- Before each integration step, verify that all dependent module tests pass.

---

## 4. Modular Source Structure

Use this project shape unless the agent environment requires a different local convention.

- `build-plan.json`  
  Machine-readable build plan and task graph.
- `PLAN.md`  
  Human-readable progress summary.
- `package.json` or equivalent project metadata  
  Contains build scripts such as `lint:shaders`, `test`, `build:offline`.
- `src/app/main.ts` or `main.js`  
  Application entry point, renderer bootstrap, module registry wiring, render loop.
- `src/app/config.ts`  
  Seed, world dimensions, quality tiers, palette constants, key bindings.
- `src/core/types.ts`  
  Shared TypeScript interfaces or JSDoc typedefs for modules.
- `src/core/eventBus.ts`  
  Optional tiny pub/sub system for UI and controls; no heavy dependencies.
- `src/core/prng.ts`  
  Deterministic seeded random generator.
- `src/core/noise.ts`  
  Seeded value noise or simplex-like noise.
- `src/core/mathUtils.ts`  
  Clamp, lerp, spherical coordinates, Gaussian helpers, ellipse sampling helpers.
- `src/worldgen/VoxelWorld.ts`  
  Chunked voxel storage and solid-fill validation.
- `src/worldgen/TerrainGenerator.ts`  
  Heightfield, Seven Hills, flattening rules.
- `src/worldgen/Hydrology.ts`  
  Tiber River carve, water level, banks, bridge placement hook.
- `src/worldgen/BiomeMapper.ts`  
  Ground material assignment by biome, slope, road proximity, and zone.
- `src/cityplanning/SpatialAllocator.ts`  
  AABB reservation, grid occupancy, overlap prevention.
- `src/cityplanning/RoadNetwork.ts`  
  Cardo/decumanus roads, Forum streets, Colosseum ring/access roads.
- `src/cityplanning/CityPlanner.ts`  
  Zone priority, placement scoring, road snapping, landmark placement.
- `src/architecture/BuilderRegistry.ts`  
  Registry of architectural builders.
- `src/architecture/types.ts`  
  Builder interface and building descriptor types.
- `src/architecture/ColosseumBuilder.ts`  
  High-detail Colosseum generation.
- `src/architecture/LandmarkBuilders.ts`  
  Arch, temples, basilicas, colonnades, aqueducts, Circus Maximus.
- `src/architecture/ResidentialBuilders.ts`  
  Insulae blocks and residential density.
- `src/architecture/VegetationBuilders.ts`  
  Cypress trees, umbrella pines, olive shrubs.
- `src/rendering/RendererShell.ts`  
  Three.js renderer, scene, camera, resize, render loop skeleton.
- `src/rendering/ChunkedInstancer.ts`  
  Converts voxel payloads into chunked `InstancedMesh` objects.
- `src/rendering/TextureAtlas.ts`  
  Canvas-generated shared texture atlas.
- `src/rendering/VoxelMaterialFactory.ts`  
  Builds the custom or patched voxel material from shader modules.
- `src/rendering/WaterMaterialFactory.ts`  
  Tiber water shader setup.
- `src/rendering/LightingManager.ts`  
  Sun, hemisphere/ambient approximation, fog, sky colors, Day/Sunset lerp.
- `src/rendering/SkyManager.ts`  
  Procedural gradient sky and horizon blending.
- `src/shaders/voxel.vert.glsl`  
  Vertex shader for instanced voxel blocks.
- `src/shaders/voxel.frag.glsl`  
  Fragment shader for instanced voxel blocks.
- `src/shaders/water.vert.glsl`  
  Optional water vertex shader.
- `src/shaders/water.frag.glsl`  
  Water fragment shader.
- `src/shaders/sky.vert.glsl`  
  Optional sky vertex shader.
- `src/shaders/sky.frag.glsl`  
  Sky fragment shader.
- `src/shaders/shaderContracts.json`  
  Declares uniforms, attributes, varyings, and target WebGL version for each shader.
- `src/controls/GodCamera.ts`  
  Custom orbit, pan, zoom, flyover, recenter behavior.
- `src/controls/InputManager.ts`  
  Keyboard/mouse event handling.
- `src/ui/Hud.ts`  
  Minimal HUD, FPS, mode, time of day, quality level.
- `src/validation/ShaderLintRunner.ts`  
  Build-time validation entry point; not a runtime dependency unless diagnostics are enabled.
- `src/validation/RuntimeSelfTests.ts`  
  Internal checks for overlaps, voids, landmark presence, deterministic seed behavior.
- `src/validation/PerformanceGovernor.ts`  
  FPS sampling and adaptive quality switching.
- `vendor/three.min.js` or vendored local Three.js build  
  Required offline dependency; no CDN reference allowed in final output.

---

## 5. Module Contracts and Boundaries

To allow parallel work, modules must interact through stable contracts. No circular dependencies are allowed. A lower-level module must not import from a higher-level feature module.

### 5.1 Core types

`src/core/types.ts` should define or document shared shapes such as:

- `Seed = number`
- `Vec3`
- `AABB`
- `VoxelType`
- `ZoneId = "colosseum" | "forum" | "outskirts" | "river"`
- `VoxelPayload`
- `BuildCandidate`
- `AllocationResult`
- `ArchitecturalBuilder`
- `RenderChunk`
- `QualityTier`
- `TimeOfDay = "day" | "sunset"`
- `ControlMode = "manual" | "flyover"`

### 5.2 Voxel payload shape

Architecture and worldgen modules should not directly create Three.js objects when possible. They should produce renderable voxel payloads consumed by the rendering module.

Suggested fields:

- `x`, `y`, `z`
- `scaleX`, `scaleY`, `scaleZ`
- `type` or `tileIndex`
- `r`, `g`, `b` for instance color
- `ao` ambient occlusion multiplier
- `zone`
- `ownerId`, for debugging and diagnostics

### 5.3 Architectural builder interface

Every architectural generator must implement a common interface:

- `id`: unique string.
- `kind`: `colosseum`, `temple`, `basilica`, `insula`, `tree`, etc.
- `priority`: numeric placement priority.
- `zonestarget`: allowed zones.
- `getFootprint(candidate)`: returns AABB or grid footprint.
- `isValid(candidate, world, allocator)`: rejects invalid placement.
- `build(candidate, world, rng)`: writes voxels or payloads.

Builders must not mutate global state except through the provided world/allocator contracts.

### 5.4 Shader contract manifest

Each shader file must have a corresponding entry in `shaderContracts.json`.

For each shader, declare:

- `id`
- `stage`: vertex, fragment, or program
- `glTarget`: WebGL2 or WebGL1-compatible if supported
- `uniforms`: name, type, default value or required flag
- `attributes`: custom attributes beyond built-in vertex data
- `varyings`: names and types
- `sourceFiles`
- `allowedBuiltins`: Three.js/WebGL built-ins used deliberately

Example contract data for the instanced voxel shader:

- Vertex inputs: `position`, `normal`, `uv`, `instanceMatrix`, `instanceColor`, custom `aTileIndex`, custom `aAO`
- Uniforms: `map`, `uSunDir`, `uSunColor`, `uSkyAmbient`, `uGroundAmbient`, `uFogColor`, `uFogDensity`
- Varyings: `vColor`, `vUv`, `vNormal`, `vAO`, `vViewDistance`

The GLSL linter and runtime shader factory should both use this contract.

---

## 6. Parallelization Policy

Tasks should be parallelized whenever their dependencies are complete and they do not write to the same file or generated artifact.

### Recommended parallel lanes

| Lane | Focus | Typical modules |
|---|---|---|
| `lane:core` | Seed, noise, types, math utilities | `src/core` |
| `lane:world` | Terrain, river, biome mapping | `src/worldgen` |
| `lane:city` | Roads, zoning, allocator, planner | `src/cityplanning` |
| `lane:architecture` | Colosseum, landmarks, insulae, vegetation | `src/architecture` |
| `lane:rendering` | Instancing, atlas, materials, lighting | `src/rendering` |
| `lane:shaders` | GLSL files, shader contracts, lint configuration | `src/shaders` |
| `lane:controls-ui` | Camera controls, HUD, input | `src/controls`, `src/ui` |
| `lane:validation` | Self-tests, performance governor, diagnostics | `src/validation` |
| `lane:integration` | Wiring modules together and final build | `src/app`, generated bundle |

### Scheduling rules

- A task is eligible for parallel execution when all tasks in `dependsOn` are `done`.
- Two tasks may run in parallel only if their `files` write sets do not intersect.
- If the agent environment supports sub-agents, assign one lane per sub-agent where useful.
- If the environment does not support true parallelism, still prepare independent modules lane by lane and keep the task metadata accurate for future orchestration.
- Integration tasks are exclusive and sequential:
  - `INTG-001`: integrate core contracts.
  - `INTG-002`: integrate worldgen into renderer skeleton.
  - `INTG-003`: integrate cityplanning and builders.
  - `INTG-004`: integrate shaders, controls, UI.
  - `INTG-005`: final performance tuning and offline packaging.

---

## 7. GLSL Linting Requirement

All custom shaders must be verified before integration. The agent must use a GLSL linter available in the environment or implement a deterministic local linting script if no dedicated tool is present. This is a build-time requirement only; the final runtime artifact must not include unnecessary dev tooling.

### 7.1 Shader organization

- Keep shaders as raw files:
  - `src/shaders/*.vert.glsl`
  - `src/shaders/*.frag.glsl`
- Do not bury core shader logic only inside inline strings if linting is possible. If a shader must be patched at runtime, extract all custom chunks into separate `.glsl` source files first.
- Maintain `shaderContracts.json`.

### 7.2 Lint command

Define a project script:

- `npm run lint:shaders`
- or the environment equivalent.

The command must:

- Discover all shader sources from `src/shaders/`.
- Load `shaderContracts.json`.
- Parse each shader with the available GLSL linter.
- Produce zero errors for a passing build.
- Save a report, preferably in `test-reports/glsl-lint.json` or equivalent.

If a dedicated linter is unavailable, implement a local validator that at minimum checks:

- balanced braces and parentheses
- required entry point `main()`
- fragment shader precision declaration when required by target GLSL version
- semicolon presence after statements
- no undeclared identifiers that are not in the contract or built-in allowlist
- vertex-to-fragment varying name and type compatibility
- allowed uniform and attribute names per shader contract
- no accidental use of non-deterministic random behavior without a seeded uniform

### 7.3 Required lint checks for this project

Shader integration fails if any of these produce errors:

- Syntax errors in any `.glsl` file.
- Missing `main()` in vertex or fragment stages.
- Missing precision qualifier in WebGL2/WebGL1 fragment sources where required.
- Unknown custom attributes not present in the voxel renderer payload.
- Unknown uniforms not declared in `shaderContracts.json`.
- Mismatched varyings between vertex and fragment shaders.
- Deprecated or ambiguous built-in usage for the chosen WebGL target.
- Shader source references assets, textures, or includes that would require network access.
- Non-deterministic shader animation unless explicitly driven by a seeded or time uniform approved in diagnostics.

### 7.4 Runtime shader validation

When the final app boots in debug/self-test mode:

- Validate that required uniforms exist on each material.
- Validate that required custom attributes are present on instanced geometries.
- Log shader compilation/link errors if available.
- Fail self-tests if any material reports a GLSL compile error.

---

## 8. Build and Integration Workflow

The agent should use this workflow:

1. Initialize `build-plan.json` and `PLAN.md`.
2. Scaffold modules with stubs, types, build scripts, and lint setup.
3. Run parallel independent module tasks according to the dependency graph.
4. After each module task:
   - Run unit tests or deterministic checks.
   - Update build plan status.
5. Before integration:
   - Run shader linting.
   - Run overlap validation.
   - Run void/terrain validation.
   - Run deterministic seed check if applicable.
6. Integrate modules through `src/app`.
7. Build the final offline artifact.
8. Run offline smoke tests and performance validation.
9. Update final plan status to `complete` with test evidence.

---

## 9. Parallel Execution Waves

The following is the recommended execution graph. Exact task IDs should be stored in `build-plan.json`.

### Wave 0 — Bootstrap, sequential

Tasks:

- `BOOT-001`: create live build plan files.
- `BOOT-002`: scaffold modular source tree and app entry point.
- `BOOT-003`: establish core type contracts and module registry.
- `BOOT-004`: configure GLSL lint command and shader contracts file.
- `BOOT-005`: add basic diagnostics and test harness hooks.

Gate:

- Build plan exists.
- Project can be inspected without errors.
- Shader lint script runs on empty or sample shaders and outputs a report.

### Wave 1 — Parallel foundational modules

All depend on Wave 0 and can run in parallel if files are disjoint.

| Lane | Tasks | Output |
|---|---|---|
| `lane:core` | `PRNG-001`, `NOISE-001`, `MATH-001` | Deterministic random, noise, math utilities. |
| `lane:rendering` | `ATLAS-001`, `CHUNKER-001-skeleton` | Canvas texture atlas, chunked instancer interface. |
| `lane:shaders` | `SHADERS-001-contracts`, `SHADERS-002-lint-pass` | Shader contract schema, placeholder shaders pass lint. |
| `lane:controls-ui` | `CAMERA-001`, `HUD-001` | Camera and HUD stubs using contracts. |
| `lane:city` | `ALLOC-001`, `ROADS-001-schema` | AABB allocator, road data schema. |
| `lane:architecture` | `REGISTRY-001` | Builder registry and builder interface. |

Gate:

- Unit tests for core utilities pass.
- Shader contracts validate sample shaders.
- Allocator has zero-overlap unit test.
- Controls can rotate/pan/zoom a dummy scene.

### Wave 2 — Worldgen and planning in parallel

Depend on Wave 1.

| Lane | Tasks | Output |
|---|---|---|
| `lane:world` | `TERRAIN-001`, `RIVER-001`, `BIOME-001` | Heightfield, Seven Hills, river carve, biome assignment. |
| `lane:city` | `ALLOC-002`, `PLANNER-001`, `ROADS-002` | Full road network, zoning, placement scoring. |
| `lane:rendering` | `CHUNKER-002`, `VOXEL-MATERIAL-001` | Terrain payloads render with instanced voxel material. |
| `lane:shaders` | `VOXEL-SHADERS-001`, `WATER-SHADER-001` | Instanced voxel and water shaders pass lint. |

Gate:

- Terrain is solid.
- River exists at map edge.
- Roads are reserved and visible.
- Terrain renders via chunked instancing.
- Voxel and water shaders lint clean.

### Wave 3 — Architecture in parallel

Depend on planner/world contracts.

| Lane | Tasks | Output |
|---|---|---|
| `lane:architecture` | `COLOSSEUM-001`, `LANDMARKS-001`, `RESIDENTIAL-001`, `VEGETATION-001` | Colosseum, Forum landmarks, insulae, vegetation. |
| `lane:rendering` | `DYNAMIC-PAYLOADS-001` | Crowd/gladiator/velarium payload handling. |
| `lane:shaders` | `VELARIUM-SHADER-001`, `CROWD-MATERIAL-001` if separate | Instanced small-object materials validated. |

Gate:

- Zero building overlap.
- Colosseum curved and dominant.
- Forum landmarks present.
- Insulae snap to roads.
- Vegetation does not block monument views excessively.

### Wave 4 — Integration, exclusive sequential

Tasks:

- `INTG-001`: integrate worldgen payloads into renderer shell.
- `INTG-002`: integrate city planner and all builders through registry.
- `INTG-003`: integrate shaders, lighting, water, sky, and time-of-day.
- `INTG-004`: wire camera, input, HUD, and flyover mode.
- `INTG-005`: connect diagnostics, self-tests, and performance governor.

Gate:

- Full procedural city appears from one boot.
- Controls and shortcuts work.
- Self-tests report zero overlap and zero ground voids.
- Shaders compile without runtime errors.

### Wave 5 — Polish, performance, final validation

Tasks:

- `PERF-001`: tune chunk size and instance count.
- `PERF-002`: adaptive quality tiers.
- `PERF-003`: FPS governor with hysteresis.
- `VIS-001`: warm Mediterranean lighting polish.
- `VIS-002`: crowd density balance.
- `VIS-003`: river reflection/fresnel polish.
- `VAL-001`: full offline and acceptance validation.

Gate:

- Target 55 FPS sustained after warm-up or adaptive quality reaches acceptable state.
- Draw call budget met.
- Final artifact runs with no network requests.

---

## 10. World Generation Requirements

### Terrain

- Map size should be approximately 1024 x 1024 base voxels unless performance evidence requires adjustment.
- The ground must be a continuous solid voxel volume from base level up to terrain height.
- Seven Hills should be recognizable but organic, not artificial cones.
- The Colosseum footprint, main roads, Forum rectangle, and major monument pads must be flattened or softened.
- No visible floating tiles.
- Add map-edge side skirts or a base slab so low-angle camera views do not reveal emptiness.

### Seven Hills

Generate hills with seeded Gaussian bumps plus noise:

- Different amplitudes and radii.
- Smooth transition into city areas.
- Hillside vegetation placement based on slope and elevation.
- Avoid tall hills obscuring the Colosseum from default view.

### Tiber River

- Place river near one map edge, not through the central monuments.
- Use a seeded meander or curved carve.
- Width: approximately 30 to 60 units.
- Water surface level below nearby street pads but above riverbed.
- Riverbanks should transition from water to dirt, gravel, and grass.
- At least one bridge or ford may be added if performance budget allows.

### Biome palette

Use warm historical materials:

- Travertine: creamy limestone for Colosseum and public monuments.
- Marble: white-grey for temples and basilicas.
- Terracotta: orange-brown roofs.
- Porphyry: purple-red accents.
- Gold: temple roof ridges and decorative trim.
- Cobblestone: roads and plazas.
- Dirt: hillside and foundation material.
- Grass: hills and banks.
- Sand: arena floor.

---

## 11. City Planning Requirements

### Allocation system

Use a two-level collision system:

1. Integer grid occupancy for fast footprint checks.
2. AABB records for precise building bounds and diagnostics.

Placement flow:

1. Reserve Zone A Colosseum area first.
2. Generate main roads and Forum street grid.
3. Place major landmarks by fixed priority.
4. Fill remaining valid cells with insulae using scoring.
5. Place vegetation where allowed.
6. Run final overlap validation.

Overlap rule:

- Final overlap count must be zero.
- If a minor building cannot fit, skip it.
- Do not move the Colosseum or major Forum landmarks to fix minor residential placement.

### Zones

| Zone | Purpose | Content |
|---|---|---|
| A | Monument core | Colosseum, ring road, gates, immediate plaza |
| B | Forum/civic center | Temples, basilicas, colonnades, arches, paved areas |
| C | Residential and outskirts | Insulae, hills, vegetation, distant infrastructure |
| D | River edge | Water, banks, limited crossing structures |

### Roads

Generate:

- Decumanus: primary east-west axis.
- Cardo: primary north-south axis.
- Forum grid streets.
- Colosseum access roads and ring connection.
- Road network connecting major landmarks if possible.

Rules:

- Major roads width 8 to 12 units.
- Secondary Forum streets width 4 to 6 units.
- Buildings align and snap to roads with setback.
- Roads cannot overlap buildings.
- Roads must be visually readable as cobblestone or light stone.

---

## 12. Architectural Requirements

### Colosseum

The Colosseum is the centerpiece and must feel large and curved.

Required:

- Elliptical or super-elliptical footprint.
- At least 160 to 220 facade bays around the circumference.
- Smaller detail voxels than the surrounding city, preferably 0.5 base units for facade details.
- Multi-level arcade structure:
  - Ground level arches.
  - Second level openings.
  - Third level windows/openings.
  - Upper attic band.
- Cornices and pilasters.
- Four main gates or emphasized entrances.
- Internal cavea tiers following concentric ellipses.
- Arena floor in sand color.
- Hypogeum: exposed underground maze under a cutaway portion of the arena floor.
- Velarium: masts and translucent awning panels over or near the upper cavea.
- Crowd voxels densely populating visible seating tiers.
- Gladiators as small voxel groups in the arena centre.

Curvature check:

- From default flyover distance, the Colosseum must not look rectangular or square.
- The outer silhouette should clearly follow an ellipse.

### Forum landmarks

Include at least:

- Arch of Constantine equivalent:
  - Triple arch.
  - Central arch taller than sides.
  - Travertine body with porphyry and gold accents.
- Temple of Venus and Roma or abstract equivalent:
  - Raised marble platform.
  - Columns.
  - Dual sanctuary or elongated cella suggestion.
  - Gold roof accents.
- Two basilicas:
  - Elongated public hall shape.
  - Apse.
  - Clerestory or arcade rhythm.
- Colonnades along Forum axes.
- Smaller temples or shrines for density.

### Residential insulae

Generate dense apartment blocks in Zone C and along secondary roads.

Required:

- Road-aligned footprints.
- Height variation around 4 to 8 stories.
- Terracotta roofs or flat roof edges with clay tones.
- Window grids, doorways, and varied facade color.
- No overlap with roads, landmarks, water, or steep invalid terrain.

### Infrastructure

Include:

- Aqueducts across horizon or map edge with repeating arches.
- Optional distant Circus Maximus track if budget allows.
- If quality tier lowers, preserve simplified ground footprint rather than hiding the layout entirely.

### Vegetation

Scatter:

- Italian cypress: tall, narrow, dark green.
- Umbrella pines: shorter trunks with wide flat canopies.
- Olive shrubs: low irregular light-green clusters.

Placement:

- Prefer hillsides and riverbanks.
- Avoid roads, water, buildings, arena floor, and monument platforms.
- Maintain spacing.
- Use density gradients to frame architecture rather than cluttering it.

---

## 13. Rendering Requirements

### Instancing

Use Three.js `InstancedMesh` as the primary rendering method.

Rules:

- Reuse a single base cube geometry where possible.
- Split instances into chunks for frustum culling and memory control.
- No individual `THREE.Mesh` per voxel.
- Use instance matrices for position/scale/rotation.
- Use per-instance color for crowd, facade variation, and material tinting.
- Use custom instanced attributes for texture atlas tile index and AO where needed.
- Dynamic objects such as gladiators may use separate small instanced meshes or grouped transforms, but still avoid per-voxel mesh objects.

### Texture atlas

Generate a shared texture atlas with Canvas API.

Suggested:

- Atlas size: 1024 x 1024.
- Tile grid: 16 x 16.
- Tile size: 64 x 64.
- Tiles for cobblestone, stone, travertine, marble, terracotta, gold, dirt, grass, sand, porphyry, dark hypogeum stone, and neutral crowd tiles.

Rules:

- Generate at runtime, not from external files.
- Add subtle noise variation; avoid harsh patterns.
- Use mipmaps if supported.
- Prevent atlas bleeding with small UV insets.

### Voxel shader

Use a custom ShaderMaterial or patched built-in material that supports instanced voxel rendering.

Required features:

- Sample shared texture atlas based on per-instance tile index.
- Support per-instance color.
- Support per-instance ambient occlusion multiplier.
- Simple Lambert-style sun lighting.
- Hemisphere ambient approximation using warm ground bounce and sky tone.
- Fog support.
- Time-of-day uniforms.
- Efficient fragment code suitable for hundreds of thousands of instances.

### Water shader

The Tiber must use a separate semi-transparent water material.

Required:

- Blue-green base color.
- Animated procedural ripple pattern using sine/noise and time uniform.
- Fresnel-like blend toward sky color at shallow angles.
- Sun glint approximation.
- No external textures or environment maps unless fully generated in code.

### Lighting and atmosphere

Implement Day and Sunset states.

Day:

- Warm white sun.
- Blue-grey Mediterranean sky tint.
- Balanced shadows/depth.
- Fog blends into horizon.

Sunset:

- Low-angle orange-gold sun.
- Warmer fog.
- Peach/orange horizon and soft blue-violet upper sky if using sky shader.
- Stronger depth silhouette for Colosseum and hills.

Toggle with `T` key, with smooth interpolation over approximately 0.6 to 1.0 seconds.

### Ambient occlusion

Bake approximate AO during generation:

- Darken surfaces under overhangs.
- Darken cavea recesses.
- Darken hypogeum corridors.
- Preserve sunlit top faces.
- Use AO values roughly between 0.55 and 1.0 to keep materials rich.

Shadow map usage:

- Optional on high quality only.
- If enabled, limit shadow camera to the central monument area for performance.
- Do not rely solely on dynamic shadows for depth; baked AO must carry most of the visual grounding.

---

## 14. Controls and UI

### Camera

Implement a custom god-mode orbit camera. Do not rely on externally fetched OrbitControls code.

Required:

- Left-click drag rotates around target.
- Right-click drag pans target in camera plane.
- Scroll wheel zooms/dollies.
- Smooth damping.
- Reasonable radius, polar angle, and world-bound clamps.
- High-altitude overview capable of showing the full city centre.

### Keyboard shortcuts

Required:

- `R`: re-centre on Colosseum with smooth transition.
- `F`: toggle flyover mode with constant rotation.
- `T`: toggle Day/Sunset time of day.

Recommended:

- `H`: toggle help overlay.
- `D`: toggle debug/diagnostics overlay.
- `1` / `2` / `3`: force quality tiers if useful.

### HUD

Minimal DOM overlay with:

- FPS.
- Quality tier.
- Mode: manual or flyover.
- Time of day.
- Optional draw calls and instance counts in debug mode.

Style:

- Small, non-obstructive translucent panel.
- System font or embedded system stack only.
- No external CSS or fonts.

---

## 15. Validation, Testing, and Performance

### Module-level tests

Each module should have deterministic checks.

Examples:

- PRNG/noise: same seed produces same output.
- Allocator: overlapping candidate rejected; valid candidate accepted.
- Terrain: every visible surface column has fill to base level.
- Roads: reserved cells cannot be built on.
- Builders: generated bounding boxes do not overlap other registered boxes.
- Shaders: lint command exits zero.
- Renderer: draw-call count and instance count accessible from diagnostics.
- Controls: programmatic tests or runtime smoke checks for key handlers.

### Runtime self-tests

Expose a lightweight internal self-test mode, such as `?selftest=1`, that runs after boot and writes results to diagnostics.

Checks:

- No external network requests.
- Colosseum present.
- Forum landmarks present.
- Aqueduct or horizon infrastructure present if enabled by quality tier.
- Zero AABB overlaps.
- Zero ground void columns.
- Shader compilation errors count is zero.
- FPS after warm-up and current quality tier.

### Diagnostics object

Expose a debug object, for example:

- `window.__ROMA_DIAGNOSTICS`

Fields:

- `seed`
- `fps`
- `qualityTier`
- `drawCalls`
- `visibleInstances`
- `overlapCount`
- `voidColumnCount`
- `shaderErrors`
- `timeOfDay`
- `cameraMode`

Field names may vary, but equivalent diagnostics must be available.

### Performance target

Target:

- At least 55 FPS on a modern desktop browser at default quality or after automatic quality selection.

Budgets:

- Typical draw calls should remain low, ideally 60 or fewer average and under 120 peak.
- Avoid per-frame allocations in the render loop.
- Use chunked instancing and frustum culling.
- Adaptive quality should reduce in this order if needed:
  1. Crowd density.
  2. Vegetation count.
  3. Distant infrastructure detail.
  4. Shadow maps.
  5. Water animation complexity.
  6. Far fog and horizon detail.

Quality tiers:

| Tier | Shadows | Crowd | Vegetation | Water | Infrastructure |
|---|---|---|---|---|---|
| High | Optional central shadow map | Full | Full | Animated fresnel/ripple | Full or detailed simplified |
| Medium | Off or low-res | Reduced | Reduced | Simple ripple | Reduced |
| Low | Off | Sparse | Sparse | Static or simple | Ground footprints/silhouettes |

The performance governor must use hysteresis to avoid rapid tier oscillation.

---

## 16. Offline Packaging Requirements

Final artifact rules:

- No CDN links.
- No remote imports.
- No remote fonts, images, models, audio, or CSS.
- No runtime `fetch()` for project assets.
- Three.js must be embedded in the final artifact or included as a local vendored file with no network dependency.
- All textures must be generated at runtime via Canvas or encoded locally.
- Shaders may be embedded into the final bundle by the build process, but they must originate from linted raw shader files during development.
- Generated assets should not require CORS or local server assumptions unless absolutely necessary; a directly openable single HTML file is preferred.

The agent must run an offline smoke test:

- Load artifact with network disabled or by checking network request count.
- Confirm scene initializes.
- Confirm controls work.
- Confirm no shader compile errors in console.
- Confirm diagnostics report reasonable FPS and zero overlaps.

---

## 17. Acceptance Criteria

The project is accepted only when all of the following are true.

### Agentic workflow

- `build-plan.json` exists and is updated throughout the work.
- `PLAN.md` reflects current progress.
- Task graph contains dependencies and parallel lane metadata.
- Independent tasks were executed in parallel where possible or explicitly marked as serial due to file conflicts.
- Integration did not bypass module contracts.
- Build plan records test evidence for shader linting, overlap validation, and performance.

### Modular structure

- Source is modular rather than a hand-written monolith only.
- Final artifact is generated from modules through a build process.
- Modules have clear dependency boundaries.
- Architecture modules do not directly create per-voxel Three.js meshes where payloads/instancing are intended.

### Shaders

- All custom shaders pass the GLSL linter with zero errors.
- Shader contracts match actual attributes, uniforms, and varyings.
- Runtime shader compilation reports zero errors.

### World and architecture

- The Colosseum is massive, central, curved, and detailed.
- Cavea, hypogeum, crowd, gladiators, and velarium are present.
- Forum contains Arch of Constantine equivalent, Temple of Venus and Roma equivalent, basilicas, and colonnades.
- Residential insulae fill the outskirts and secondary roads without overlap.
- Tiber River exists at map edge with distinct water material.
- Seven Hills terrain is visible and frames the city.
- Ground is solid with no voids.
- Roads are clear and guide building placement.

### Controls and visuals

- Left-click rotates, right-click pans, scroll zooms.
- `R`, `F`, and `T` work as specified.
- Day/Sunset toggle is visually distinct.
- Warm Mediterranean lighting and historical palette are present.
- AO or directional depth shading gives the voxel scene dimension.

### Performance and offline

- Target FPS is at least 55 after warm-up, with adaptive quality if needed.
- Draw calls and instance counts are within budget.
- Final artifact makes zero network requests.
- Three.js is included as mandatory runtime foundation without remote loading.
- No external assets are used at runtime.

---

## 18. Final Output Instruction

Generate the complete agentic project now.

The output must be implementation-ready, not a conceptual outline. It should include:

- The modular source structure.
- Build scripts for offline assembly and shader linting.
- A maintained `build-plan.json` or equivalent task graph.
- Module implementations for world generation, city planning, architecture, rendering, shaders, controls, UI, validation, and performance governance.
- All GLSL shaders verified through the linter workflow.
- Final generated offline artifact or instructions/scripts that deterministically produce it from modules.

During execution, prioritize parallel module work, update the build plan after every task, run shader linting before integration, validate zero overlap and solid ground, and assemble the final self-contained Three.js application from validated modules.
