Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): build the island - world V1 of the Jarvis Agents section
rubenluetke10-beep0e2044d28e99
diff --git a/docs/agent-society/MASTERPLAN.md b/docs/agent-society/MASTERPLAN.mdindex 9d8b9f4224..50d06c25e9 100644--- a/docs/agent-society/MASTERPLAN.md+++ b/docs/agent-society/MASTERPLAN.md@@ -149,7 +149,16 @@ mission running), a **meeting pavilion** (bounded rooms, visible round counter "pending approvals), and **Jarvis' lighthouse** (the lead agent, mapped to the voice orb). Idleagents wander the island client-side (rest-biased, exponential dwell).Click a figure → model card. HUD: active count, today's cost (from the costs ledger, §5), "Active-now" face strip. A **Ledger tab** keeps the current DepartureBoard as the data-dense secondary view+now" face strip.++**Island layout (maintainer decisions 2026-09-01/02, binding detail in+[`world-art-direction.md`](world-art-direction.md)):** the island is a 10 × 10 grid of screen-sized+fields; the central 4 × 4 fields are the **market district** — a solarpunk village in a ring+around ONE open square (the meeting place, with the big tree and the long table), the lead's hub+at the head of the square, the workshop / archive / harbor gate / lighthouse in the four quarters+around it. Camera: steep bird's-eye (50° pitch, 45° yaw), fine pixel grain (2 screen px per+rendered px), three fixed zoom steps, drag / keys / minimap navigation. The meeting pavilion of+the first sketch became the square itself. A **Ledger tab** keeps the current DepartureBoard as the data-dense secondary view— and is the *declared* fallback wherever WebGL is absent, reduced motion is requested, or thebox is headless.@@ -358,6 +367,11 @@ Decided 2026-09-01:society — backend and UI — is built in-house (§7).8. **Build start:** frontend card work may proceed on clearly-labeled sample data while M1 lands(`components/society/data.ts` is the single swap point).+10. **World layout & art direction (2026-09-01/02):** colourful pixel island, solarpunk village in+ a comic-village ring around the central market square (4 × 4 of 10 × 10 fields), steep+ bird's-eye camera, fine pixel grain, three zoom steps + minimap — see+ [`world-art-direction.md`](world-art-direction.md) (binding for M3 world work). V1 of the+ island ships as the World face of the Jarvis Agents section with the board as its Ledger.9. **Agent definition & ecosystem wiring:** see [`agent-definition.md`](agent-definition.md)(binding). Highlights: full customization per agent (brain, grant/focus/deny over ONEcapability catalog of plugins + CLIs + MCPs + skills, approval rules, budget, workspace);diff --git a/docs/agent-society/world-art-direction.md b/docs/agent-society/world-art-direction.mdnew file mode 100644index 0000000000..83c2e1aa6d--- /dev/null+++ b/docs/agent-society/world-art-direction.md@@ -0,0 +1,129 @@+# World Art Direction — the island++Status: **binding for M3 (world), decided with the maintainer on 2026-09-01/02.**+Subordinate to [`MASTERPLAN.md`](MASTERPLAN.md) §4.1/§4.3; this is the art-direction pass the+master plan requires before environment assets are built. Figures are governed by+[`character-pipeline.md`](character-pipeline.md). Code: `jarvis/ui/web/frontend/src/components/society/world/`+(model in `islandLayout.ts`, colours in `worldPalette.ts`).++## 1. The picture in one paragraph++A bright pixel island in the warm light of a late afternoon — the softness and colour of a+cosy farming game rendered in true 3D — on which a small **solarpunk village** stands: white walls,+glass bands, solar barrel roofs, garden roofs, wood accents, rounded shapes. The village is laid+out like a classic comic village: a ring of houses around ONE open square where everyone gathers,+the biggest house at the head of the square. Around the village, four quarters carry the working+places of the society. Seen steeply from above, lightly pixelated, never dark, never monochrome.++## 2. Decisions (maintainer, 2026-09-01/02)++| # | Question | Decision | Why it beat the runner-up |+|---|---|---|---|+| 1 | Look | **Colourful pixel island** (cosy-farming-game softness in 3D) | matches "bright, beautiful, lightly pixelated"; a block diorama or clean low-poly would lose the warmth |+| 2 | Camera | **Steep bird's-eye: 50° below the horizon, 45° dimetric yaw**, orthographic | reads as "from above" yet keeps house fronts and figure silhouettes; 30–35° gives more façade but less overview |+| 3 | Size | **10 × 10 fields; the central 4 × 4 fields are the market district** | the maintainer wants a big island that is not seen in one screen; one field = one screen at the closest zoom |+| 4 | Landscape | **A village / small town** on a green island: meadows, beach, a bay, one rocky highland | free-text decision: "a village, ultramodern, future-oriented" |+| 5 | Architecture | **Solarpunk village** — white + glass + solar + gardens + wood, lots of green between | colourful AND futuristic; pure factory grey or neon-cyber contradicts the bright island |+| 6 | Centre | **Comic-village ring structure, modernised**: houses around the open square, the big tree with the long table in the middle, the lead's hub at the head (north) | the maintainer's own image ("Asterix-style village structure, only modern") |+| 7 | Pixel grain | **Fine — 2 screen pixels per rendered pixel** (a 1280-px stage renders at 640 px) | figures and signs stay readable; 320×180 would be too coarse for a big island |+| 8 | Navigation | **Drag + arrow keys/WASD, three fixed zoom steps (32 / 64 / 128 m), minimap** | 100 fields need zoom to find an agent; fixed steps keep pixels crisp |++Decided by the build, open to the maintainer: fixed warm-afternoon light in V1 (a real-clock+day/night cycle is a later flavour); animated pixel water; the hub carries the pulsing beacon+that will map onto the voice orb.++## 3. Layout++Units: 1 world unit = 1 m; one tile = 2 m; the island is 160 × 160 tiles (320 m). World origin+is the island centre; +x east, +z south.++```+ N (archive tower)+ |+ solar | rock highland+ field |+W (workshop)—[ MARKET DISTRICT ]—(lighthouse cape) E+ |+ gardens |+ greenhouses|+ S (harbor gate + dock in the bay)+```++**Market district (64 × 64 tiles, one flat plateau):**+- open square, radius 13 tiles, paved; garden beds alternate around its rim;+- the big tree in the exact centre, a ring bench around it, the long table on the south side —+ this is the `meeting` checkpoint (MASTERPLAN §2.7);+- 12 houses on a ring at radius 19 tiles, doors facing the square; the four cardinal directions+ stay open as gates; three variants cycle: solar-barrel roof, garden roof, glass loft;+- the **hub** (lead agent) at the head of the square, north, radius 20: the largest building,+ glass band, dome, beacon mast;+- ring road at radius 25, hedge ring with four gates at radius 29, lamps along the spokes;+- four spokes (width 3 tiles) from the square to the quarters.++**Quarters and checkpoints** (backend place → island place, `Walkers.tsx`):++| checkpoint | place | building |+|---|---|---|+| `desk` | workshop (west) | long hall, sawtooth skylights, wide door toward the village |+| `meeting` | market square | the table under the big tree |+| `archive` | archive (north) | round tower, two glass bands, blue dome |+| `gate` | harbor gate (south) | gate pillars over the dock into the bay, kiosk, moored boat |+| — | lighthouse (east cape) | striped tower with rotating lamp, keeper's hut |+| — | gardens (south-east) | six glass greenhouses on garden tiles |+| — | solar field (north-west) | 35 tilted panels on posts |++Idle agents (`idle`) wander inside the square with the rest-biased model (`wander.ts`);+paused agents stand still.++## 4. Palette++Everything inside the viewport comes from `worldPalette.ts`. Never a theme token, never Ink &+Paper, never the Cursor design doc (MASTERPLAN §4.3). Two shades per terrain kind give the+tile-art flicker under the pixel pass.++| Role | Colours |+|---|---|+| sky / clear | `#a5dbff` |+| sea | surface `#44a0dd`, deep `#2f7fc4`, ripple `#8fd0f4`, foam `#d9f2ff` |+| sand | `#f3e2ad` / `#ead597` |+| grass | `#7ccb5c` / `#6fbe51`; meadow (high ground) `#97d46c` / `#8ac860` |+| rock | `#a8a7b3` / `#9a99a6`, faces `#6f6e7c` |+| square / paths | `#ece1cf` / `#e2d5c0`; paths `#dcc9a5` / `#d0bd97` |+| cliff faces under grass | `#8e6a44` |+| walls | `#f7f3ea` / `#e6e0d2`, trim `#c9c2b2` |+| glass | `#8ed2f0` (unlit — it glows) |+| solar | `#26375a`, seams `#3e5f95` |+| wood | `#b57f45` / `#8c5e2f`, doors `#e0893b` |+| lead accent | `#2f6f8f` (the Jarvis palette of the roster), beacon `#ffe08a` |+| trees | trunk `#7a5230`, canopies `#4faf49` / `#6cc35e` / `#93da7c` |+| in-world type | Pixelify Sans (OFL, bundled via fontsource), ink `#1f2a3a` on cream chips |++Light: hemisphere sky `#d6ecff` / ground `#7f9c5a`, one warm directional sun `#fff1d6` from the+south-west, **no tone mapping** (`flat`), no shadows (a 2-px shadow is noise; a blob decal under+the feet comes with the figure pipeline). Materials: Lambert for lit surfaces, Basic for glass,+lamps and beacons — never PBR.++## 5. Rendering rules++- Orthographic camera, `RenderPixelatedPass` (normal edge 0.18, depth edge 0.28) ++ `OutputPass`, `dpr = 1`, antialias off. Pixel size is an integer (2); zoom never scales the+ pixel grid.+- Terrain is ONE merged vertex-coloured mesh; trees, hedges, lamps, panels and greenhouses are+ instanced; buildings are shared unit geometries scaled per use, sharing ~25 materials through+ `WorldKit`.+- Every canvas mounts through `useWebglSurface`; the loop pauses via IntersectionObserver;+ reduced motion → demand-driven frames, no wander, no water drift; no WebGL → fallback to the+ Ledger.+- DOM over the canvas (nameplates, place signs, HUD) is legible at every zoom because it is not+ pixelated; it uses the world's type and colours.++## 6. What V1 ships, what comes next++V1 (this pass): terrain + sea, the market village, the four quarters' landmarks, trees,+navigation (drag / keys / 3 zoom steps / minimap), stand-in walkers with wander + checkpoints ++nameplates + click-to-select, place signs, the World / Ledger switch in the Jarvis Agents section.++Next, in order: the model card opening on a figure click (the card session's overlay); real+figures from the character pipeline replacing `WalkerFigure` (F3); speech bubbles and the+choreography queue on the society event stream (MASTERPLAN §3.3); the "Active now" face strip+and today's cost in the HUD; a day/night flavour; the headless-Chrome screenshot check.diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.jsonindex 5003e450f1..52257a78e7 100644--- a/jarvis/ui/web/frontend/package-lock.json+++ b/jarvis/ui/web/frontend/package-lock.json@@ -11,6 +11,7 @@"dependencies": {"@fontsource-variable/inter": "^5.3.0","@fontsource/jetbrains-mono": "^5.3.0",+ "@fontsource/pixelify-sans": "^5.3.0","@fontsource/space-grotesk": "^5.3.0","@radix-ui/react-collapsible": "^1.1.12","@radix-ui/react-dialog": "^1.1.15",@@ -982,6 +983,15 @@"url": "https://github.com/sponsors/ayuhito"}},+ "node_modules/@fontsource/pixelify-sans": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/@fontsource/pixelify-sans/-/pixelify-sans-5.3.0.tgz",+ "integrity": "sha512-4RCe9nXbi7wUu5+H0FNX1sgPZ2kJ1MmY1uTkEfvQIzzqhoS8zGKJaJfdK8oreE0OU+5gM+NdurFi3H3FJRBvyw==",+ "license": "OFL-1.1",+ "funding": {+ "url": "https://github.com/sponsors/ayuhito"+ }+ },"node_modules/@fontsource/space-grotesk": {"version": "5.3.0","resolved": "https://registry.npmjs.org/@fontsource/space-grotesk/-/space-grotesk-5.3.0.tgz",diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.jsonindex f8171d3d53..a7508ebbd1 100644--- a/jarvis/ui/web/frontend/package.json+++ b/jarvis/ui/web/frontend/package.json@@ -13,6 +13,7 @@"dependencies": {"@fontsource-variable/inter": "^5.3.0","@fontsource/jetbrains-mono": "^5.3.0",+ "@fontsource/pixelify-sans": "^5.3.0","@fontsource/space-grotesk": "^5.3.0","@radix-ui/react-collapsible": "^1.1.12","@radix-ui/react-dialog": "^1.1.15",diff --git a/jarvis/ui/web/frontend/src/components/society/world/Landmarks.tsx b/jarvis/ui/web/frontend/src/components/society/world/Landmarks.tsxnew file mode 100644index 0000000000..c67c5247a9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/Landmarks.tsx@@ -0,0 +1,181 @@+/**+ * The four quarters' landmarks — the places MASTERPLAN §4.1 names, in the+ * solarpunk language: the workshop hall (west), the archive tower (north), the+ * harbor gate with its dock and boat (south), the lighthouse on the eastern+ * cape, plus the greenhouses and the solar field that fill the corners.+ */+import { useMemo, useRef } from "react";+import { useFrame } from "@react-three/fiber";+import { InstancedMesh, Mesh, Object3D } from "three";++import { buildIsland, groundY, tileToWorld, type PlaceId, type Post } from "./islandLayout";+import { Block, useKit, type Kit } from "./WorldKit";+import { PAL } from "./worldMaterials";++function placeWorld(id: PlaceId): [number, number, number] {+ const { map, content } = buildIsland();+ const [tx, tz] = content.places[id].tile;+ const [x, z] = tileToWorld(tx, tz);+ return [x, groundY(map, x, z), z];+}++function Workshop({ kit }: { kit: Kit }) {+ const [x, y, z] = placeWorld("workshop");+ return (+ <group position={[x, y, z]}>+ <Block kit={kit} at={[0, 0.2, 0]} size={[25, 0.4, 13]} color={PAL.trim} />+ <Block kit={kit} at={[0, 2.6, 0]} size={[24, 4.8, 12]} color={PAL.wall} />+ {/* sawtooth skylight roof: three slanted glass panes and their backs */}+ {[-8, 0, 8].map((ox) => (+ <group key={ox} position={[ox, 5.0, 0]}>+ <Block kit={kit} at={[-1.6, 0.9, 0]} size={[5.2, 0.16, 12.2]} color={PAL.glass} glow rotation={[0, 0, 0.42]} />+ <Block kit={kit} at={[2.2, 0.9, 0]} size={[3.6, 0.16, 12.2]} color={PAL.workshopRoof} rotation={[0, 0, -0.62]} />+ </group>+ ))}+ {/* wide door facing the village (east, +x) */}+ <Block kit={kit} at={[12.1, 1.9, 0]} size={[0.2, 3.8, 5]} color={PAL.wood} />+ <Block kit={kit} at={[12.15, 1.9, 0]} size={[0.14, 3.2, 0.3]} color={PAL.woodDark} />+ {/* window band */}+ <Block kit={kit} at={[0, 3.4, 6.05]} size={[20, 1.0, 0.12]} color={PAL.glass} glow />+ <Block kit={kit} at={[0, 3.4, -6.05]} size={[20, 1.0, 0.12]} color={PAL.glass} glow />+ {/* chimney */}+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.metal)} position={[-9, 6.8, -4]} scale={[1.1, 4, 1.1]} />+ </group>+ );+}++function Archive({ kit }: { kit: Kit }) {+ const [x, y, z] = placeWorld("archive");+ return (+ <group position={[x, y, z]}>+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.trim)} position={[0, 0.2, 0]} scale={[13, 0.4, 13]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.wall)} position={[0, 4.5, 0]} scale={[11, 9, 11]} />+ {/* two glass bands */}+ <mesh geometry={kit.g.cylinder} material={kit.m.glow(PAL.glass)} position={[0, 3.2, 0]} scale={[11.1, 0.9, 11.1]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.glow(PAL.glass)} position={[0, 6.6, 0]} scale={[11.1, 0.9, 11.1]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.hubAccent)} position={[0, 9.1, 0]} scale={[11.6, 0.3, 11.6]} />+ <mesh geometry={kit.g.dome} material={kit.m.lit(PAL.archiveDome)} position={[0, 9.2, 0]} scale={[11, 6, 11]} />+ <mesh geometry={kit.g.cone} material={kit.m.lit(PAL.metal)} position={[0, 12.9, 0]} scale={[0.6, 1.6, 0.6]} />+ {/* entrance arch facing the village (south, +z) */}+ <Block kit={kit} at={[0, 1.7, 5.6]} size={[3.6, 3.4, 0.6]} color={PAL.wood} />+ <Block kit={kit} at={[0, 1.4, 5.95]} size={[2.2, 2.8, 0.2]} color={PAL.door} />+ </group>+ );+}++function Harbor({ kit, paused }: { kit: Kit; paused: boolean }) {+ const [x, y, z] = placeWorld("harbor");+ const boat = useRef<Mesh>(null);+ useFrame(({ clock }) => {+ if (!boat.current || paused) return;+ const t = clock.getElapsedTime();+ boat.current.position.y = 0.15 + Math.sin(t * 1.1) * 0.08;+ boat.current.rotation.z = Math.sin(t * 0.8) * 0.03;+ });+ return (+ <group position={[x, y, z]}>+ {/* the gate: two pillars and a beam over the start of the dock */}+ <Block kit={kit} at={[-3, 2.6, 8]} size={[1.1, 5.2, 1.1]} color={PAL.wall} />+ <Block kit={kit} at={[3, 2.6, 8]} size={[1.1, 5.2, 1.1]} color={PAL.wall} />+ <Block kit={kit} at={[0, 5.4, 8]} size={[8, 0.7, 1.2]} color={PAL.wood} />+ <Block kit={kit} at={[0, 5.95, 8]} size={[8.4, 0.3, 1.4]} color={PAL.hubAccent} />+ <mesh geometry={kit.g.box} material={kit.m.glow(PAL.lampLight)} position={[-3, 5.5, 8]} scale={[0.6, 0.5, 0.6]} />+ <mesh geometry={kit.g.box} material={kit.m.glow(PAL.lampLight)} position={[3, 5.5, 8]} scale={[0.6, 0.5, 0.6]} />+ {/* harbor master's kiosk */}+ <Block kit={kit} at={[-7, 1.4, 2]} size={[4, 2.8, 3.5]} color={PAL.wallShade} />+ <Block kit={kit} at={[-7, 2.95, 2]} size={[4.6, 0.3, 4.1]} color={PAL.solar} />+ <Block kit={kit} at={[-7, 1.6, 3.8]} size={[2.4, 1.0, 0.12]} color={PAL.glass} glow />+ {/* a boat moored beside the dock */}+ <group position={[6.5, -y, 24]}>+ <mesh ref={boat} geometry={kit.g.box} material={kit.m.lit(PAL.wood)} position={[0, 0.15, 0]} scale={[2.2, 1.0, 6]}>+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.woodDark)} position={[0, 2.4, 0.1]} scale={[0.08, 4.4, 0.04]} />+ <mesh geometry={kit.g.box} material={kit.m.lit(PAL.wall)} position={[0.45, 2.6, 0.1]} scale={[0.75, 2.6, 0.03]} />+ </mesh>+ </group>+ </group>+ );+}++function Lighthouse({ kit, paused }: { kit: Kit; paused: boolean }) {+ const [x, y, z] = placeWorld("lighthouse");+ const lamp = useRef<Mesh>(null);+ useFrame(({ clock }) => {+ if (!lamp.current || paused) return;+ lamp.current.rotation.y = clock.getElapsedTime() * 1.4;+ });+ return (+ <group position={[x, y, z]}>+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.trim)} position={[0, 0.25, 0]} scale={[5.5, 0.5, 5.5]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.wall)} position={[0, 5.5, 0]} scale={[3.4, 11, 3.4]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.lighthouseStripe)} position={[0, 3.2, 0]} scale={[3.45, 1.5, 3.45]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.lighthouseStripe)} position={[0, 7.4, 0]} scale={[3.45, 1.5, 3.45]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.metal)} position={[0, 11.2, 0]} scale={[4.2, 0.4, 4.2]} />+ <mesh geometry={kit.g.cylinder} material={kit.m.glow(PAL.hubGlass)} position={[0, 12.3, 0]} scale={[2.6, 1.8, 2.6]} />+ <mesh ref={lamp} geometry={kit.g.box} material={kit.m.glow(PAL.beaconCore)} position={[0, 12.3, 0]} scale={[3.2, 0.9, 0.7]} />+ <mesh geometry={kit.g.dome} material={kit.m.lit(PAL.lighthouseStripe)} position={[0, 13.2, 0]} scale={[4.2, 2.2, 4.2]} />+ {/* keeper's hut */}+ <Block kit={kit} at={[-5, 1.3, 3]} size={[4, 2.6, 3.4]} color={PAL.wallShade} />+ <Block kit={kit} at={[-5, 2.75, 3]} size={[4.6, 0.3, 4]} color={PAL.solar} />+ </group>+ );+}++/** Instanced greenhouses: glass barrels on wooden sills. */+function Greenhouses({ kit, posts }: { kit: Kit; posts: Post[] }) {+ const dummy = useMemo(() => new Object3D(), []);+ const setup = (mesh: InstancedMesh | null, yOffset: number, scale: [number, number, number], rot: [number, number, number]) => {+ if (!mesh) return;+ posts.forEach((p, i) => {+ dummy.position.set(p.x, p.y + yOffset, p.z);+ dummy.rotation.set(...rot);+ dummy.scale.set(...scale);+ dummy.updateMatrix();+ mesh.setMatrixAt(i, dummy.matrix);+ });+ mesh.instanceMatrix.needsUpdate = true;+ };+ return (+ <>+ <instancedMesh ref={(m) => setup(m, 0.15, [7.2, 0.3, 4.4], [0, 0, 0])} args={[kit.g.box, kit.m.lit(PAL.wood), posts.length]} />+ <instancedMesh ref={(m) => setup(m, 0.3, [4.2, 7.0, 4.2], [0, 0, Math.PI / 2])} args={[kit.g.halfCylinder, kit.m.glow(PAL.glass), posts.length]} />+ </>+ );+}++/** Instanced solar panels on posts, tilted toward the afternoon sun. */+function SolarField({ kit, posts }: { kit: Kit; posts: Post[] }) {+ const dummy = useMemo(() => new Object3D(), []);+ const setup = (mesh: InstancedMesh | null, yOffset: number, scale: [number, number, number], rot: [number, number, number]) => {+ if (!mesh) return;+ posts.forEach((p, i) => {+ dummy.position.set(p.x, p.y + yOffset, p.z);+ dummy.rotation.set(...rot);+ dummy.scale.set(...scale);+ dummy.updateMatrix();+ mesh.setMatrixAt(i, dummy.matrix);+ });+ mesh.instanceMatrix.needsUpdate = true;+ };+ return (+ <>+ <instancedMesh ref={(m) => setup(m, 0.6, [0.2, 1.2, 0.2], [0, 0, 0])} args={[kit.g.cylinder, kit.m.lit(PAL.metal), posts.length]} />+ <instancedMesh ref={(m) => setup(m, 1.3, [3.6, 0.12, 2.2], [-0.45, 0, 0])} args={[kit.g.box, kit.m.lit(PAL.solar), posts.length]} />+ <instancedMesh ref={(m) => setup(m, 1.36, [3.4, 0.04, 0.12], [-0.45, 0, 0])} args={[kit.g.box, kit.m.lit(PAL.solarLine), posts.length]} />+ </>+ );+}++export function Landmarks({ paused }: { paused: boolean }) {+ const kit = useKit();+ const { content } = buildIsland();+ return (+ <group>+ <Workshop kit={kit} />+ <Archive kit={kit} />+ <Harbor kit={kit} paused={paused} />+ <Lighthouse kit={kit} paused={paused} />+ <Greenhouses kit={kit} posts={content.greenhouses} />+ <SolarField kit={kit} posts={content.panels} />+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsx b/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsxnew file mode 100644index 0000000000..7559cc8cb0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/Minimap.tsx@@ -0,0 +1,109 @@+/**+ * The island at a glance: a 2D canvas painted once from the tile map, with the+ * viewport rectangle and the walkers' pins redrawn a few times a second.+ * Clicking it moves the camera there.+ */+import { useEffect, useMemo, useRef } from "react";++import { useT } from "@/i18n";+import { useCameraStore } from "./cameraStore";+import { ISLAND_HALF_M, TILE_M, buildIsland, type TileKind } from "./islandLayout";+import { walkerPins } from "./walkerRegistry";+import { ZOOM_WIDTHS_M, visibleGroundCorners } from "./worldCamera";+import { LABEL, minimapColor } from "./worldPalette";++const SIZE_PX = 168;+const REDRAW_MS = 120;++function paintBase(): HTMLCanvasElement | null {+ if (typeof document === "undefined") return null;+ const { map } = buildIsland();+ const canvas = document.createElement("canvas");+ canvas.width = map.size;+ canvas.height = map.size;+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ for (let tz = 0; tz < map.size; tz++) {+ for (let tx = 0; tx < map.size; tx++) {+ ctx.fillStyle = minimapColor(map.kind[tz * map.size + tx] as TileKind);+ ctx.fillRect(tx, tz, 1, 1);+ }+ }+ return canvas;+}++function worldToMap(x: number, z: number): [number, number] {+ const s = SIZE_PX / (ISLAND_HALF_M * 2);+ return [(x + ISLAND_HALF_M) * s, (z + ISLAND_HALF_M) * s];+}++export function Minimap({ awake }: { awake: boolean }) {+ const t = useT();+ const ref = useRef<HTMLCanvasElement>(null);+ const base = useMemo(paintBase, []);++ useEffect(() => {+ const canvas = ref.current;+ if (!canvas || !base || !awake) return;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;+ let frame = 0;+ let last = 0;+ const draw = (now: number) => {+ frame = requestAnimationFrame(draw);+ if (now - last < REDRAW_MS) return;+ last = now;+ ctx.imageSmoothingEnabled = false;+ ctx.clearRect(0, 0, SIZE_PX, SIZE_PX);+ ctx.drawImage(base, 0, 0, SIZE_PX, SIZE_PX);+ // Walker pins.+ for (const pin of walkerPins().values()) {+ const [px, pz] = worldToMap(pin.x, pin.z);+ ctx.fillStyle = LABEL.ink;+ ctx.fillRect(Math.round(px) - 2, Math.round(pz) - 2, 5, 5);+ ctx.fillStyle = pin.color;+ ctx.fillRect(Math.round(px) - 1, Math.round(pz) - 1, 3, 3);+ }+ // The viewport as a rotated rectangle.+ const { target, zoom, aspect } = useCameraStore.getState();+ const corners = visibleGroundCorners(target, ZOOM_WIDTHS_M[zoom], aspect);+ ctx.beginPath();+ corners.forEach(([x, z], i) => {+ const [px, pz] = worldToMap(x, z);+ if (i === 0) ctx.moveTo(px, pz);+ else ctx.lineTo(px, pz);+ });+ ctx.closePath();+ ctx.lineWidth = 2;+ ctx.strokeStyle = LABEL.ink;+ ctx.stroke();+ ctx.lineWidth = 1;+ ctx.strokeStyle = "#ffffff";+ ctx.stroke();+ };+ frame = requestAnimationFrame(draw);+ return () => cancelAnimationFrame(frame);+ }, [base, awake]);++ const onClick = (e: React.MouseEvent<HTMLCanvasElement>) => {+ const rect = e.currentTarget.getBoundingClientRect();+ const fx = (e.clientX - rect.left) / rect.width;+ const fz = (e.clientY - rect.top) / rect.height;+ const x = (fx * 2 - 1) * ISLAND_HALF_M;+ const z = (fz * 2 - 1) * ISLAND_HALF_M;+ // Snap to a tile centre so the ease lands on a clean pixel.+ useCameraStore.getState().jumpTo(Math.round(x / TILE_M) * TILE_M, Math.round(z / TILE_M) * TILE_M);+ };++ return (+ <canvas+ ref={ref}+ width={SIZE_PX}+ height={SIZE_PX}+ className="sw-minimap"+ role="img"+ aria-label={t("society.world.minimap_label")}+ onClick={onClick}+ />+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/PixelPass.tsx b/jarvis/ui/web/frontend/src/components/society/world/PixelPass.tsxnew file mode 100644index 0000000000..5e24e103f5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/PixelPass.tsx@@ -0,0 +1,51 @@+/**+ * The retro look, and the performance medicine in one: the scene renders into+ * a render target `pixelSize` times smaller than the canvas, nearest-filtered,+ * with thin depth/normal edge lines — three's own `RenderPixelatedPass`+ * (MASTERPLAN §4.1). Fragment cost drops by pixelSize², which is what lets the+ * island run on WebView2's integrated GPU.+ *+ * Mounted INSIDE the R3F Canvas. `useFrame` with priority 1 takes over+ * rendering from R3F, so the composer is the only thing that draws.+ */+import { useEffect, useMemo } from "react";+import { useFrame, useThree } from "@react-three/fiber";+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";+import { RenderPixelatedPass } from "three/examples/jsm/postprocessing/RenderPixelatedPass.js";++interface Props {+ pixelSize: number;+}++export function PixelPass({ pixelSize }: Props) {+ const gl = useThree((s) => s.gl);+ const scene = useThree((s) => s.scene);+ const camera = useThree((s) => s.camera);+ const size = useThree((s) => s.size);++ const composer = useMemo(() => {+ const c = new EffectComposer(gl);+ const pass = new RenderPixelatedPass(pixelSize, scene, camera, {+ // Soft outlines: enough to separate a figure from the ground, not a comic ink line.+ normalEdgeStrength: 0.18,+ depthEdgeStrength: 0.28,+ });+ c.addPass(pass);+ c.addPass(new OutputPass());+ return { c, pass };+ }, [gl, scene, camera, pixelSize]);++ useEffect(() => {+ composer.c.setSize(size.width, size.height);+ composer.pass.setPixelSize(pixelSize);+ }, [composer, size.width, size.height, pixelSize]);++ useEffect(() => () => composer.c.dispose(), [composer]);++ useFrame(() => {+ composer.c.render();+ }, 1);++ return null;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/PlaceLabels.tsx b/jarvis/ui/web/frontend/src/components/society/world/PlaceLabels.tsxnew file mode 100644index 0000000000..2197fdf9ef--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/PlaceLabels.tsx@@ -0,0 +1,40 @@+/**+ * In-world signs over the places, drawn as DOM so they stay legible through+ * the pixel pass. Text comes from the `society` locale chunk; the look from+ * `world.css` (the world's own type, MASTERPLAN §4.3).+ */+import { Html } from "@react-three/drei";++import { useT } from "@/i18n";+import { buildIsland, groundY, tileToWorld, type PlaceId } from "./islandLayout";++/** Label anchor height above the ground per place (roughly the roofline). */+const LABEL_Y: Record<PlaceId, number> = {+ market: 12.5,+ hub: 13,+ workshop: 9,+ archive: 15,+ harbor: 8,+ lighthouse: 16,+ gardens: 6,+ solar: 5,+};++export function PlaceLabels() {+ const t = useT();+ const { map, content } = buildIsland();+ return (+ <group>+ {(Object.keys(content.places) as PlaceId[]).map((id) => {+ const [tx, tz] = content.places[id].tile;+ const [x, z] = tileToWorld(tx, tz);+ const y = groundY(map, x, z) + LABEL_Y[id];+ return (+ <Html key={id} position={[x, y, z]} center zIndexRange={[20, 5]} style={{ pointerEvents: "none" }}>+ <div className="sw-placelabel">{t(`society.world.place_${id}`)}</div>+ </Html>+ );+ })}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/README.md b/jarvis/ui/web/frontend/src/components/society/world/README.mdnew file mode 100644index 0000000000..b9ca2c9930--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/README.md@@ -0,0 +1,24 @@+# components/society/world — the island (M3, in progress)++The 3D world of the Jarvis Agents section. Built in the maintainer's own+session; sibling sessions own `../card/`, `../data.ts` and `scripts/figures/`.++Binding design: `docs/agent-society/world-art-direction.md` (layout, camera,+palette, building language) under `docs/agent-society/MASTERPLAN.md` §4.++| File | Role |+|---|---|+| `islandLayout.ts` | THE model: grid constants, deterministic terrain, village ring, places, trees, A\* pathfinding. Pure, tested. |+| `worldCamera.ts` | Pitch/yaw/zoom steps and screen↔ground math. Pure, tested. |+| `walkerKinematics.ts` | character-pipeline.md §6 as functions (heading, turning, arrival). Pure, tested. The figure pipeline's F3 step plugs its GLB `<Figure>` in here without changing these. |+| `wander.ts` | Rest-biased idle model (zero tokens). Pure, tested. |+| `terrainGeometry.ts` | Tile map → one vertex-coloured mesh. Pure three, tested. |+| `worldPalette.ts` | The world's own colours (§4.3). Nothing inside the canvas reads a theme token. |+| `cameraStore.ts` · `useWorldControls.ts` · `WorldCameraRig.tsx` | Target/zoom store, DOM navigation, the R3F camera driver. |+| `PixelPass.tsx` | `RenderPixelatedPass` + `OutputPass` composer — the retro look and the GPU budget. |+| `Terrain.tsx` · `Village.tsx` · `Landmarks.tsx` · `Trees.tsx` | The scene, all primitives, shared through `WorldKit.tsx`. |+| `Walkers.tsx` · `WalkerFigure.tsx` · `walkerRegistry.ts` | Agents on foot: state machine, stand-in figure, minimap pins. |+| `PlaceLabels.tsx` · `WorldHud.tsx` · `Minimap.tsx` · `world.css` | DOM over the canvas in the world's type. |+| `WorldStage.tsx` | The composition; mounted by `views/JarvisAgentsView.tsx` behind the World / Ledger switch. |++Strings live in the lazy `society` locale chunk (`src/i18n/locales/society/`).diff --git a/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx b/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsxnew file mode 100644index 0000000000..124b93af89--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx@@ -0,0 +1,61 @@+/**+ * The ground and the sea. The terrain is one merged, vertex-coloured mesh+ * (`terrainGeometry.ts`); the sea is a single plane under everything with a+ * scrolling pixel texture. Both are static apart from the water's drift.+ */+import { useEffect, useMemo } from "react";+import { useFrame } from "@react-three/fiber";+import { DoubleSide, MeshBasicMaterial, MeshLambertMaterial, PlaneGeometry } from "three";++import { buildIsland } from "./islandLayout";+import { buildTerrainGeometry } from "./terrainGeometry";+import { WATER_TILE_M, makeWaterTexture } from "./waterTexture";+import { WATER } from "./worldPalette";++export function Terrain() {+ const geometry = useMemo(() => buildTerrainGeometry(buildIsland().map), []);+ const material = useMemo(+ () => new MeshLambertMaterial({ vertexColors: true, side: DoubleSide }),+ [],+ );+ useEffect(+ () => () => {+ geometry.dispose();+ material.dispose();+ },+ [geometry, material],+ );+ return <mesh geometry={geometry} material={material} receiveShadow={false} />;+}++/** The sea plane — far larger than the island so its edge is never in view. */+const SEA_SIZE_M = 1600;++export function Water({ paused }: { paused: boolean }) {+ const texture = useMemo(() => makeWaterTexture(), []);+ const geometry = useMemo(() => new PlaneGeometry(SEA_SIZE_M, SEA_SIZE_M), []);+ const material = useMemo(() => {+ if (!texture) return new MeshBasicMaterial({ color: WATER.surface });+ texture.repeat.set(SEA_SIZE_M / WATER_TILE_M, SEA_SIZE_M / WATER_TILE_M);+ return new MeshBasicMaterial({ map: texture });+ }, [texture]);+ useEffect(+ () => () => {+ geometry.dispose();+ material.dispose();+ texture?.dispose();+ },+ [geometry, material, texture],+ );++ useFrame(({ clock }) => {+ if (paused || !texture) return;+ const t = clock.getElapsedTime();+ // A slow drift plus a gentle back-and-forth: water, not a conveyor belt.+ texture.offset.set(t * 0.012 + Math.sin(t * 0.35) * 0.01, t * 0.006);+ });++ return (+ <mesh geometry={geometry} material={material} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]} />+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/Trees.tsx b/jarvis/ui/web/frontend/src/components/society/world/Trees.tsxnew file mode 100644index 0000000000..c334a9d3e0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/Trees.tsx@@ -0,0 +1,60 @@+/**+ * Every tree on the island in three draw calls: instanced trunks, instanced+ * lower canopies, instanced upper canopies. Size and shade come from the+ * layout's deterministic spots, so the forest is the same in every window.+ */+import { useMemo } from "react";+import { Color, InstancedMesh, Object3D } from "three";++import { buildIsland } from "./islandLayout";+import { NATURE } from "./worldPalette";+import { useKit } from "./WorldKit";++export function Trees() {+ const { g, m } = useKit();+ const { trees } = buildIsland().content;+ const dummy = useMemo(() => new Object3D(), []);+ const colors = useMemo(+ () => ({ a: new Color(NATURE.canopyA), b: new Color(NATURE.canopyB), light: new Color(NATURE.canopyLight) }),+ [],+ );++ const trunks = (mesh: InstancedMesh | null) => {+ if (!mesh) return;+ trees.forEach((t, i) => {+ const h = 1.1 + t.size * 0.9;+ dummy.position.set(t.x, t.y + h / 2, t.z);+ dummy.rotation.set(0, 0, 0);+ dummy.scale.set(0.42, h, 0.42);+ dummy.updateMatrix();+ mesh.setMatrixAt(i, dummy.matrix);+ });+ mesh.instanceMatrix.needsUpdate = true;+ };++ const canopies = (mesh: InstancedMesh | null, upper: boolean) => {+ if (!mesh) return;+ trees.forEach((t, i) => {+ const h = 1.1 + t.size * 0.9;+ const r = upper ? 1.6 + t.size * 1.2 : 2.4 + t.size * 1.8;+ const dy = upper ? h + r * 0.55 + 0.9 : h + r * 0.35;+ const jitter = upper ? (t.shade - 0.5) * 0.9 : 0;+ dummy.position.set(t.x + jitter, t.y + dy, t.z - jitter * 0.6);+ dummy.rotation.set(0, t.shade * Math.PI, 0);+ dummy.scale.set(r, r * 0.85, r);+ dummy.updateMatrix();+ mesh.setMatrixAt(i, dummy.matrix);+ mesh.setColorAt(i, upper ? (t.shade > 0.5 ? colors.light : colors.b) : t.shade > 0.5 ? colors.b : colors.a);+ });+ mesh.instanceMatrix.needsUpdate = true;+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;+ };++ return (+ <group>+ <instancedMesh ref={trunks} args={[g.cylinder, m.lit(NATURE.trunk), trees.length]} />+ <instancedMesh ref={(mesh) => canopies(mesh, false)} args={[g.blob, m.lit("#ffffff"), trees.length]} />+ <instancedMesh ref={(mesh) => canopies(mesh, true)} args={[g.blob, m.lit("#ffffff"), trees.length]} />+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/Village.tsx b/jarvis/ui/web/frontend/src/components/society/world/Village.tsxnew file mode 100644index 0000000000..45834c935c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/Village.tsx@@ -0,0 +1,192 @@+/**+ * The market district: twelve solarpunk houses in a ring around the open+ * square, the lead agent's hub at its head, the big tree with the round table+ * in the middle, the hedge ring with its four gates, and the lamps.+ *+ * Everything is primitives from `worldMaterials.ts` — no asset files. The+ * building language (docs/agent-society/world-art-direction.md §4): white+ * walls, glass, solar barrels, garden roofs, wood accents, rounded shapes.+ */+import { useMemo, useRef } from "react";+import { useFrame } from "@react-three/fiber";+import { Color, InstancedMesh, Mesh, Object3D } from "three";++import { buildIsland, groundY, type HousePlot, type Post } from "./islandLayout";+import { Block, useKit, type Kit } from "./WorldKit";+import { PAL } from "./worldMaterials";++/** One house. Local +z is the front (door side); the plot rotation points it at the square. */+function House({ kit, plot }: { kit: Kit; plot: HousePlot }) {+ const { map } = buildIsland();+ const y = groundY(map, plot.x, plot.z);+ const w = plot.w * 2; // footprint in metres+ const d = plot.d * 2;+ const h = plot.variant === "glass-loft" ? 3.0 : 3.4;+ const shade = plot.seed > 0.5 ? PAL.wall : PAL.wallShade;+ return (+ <group position={[plot.x, y, plot.z]} rotation={[0, plot.rotation, 0]}>+ {/* body */}+ <Block kit={kit} at={[0, h / 2, 0]} size={[w, h, d]} color={shade} />+ {/* plinth */}+ <Block kit={kit} at={[0, 0.15, 0]} size={[w + 0.4, 0.3, d + 0.4]} color={PAL.trim} />+ {/* door and two windows on the front */}+ <Block kit={kit} at={[0, 1.05, d / 2 + 0.05]} size={[1.1, 2.1, 0.12]} color={PAL.door} />+ <Block kit={kit} at={[-w / 2 + 1.2, 1.9, d / 2 + 0.05]} size={[1.2, 1.1, 0.12]} color={PAL.glass} glow />+ <Block kit={kit} at={[w / 2 - 1.2, 1.9, d / 2 + 0.05]} size={[1.2, 1.1, 0.12]} color={PAL.glass} glow />+ {/* side windows */}+ <Block kit={kit} at={[w / 2 + 0.05, 1.9, 0]} size={[0.12, 1.1, 1.6]} color={PAL.glass} glow />+ <Block kit={kit} at={[-w / 2 - 0.05, 1.9, 0]} size={[0.12, 1.1, 1.6]} color={PAL.glass} glow />+ {/* wooden awning over the door */}+ <Block kit={kit} at={[0, 2.35, d / 2 + 0.5]} size={[2.2, 0.14, 1.0]} color={PAL.wood} />+ {plot.variant === "solar-barrel" && (+ <>+ {/* barrel roof: a half cylinder laid along the house's width */}+ <mesh+ geometry={kit.g.halfCylinder}+ material={kit.m.lit(PAL.solar)}+ position={[0, h, 0]}+ rotation={[0, 0, Math.PI / 2]}+ scale={[d + 0.6, w + 0.4, d + 0.6]}+ />+ <Block kit={kit} at={[0, h + d / 2 + 0.25, 0]} size={[w + 0.5, 0.1, 0.5]} color={PAL.solarLine} />+ </>+ )}+ {plot.variant === "garden-roof" && (+ <>+ <Block kit={kit} at={[0, h + 0.2, 0]} size={[w + 0.5, 0.4, d + 0.5]} color={PAL.trim} />+ <Block kit={kit} at={[0, h + 0.5, 0]} size={[w, 0.25, d]} color={PAL.gardenRoof} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.gardenRoofBush)} position={[-w / 4, h + 0.95, 0]} scale={1.1} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.gardenRoofBush)} position={[w / 4, h + 0.9, -d / 5]} scale={0.9} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.flower)} position={[w / 5, h + 0.8, d / 4]} scale={0.5} />+ </>+ )}+ {plot.variant === "glass-loft" && (+ <>+ <Block kit={kit} at={[0, h + 0.1, 0]} size={[w + 0.3, 0.2, d + 0.3]} color={PAL.trim} />+ <Block kit={kit} at={[0, h + 1.0, 0]} size={[w - 1.6, 1.6, d - 1.0]} color={PAL.glass} glow />+ <Block kit={kit} at={[0, h + 1.9, 0]} size={[w - 1.2, 0.2, d - 0.6]} color={PAL.wall} />+ <Block kit={kit} at={[0, h + 2.05, 0]} size={[w - 1.6, 0.1, d - 1.2]} color={PAL.solar} />+ </>+ )}+ </group>+ );+}++/** The lead agent's hub — the largest house, at the head of the square, with a beacon. */+function Hub({ kit, paused }: { kit: Kit; paused: boolean }) {+ const { map, content } = buildIsland();+ const [tx, tz] = content.places.hub.tile;+ const x = (tx + 0.5 - map.size / 2) * 2;+ const z = (tz + 0.5 - map.size / 2) * 2;+ const y = groundY(map, x, z);+ const beacon = useRef<Mesh>(null);+ useFrame(({ clock }) => {+ if (!beacon.current || paused) return;+ const t = clock.getElapsedTime();+ const s = 1 + Math.sin(t * 2.2) * 0.12;+ beacon.current.scale.setScalar(s * 1.3);+ });+ return (+ <group position={[x, y, z]}>+ <Block kit={kit} at={[0, 0.2, 0]} size={[15, 0.4, 11]} color={PAL.trim} />+ <Block kit={kit} at={[0, 2.4, 0]} size={[14, 4.4, 10]} color={PAL.wall} />+ {/* glass band all around */}+ <Block kit={kit} at={[0, 2.6, 0]} size={[14.1, 1.2, 10.1]} color={PAL.hubGlass} glow />+ {/* accent trim in the lead's colour */}+ <Block kit={kit} at={[0, 4.7, 0]} size={[14.6, 0.3, 10.6]} color={PAL.hubAccent} />+ {/* entrance: wide door, two steps, facing the square (south, +z) */}+ <Block kit={kit} at={[0, 1.4, 5.1]} size={[3.2, 2.8, 0.2]} color={PAL.door} />+ <Block kit={kit} at={[0, 0.5, 6.2]} size={[5, 0.2, 1.6]} color={PAL.trim} />+ <Block kit={kit} at={[0, 0.3, 7.4]} size={[6, 0.2, 1.4]} color={PAL.trim} />+ {/* dome */}+ <mesh geometry={kit.g.dome} material={kit.m.lit(PAL.hubGlass)} position={[0, 4.85, 0]} scale={[9, 7, 9]} />+ {/* beacon mast and light */}+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.metal)} position={[0, 9.2, 0]} scale={[0.35, 2.4, 0.35]} />+ <mesh ref={beacon} geometry={kit.g.sphere} material={kit.m.glow(PAL.beacon)} position={[0, 10.9, 0]} scale={1.3} />+ </group>+ );+}++/** The big tree in the middle of the square, the ring bench and the long table. */+function SquareCentre({ kit }: { kit: Kit }) {+ const { map } = buildIsland();+ const y = groundY(map, 1, 1);+ return (+ <group position={[0, y, 0]}>+ <mesh geometry={kit.g.cylinder} material={kit.m.lit(PAL.trunk)} position={[0, 2.6, 0]} scale={[1.8, 5.2, 1.8]} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.bigCanopy)} position={[0, 6.4, 0]} scale={[9.5, 6.5, 9.5]} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.bigCanopyLight)} position={[2.4, 7.8, 1.2]} scale={[5.5, 4.5, 5.5]} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.bigCanopy)} position={[-2.8, 7.4, -1.6]} scale={[5, 4, 5]} />+ <mesh geometry={kit.g.blob} material={kit.m.lit(PAL.bigCanopyLight)} position={[0.4, 9.6, -0.6]} scale={[4.2, 3.4, 4.2]} />+ {/* ring bench */}+ <mesh geometry={kit.g.ring} material={kit.m.lit(PAL.bench)} position={[0, 0.45, 0]} rotation={[Math.PI / 2, 0, 0]} scale={[7.4, 7.4, 4]} />+ {/* the long table on the south side, where everyone gathers */}+ <Block kit={kit} at={[0, 0.85, 8.5]} size={[10, 0.2, 1.8]} color={PAL.tableWood} />+ <Block kit={kit} at={[-4, 0.4, 8.5]} size={[0.4, 0.8, 1.4]} color={PAL.woodDark} />+ <Block kit={kit} at={[4, 0.4, 8.5]} size={[0.4, 0.8, 1.4]} color={PAL.woodDark} />+ <Block kit={kit} at={[0, 0.25, 7.0]} size={[9.6, 0.5, 0.5]} color={PAL.bench} />+ <Block kit={kit} at={[0, 0.25, 10.0]} size={[9.6, 0.5, 0.5]} color={PAL.bench} />+ </group>+ );+}++/** Instanced hedge segments (the village ring) — one draw call. */+function Hedges({ kit, posts }: { kit: Kit; posts: Post[] }) {+ const dummy = useMemo(() => new Object3D(), []);+ const colorA = useMemo(() => new Color(PAL.hedge), []);+ const colorB = useMemo(() => new Color(PAL.hedgeLight), []);+ const setup = (mesh: InstancedMesh | null) => {+ if (!mesh) return;+ posts.forEach((p, i) => {+ dummy.position.set(p.x, p.y + 0.55, p.z);+ dummy.rotation.set(0, p.rotation, 0);+ dummy.scale.set(2.3, 1.1, 0.8);+ dummy.updateMatrix();+ mesh.setMatrixAt(i, dummy.matrix);+ mesh.setColorAt(i, i % 3 === 0 ? colorB : colorA);+ });+ mesh.instanceMatrix.needsUpdate = true;+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;+ };+ return (+ <instancedMesh ref={setup} args={[kit.g.box, kit.m.lit("#ffffff"), posts.length]} />+ );+}++/** Lamps along the spokes: a post and a glowing head. */+function Lamps({ kit, posts }: { kit: Kit; posts: Post[] }) {+ const dummy = useMemo(() => new Object3D(), []);+ const setup = (mesh: InstancedMesh | null, yOffset: number, scale: [number, number, number]) => {+ if (!mesh) return;+ posts.forEach((p, i) => {+ dummy.position.set(p.x, p.y + yOffset, p.z);+ dummy.rotation.set(0, 0, 0);+ dummy.scale.set(...scale);+ dummy.updateMatrix();+ mesh.setMatrixAt(i, dummy.matrix);+ });+ mesh.instanceMatrix.needsUpdate = true;+ };+ return (+ <>+ <instancedMesh ref={(m) => setup(m, 1.6, [0.18, 3.2, 0.18])} args={[kit.g.cylinder, kit.m.lit(PAL.lampPost), posts.length]} />+ <instancedMesh ref={(m) => setup(m, 3.35, [0.55, 0.45, 0.55])} args={[kit.g.box, kit.m.glow(PAL.lampLight), posts.length]} />+ </>+ );+}++export function Village({ paused }: { paused: boolean }) {+ const kit = useKit();+ const { content } = buildIsland();+ return (+ <group>+ {content.houses.map((plot, i) => (+ <House key={i} kit={kit} plot={plot} />+ ))}+ <Hub kit={kit} paused={paused} />+ <SquareCentre kit={kit} />+ <Hedges kit={kit} posts={content.hedges} />+ <Lamps kit={kit} posts={content.lamps} />+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/WalkerFigure.tsx b/jarvis/ui/web/frontend/src/components/society/world/WalkerFigure.tsxnew file mode 100644index 0000000000..4710ef669f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/WalkerFigure.tsx@@ -0,0 +1,123 @@+/**+ * The stand-in walker: a friendly box figure in the agent's palette with+ * procedural limbs — legs and arms swing while walking, hands type at a desk,+ * the whole body breathes at rest. It is NOT the shipping character: the+ * figure pipeline (docs/agent-society/character-pipeline.md) replaces it with+ * a rigged GLB the day the first base passes the gate; the walker sim, the+ * heading and the nameplate stay exactly as they are.+ *+ * The figure faces +Z in its own space (pipeline §4.1), so `headingFor` from+ * `walkerKinematics.ts` turns it the right way.+ */+import { useRef } from "react";+import { useFrame } from "@react-three/fiber";+import type { Group } from "three";++import type { AgentPalette } from "../data";+import { useKit } from "./WorldKit";++/** A warm neutral for head and hands — a doll, not a skin tone. */+const SKIN = "#efe0cd";++export type WalkerMode = "rest" | "walk" | "work" | "sleep";++export interface WalkerAnim {+ mode: WalkerMode;+ /** Current ground speed in m/s (drives the stride rate). */+ speed: number;+}++interface Props {+ palette: AgentPalette;+ anim: { current: WalkerAnim };+ paused: boolean;+ selected: boolean;+}++export function WalkerFigure({ palette, anim, paused, selected }: Props) {+ const kit = useKit();+ const body = useRef<Group>(null);+ const legL = useRef<Group>(null);+ const legR = useRef<Group>(null);+ const armL = useRef<Group>(null);+ const armR = useRef<Group>(null);+ const ring = useRef<Group>(null);+ const phase = useRef(Math.random() * Math.PI * 2);++ useFrame(({ clock }, dt) => {+ if (paused) return;+ const a = anim.current;+ const t = clock.getElapsedTime();+ const step = Math.min(dt, 0.1);+ let legSwing = 0;+ let armSwing = 0;+ let armLift = 0;+ let bob = 0;+ if (a.mode === "walk") {+ // Stride rate follows speed: ~1.28 m per full cycle at nominal pace.+ phase.current += step * a.speed * (Math.PI * 2) / 1.28;+ legSwing = Math.sin(phase.current) * 0.65;+ armSwing = -Math.sin(phase.current) * 0.5;+ bob = Math.abs(Math.sin(phase.current)) * 0.05;+ } else if (a.mode === "work") {+ armLift = -1.25;+ armSwing = Math.sin(t * 9) * 0.08;+ bob = Math.sin(t * 2.2) * 0.012;+ } else if (a.mode === "sleep") {+ bob = Math.sin(t * 0.9) * 0.01;+ armLift = 0.15;+ } else {+ bob = Math.sin(t * 1.6 + phase.current) * 0.02;+ }+ if (body.current) body.current.position.y = bob;+ if (legL.current) legL.current.rotation.x = legSwing;+ if (legR.current) legR.current.rotation.x = -legSwing;+ if (armL.current) armL.current.rotation.x = armLift + armSwing;+ if (armR.current) armR.current.rotation.x = armLift - armSwing;+ if (ring.current) {+ const s = 1 + Math.sin(t * 3) * 0.06;+ ring.current.scale.set(s, 1, s);+ }+ });++ const lit = kit.m.lit;+ const glow = kit.m.glow;+ const box = kit.g.box;++ return (+ <group>+ {selected && (+ <group ref={ring} position={[0, 0.04, 0]}>+ <mesh geometry={kit.g.ring} material={glow(palette.accent)} rotation={[Math.PI / 2, 0, 0]} scale={[1.9, 1.9, 1.2]} />+ </group>+ )}+ <group ref={body}>+ {/* legs, pivoting at the hip */}+ <group ref={legL} position={[-0.14, 0.86, 0]}>+ <mesh geometry={box} material={lit(palette.secondary)} position={[0, -0.4, 0]} scale={[0.22, 0.8, 0.24]} />+ <mesh geometry={box} material={lit(palette.secondary)} position={[0, -0.8, 0.04]} scale={[0.24, 0.12, 0.32]} />+ </group>+ <group ref={legR} position={[0.14, 0.86, 0]}>+ <mesh geometry={box} material={lit(palette.secondary)} position={[0, -0.4, 0]} scale={[0.22, 0.8, 0.24]} />+ <mesh geometry={box} material={lit(palette.secondary)} position={[0, -0.8, 0.04]} scale={[0.24, 0.12, 0.32]} />+ </group>+ {/* torso and belt */}+ <mesh geometry={box} material={lit(palette.primary)} position={[0, 1.16, 0]} scale={[0.56, 0.62, 0.32]} />+ <mesh geometry={box} material={lit(palette.accent)} position={[0, 0.88, 0]} scale={[0.58, 0.08, 0.34]} />+ {/* arms, pivoting at the shoulder */}+ <group ref={armL} position={[-0.38, 1.42, 0]}>+ <mesh geometry={box} material={lit(palette.primary)} position={[0, -0.28, 0]} scale={[0.16, 0.56, 0.2]} />+ <mesh geometry={box} material={lit(SKIN)} position={[0, -0.6, 0]} scale={[0.15, 0.14, 0.18]} />+ </group>+ <group ref={armR} position={[0.38, 1.42, 0]}>+ <mesh geometry={box} material={lit(palette.primary)} position={[0, -0.28, 0]} scale={[0.16, 0.56, 0.2]} />+ <mesh geometry={box} material={lit(SKIN)} position={[0, -0.6, 0]} scale={[0.15, 0.14, 0.18]} />+ </group>+ {/* head and visor (the visor marks the front: +Z) */}+ <mesh geometry={box} material={lit(SKIN)} position={[0, 1.72, 0]} scale={[0.44, 0.44, 0.4]} />+ <mesh geometry={box} material={glow(palette.accent)} position={[0, 1.76, 0.2]} scale={[0.36, 0.12, 0.06]} />+ <mesh geometry={box} material={lit(palette.secondary)} position={[0, 1.96, -0.02]} scale={[0.46, 0.08, 0.42]} />+ </group>+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsx b/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsxnew file mode 100644index 0000000000..50f3ab2194--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsx@@ -0,0 +1,255 @@+/**+ * The society on foot. One `Walker` per roster row: a small state machine+ * (rest / walk / work / sleep) that walks A* paths over the tile grid with the+ * kinematics of character-pipeline.md §6 and idles with the rest-biased+ * wander model (MASTERPLAN §2.7). The backend owns the semantic place+ * (`checkpoint`); every footstep here is client-side and never synced.+ *+ * Idle costs nothing: no network, no LLM — a timer and a random tile.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { Html } from "@react-three/drei";+import { useFrame, useThree, type ThreeEvent } from "@react-three/fiber";+import type { Group } from "three";++import type { AgentCheckpoint, AgentRunState, SocietyAgent } from "../data";+import { useCameraStore } from "./cameraStore";+import {+ buildIsland,+ findPath,+ groundY,+ randomPlazaTile,+ smoothPath,+ tileToWorld,+ worldToTile,+ type PlaceId,+} from "./islandLayout";+import {+ NOMINAL_WALK_MPS,+ TURN_RATE_RAD_S,+ WANDER_SPEED_MPS,+ headingFor,+ isMoving,+ lateralOffset,+ stepAlong,+ turnToward,+} from "./walkerKinematics";+import { WalkerFigure, type WalkerAnim, type WalkerMode } from "./WalkerFigure";+import { clearWalkerPin, setWalkerPin } from "./walkerRegistry";+import { mulberry32, nextBeat, seedFromString } from "./wander";++/** Semantic place → island place (MASTERPLAN §2.7 checkpoints). */+export const CHECKPOINT_PLACE: Record<AgentCheckpoint, PlaceId | null> = {+ desk: "workshop",+ meeting: "market",+ archive: "archive",+ gate: "harbor",+ idle: null,+};++interface Sim {+ x: number;+ z: number;+ y: number;+ heading: number;+ mode: WalkerMode;+ timer: number;+ waypoints: Array<[number, number]>;+ index: number;+ speed: number;+ purpose: PlaceId | null;+ atPurpose: boolean;+ rng: () => number;+}++function stateMode(state: AgentRunState, atPurpose: boolean): WalkerMode {+ if (state === "paused") return "sleep";+ if (state === "working" && atPurpose) return "work";+ return "rest";+}++function pathTo(sim: Sim, target: [number, number]): boolean {+ const { map } = buildIsland();+ const from = worldToTile(sim.x, sim.z);+ const raw = findPath(map, from, target);+ if (!raw) return false;+ const smooth = smoothPath(map, raw).slice(1);+ sim.waypoints = smooth.map(([tx, tz]) => tileToWorld(tx, tz));+ if (sim.waypoints.length === 0) return false;+ sim.index = 0;+ sim.mode = "walk";+ return true;+}++function Walker({+ agent,+ paused,+ selected,+ onSelect,+}: {+ agent: SocietyAgent;+ paused: boolean;+ selected: boolean;+ onSelect: (agentId: string) => void;+}) {+ const group = useRef<Group>(null);+ const anim = useRef<WalkerAnim>({ mode: "rest", speed: 0 });+ const gl = useThree((s) => s.gl);+ const [hover, setHover] = useState(false);+ const offset = useMemo(() => lateralOffset(agent.agentId), [agent.agentId]);++ const sim = useRef<Sim | null>(null);+ if (sim.current === null) {+ const { map, content } = buildIsland();+ const rng = mulberry32(seedFromString(agent.agentId) ^ Date.now());+ const purpose = CHECKPOINT_PLACE[agent.checkpoint];+ const startTile = purpose ? content.places[purpose].standTile : randomPlazaTile(map, rng);+ const [x, z] = tileToWorld(startTile[0], startTile[1]);+ const facing = purpose ? content.places[purpose].facing : rng() * Math.PI * 2;+ sim.current = {+ x: x + offset,+ z,+ y: groundY(map, x, z),+ heading: facing,+ mode: stateMode(agent.state, purpose !== null),+ timer: 1 + rng() * 3,+ waypoints: [],+ index: 0,+ speed: WANDER_SPEED_MPS,+ purpose,+ atPurpose: purpose !== null,+ rng,+ };+ }++ // A checkpoint or state change from the roster re-targets the walker.+ useEffect(() => {+ const s = sim.current;+ if (!s) return;+ const purpose = CHECKPOINT_PLACE[agent.checkpoint];+ if (purpose !== s.purpose) {+ s.purpose = purpose;+ s.atPurpose = false;+ if (purpose) {+ s.speed = NOMINAL_WALK_MPS;+ if (!pathTo(s, buildIsland().content.places[purpose].standTile)) {+ s.atPurpose = true;+ s.mode = stateMode(agent.state, true);+ }+ } else {+ s.mode = stateMode(agent.state, false);+ s.timer = 1;+ }+ } else if (s.mode !== "walk") {+ s.mode = stateMode(agent.state, s.atPurpose);+ }+ }, [agent.checkpoint, agent.state]);++ useEffect(() => () => clearWalkerPin(agent.agentId), [agent.agentId]);++ useFrame((_, dt) => {+ const s = sim.current;+ const g = group.current;+ if (!s || !g) return;+ const { map, content } = buildIsland();+ const step = Math.min(dt, 0.1);++ if (!paused) {+ if (s.mode === "walk") {+ const r = stepAlong(s.x, s.z, s.waypoints, s.index, s.speed, step);+ s.x = r.x;+ s.z = r.z;+ s.index = r.index;+ if (isMoving(r.vx, r.vz)) {+ s.heading = turnToward(s.heading, headingFor(r.vx, r.vz), TURN_RATE_RAD_S * step);+ }+ anim.current.speed = Math.hypot(r.vx, r.vz);+ if (r.arrived) {+ if (s.purpose && !s.atPurpose) {+ s.atPurpose = true;+ s.heading = content.places[s.purpose].facing;+ }+ s.mode = stateMode(agent.state, s.atPurpose);+ s.timer = 2 + s.rng() * 4;+ s.speed = WANDER_SPEED_MPS;+ }+ } else if (s.mode === "rest" || s.mode === "work") {+ s.timer -= step;+ if (s.timer <= 0) {+ if (s.purpose) {+ // At a place: stay. A working agent keeps working; a resting one shifts its weight.+ s.timer = 4 + s.rng() * 6;+ } else {+ const beat = nextBeat(s.rng);+ if (beat.kind === "rest") {+ s.timer = beat.seconds;+ } else if (!pathTo(s, randomPlazaTile(map, s.rng))) {+ s.timer = 2;+ }+ }+ }+ }+ // Ground snap with a short ease so a level step reads as a step.+ const targetY = groundY(map, s.x, s.z);+ s.y += (targetY - s.y) * Math.min(1, step * 12);+ }++ anim.current.mode = s.mode;+ g.position.set(s.x, s.y, s.z);+ g.rotation.y = s.heading;+ setWalkerPin(agent.agentId, { x: s.x, z: s.z, color: agent.palette.accent, name: agent.name });+ });++ useEffect(() => {+ gl.domElement.style.cursor = hover ? "pointer" : "";+ return () => {+ gl.domElement.style.cursor = "";+ };+ }, [hover, gl]);++ const onClick = (e: ThreeEvent<MouseEvent>) => {+ e.stopPropagation();+ if (useCameraStore.getState().dragging) return;+ onSelect(agent.agentId);+ };++ return (+ <group+ ref={group}+ onClick={onClick}+ onPointerOver={(e) => {+ e.stopPropagation();+ setHover(true);+ }}+ onPointerOut={() => setHover(false)}+ >+ <WalkerFigure palette={agent.palette} anim={anim} paused={paused} selected={selected} />+ <Html position={[0, 2.35, 0]} center zIndexRange={[30, 10]} style={{ pointerEvents: "none" }}>+ <div className="sw-nameplate" data-state={agent.state} data-selected={selected || undefined}>+ <span className="sw-nameplate-dot" style={{ background: agent.palette.accent }} />+ {agent.name}+ </div>+ </Html>+ </group>+ );+}++export function Walkers({+ agents,+ paused,+ selectedId,+ onSelect,+}: {+ agents: SocietyAgent[];+ paused: boolean;+ selectedId: string | null;+ onSelect: (agentId: string) => void;+}) {+ return (+ <group>+ {agents.map((a) => (+ <Walker key={a.agentId} agent={a} paused={paused} selected={a.agentId === selectedId} onSelect={onSelect} />+ ))}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsxnew file mode 100644index 0000000000..8a0afb2abe--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldCameraRig.tsx@@ -0,0 +1,94 @@+/**+ * Drives the Canvas's orthographic camera from the camera store: follows the+ * target with an exponential ease, applies the zoom step to the frustum, and+ * turns held keys into a steady pan. Inside the Canvas; the DOM controls live+ * in `useWorldControls`.+ */+import { useEffect, useRef } from "react";+import { useFrame, useThree } from "@react-three/fiber";+import type { OrthographicCamera } from "three";++import { keyPanVector, useCameraStore } from "./cameraStore";+import {+ KEY_PAN_PER_S,+ ZOOM_WIDTHS_M,+ cameraOffset,+ followAlpha,+ groundBasis,+ orthoHalfExtents,+} from "./worldCamera";++/** How quickly the camera settles on a new target / zoom, per second. */+const FOLLOW_RATE = 7;++const OFFSET = cameraOffset();+const BASIS = groundBasis();++export function WorldCameraRig() {+ const camera = useThree((s) => s.camera) as OrthographicCamera;+ const size = useThree((s) => s.size);+ const invalidate = useThree((s) => s.invalidate);+ const setAspect = useCameraStore((s) => s.setAspect);+ const current = useRef<{ x: number; z: number; width: number }>({+ x: useCameraStore.getState().target[0],+ z: useCameraStore.getState().target[1],+ width: ZOOM_WIDTHS_M[useCameraStore.getState().zoom],+ });++ useEffect(() => {+ setAspect(size.width / Math.max(1, size.height));+ }, [size.width, size.height, setAspect]);++ // A store change must wake a demand-driven loop (reduced motion).+ useEffect(() => useCameraStore.subscribe(() => invalidate()), [invalidate]);++ useFrame((_, dt) => {+ const state = useCameraStore.getState();+ const step = Math.min(dt, 0.1);++ // Keyboard pan: constant speed as a fraction of the visible width.+ const [kr, ku] = keyPanVector(state.heldKeys);+ if (kr !== 0 || ku !== 0) {+ const speed = current.current.width * KEY_PAN_PER_S * step;+ const len = Math.hypot(kr, ku);+ const dx = ((kr * BASIS.right[0] + ku * BASIS.forward[0]) / len) * speed;+ const dz = ((kr * BASIS.right[1] + ku * BASIS.forward[1]) / len) * speed;+ state.panBy(dx, dz);+ invalidate();+ }++ const [tx, tz] = useCameraStore.getState().target;+ const targetWidth = ZOOM_WIDTHS_M[state.zoom];+ const a = followAlpha(step, FOLLOW_RATE);+ const cur = current.current;+ // While dragging the world must stick to the pointer: no easing.+ if (state.dragging) {+ cur.x = tx;+ cur.z = tz;+ } else {+ cur.x += (tx - cur.x) * a;+ cur.z += (tz - cur.z) * a;+ }+ cur.width += (targetWidth - cur.width) * a;+ if (Math.abs(targetWidth - cur.width) < 0.01) cur.width = targetWidth;++ const aspect = size.width / Math.max(1, size.height);+ const { halfW, halfH } = orthoHalfExtents(cur.width, aspect);+ camera.left = -halfW;+ camera.right = halfW;+ camera.top = halfH;+ camera.bottom = -halfH;+ camera.near = 1;+ camera.far = 1200;+ camera.position.set(cur.x + OFFSET[0], OFFSET[1], cur.z + OFFSET[2]);+ camera.lookAt(cur.x, 0, cur.z);+ camera.updateProjectionMatrix();++ // Keep the loop alive until the ease has settled.+ if (Math.abs(tx - cur.x) > 0.005 || Math.abs(tz - cur.z) > 0.005 || cur.width !== targetWidth) {+ invalidate();+ }+ }, 0);++ return null;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsxnew file mode 100644index 0000000000..a5628791e1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldHud.tsx@@ -0,0 +1,74 @@+/**+ * The thin layer of DOM over the canvas: the population chip (top-left),+ * whatever the section hands in for the top-right corner (the World / Ledger+ * switch — app chrome, not world content), the controls hint, the zoom+ * buttons and the minimap (bottom-right).+ */+import type { ReactNode } from "react";+import { Minus, Plus } from "lucide-react";++import { fill, useT } from "@/i18n";+import type { SocietyAgent } from "../data";+import { useCameraStore } from "./cameraStore";+import { Minimap } from "./Minimap";+import { ZOOM_WIDTHS_M } from "./worldCamera";++interface Props {+ agents: SocietyAgent[];+ sample: boolean;+ awake: boolean;+ reducedMotion: boolean;+ topRight?: ReactNode;+}++export function WorldHud({ agents, sample, awake, reducedMotion, topRight }: Props) {+ const t = useT();+ const zoom = useCameraStore((s) => s.zoom);+ const zoomStep = useCameraStore((s) => s.zoomStep);+ const active = agents.filter((a) => a.state === "working").length;+ return (+ <div className="sw-hud" aria-live="off">+ <div className="sw-hud-top">+ <div className="sw-chip-row">+ <div className="sw-chip">+ <strong>{fill(t("society.world.hud_agents"), { count: agents.length })}</strong>+ <span className="sw-chip-sep" />+ <span>{fill(t("society.world.hud_active"), { count: active })}</span>+ </div>+ {sample && <div className="sw-chip sw-chip-note">{t("society.world.sample_badge")}</div>}+ {reducedMotion && <div className="sw-chip sw-chip-note">{t("society.world.reduced_motion_note")}</div>}+ </div>+ {topRight ? <div className="sw-hud-topright">{topRight}</div> : null}+ </div>+ <div className="sw-hud-bottom">+ <div className="sw-hint">{t("society.world.controls_hint")}</div>+ <div className="sw-corner">+ <div className="sw-zoom" role="group" aria-label={t("society.world.zoom_label")}>+ <button+ type="button"+ className="sw-zoom-btn"+ onClick={() => zoomStep(-1)}+ disabled={zoom === 0}+ aria-label={t("society.world.zoom_in")}+ title={t("society.world.zoom_in")}+ >+ <Plus size={14} />+ </button>+ <span className="sw-zoom-level">{ZOOM_WIDTHS_M[zoom]} m</span>+ <button+ type="button"+ className="sw-zoom-btn"+ onClick={() => zoomStep(1)}+ disabled={zoom === ZOOM_WIDTHS_M.length - 1}+ aria-label={t("society.world.zoom_out")}+ title={t("society.world.zoom_out")}+ >+ <Minus size={14} />+ </button>+ </div>+ <Minimap awake={awake} />+ </div>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldKit.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldKit.tsxnew file mode 100644index 0000000000..e3c2ef6d52--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldKit.tsx@@ -0,0 +1,55 @@+/**+ * One set of shared geometries and materials per mounted stage, handed to+ * every primitive-built object through context — a house, a tree and a lamp+ * post all draw from the same dozen materials, which keeps program switches+ * and GPU memory flat however many objects the island grows.+ */+import { createContext, useContext, type ReactNode } from "react";++import { useWorldGeometries, useWorldMaterials, type WorldGeometries, type WorldMaterials } from "./worldMaterials";++export interface Kit {+ g: WorldGeometries;+ m: WorldMaterials;+}++const KitContext = createContext<Kit | null>(null);++export function WorldKitProvider({ children }: { children: ReactNode }) {+ const g = useWorldGeometries();+ const m = useWorldMaterials();+ return <KitContext.Provider value={{ g, m }}>{children}</KitContext.Provider>;+}++export function useKit(): Kit {+ const kit = useContext(KitContext);+ if (!kit) throw new Error("useKit outside WorldKitProvider");+ return kit;+}++/** A box helper: centre (x, y, z), size (w, h, d), colour. */+export function Block({+ kit,+ at,+ size,+ color,+ glow = false,+ rotation,+}: {+ kit: Kit;+ at: [number, number, number];+ size: [number, number, number];+ color: string;+ glow?: boolean;+ rotation?: [number, number, number];+}) {+ return (+ <mesh+ geometry={kit.g.box}+ material={glow ? kit.m.glow(color) : kit.m.lit(color)}+ position={at}+ scale={size}+ rotation={rotation}+ />+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsxnew file mode 100644index 0000000000..57b364ea58--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx@@ -0,0 +1,150 @@+/**+ * The island, mounted — the world view of the Jarvis Agents section+ * (MASTERPLAN §4.1) and the first piece of M3.+ *+ * Discipline every world canvas owes (society README):+ * - the R3F Canvas mounts through `useWebglSurface` (AP-32: context released+ * on unmount, rebuilt after a loss, degraded after two losses);+ * - the render loop runs only while the host is on screen, gated by an+ * IntersectionObserver (`useCanvasAwake`) — never `document.hidden`;+ * - `prefers-reduced-motion` freezes the island (demand-driven frames, no+ * wander, no water drift) instead of animating it;+ * - no WebGL at all → an honest fallback that points to the ledger.+ *+ * Everything inside the canvas wears the world's own branding (§4.3); the+ * switch the section hands in for the top-right corner is app chrome.+ */+import "@fontsource/pixelify-sans/500.css";+import "@fontsource/pixelify-sans/600.css";+import "./world.css";++import { useCallback, useRef, useState, type ReactNode } from "react";+import { Canvas } from "@react-three/fiber";+import { useReducedMotion } from "framer-motion";++import { useLocaleChunk, useT } from "@/i18n";+import { useCanvasAwake } from "@/hooks/useCanvasAwake";+import { useWebglSurface } from "@/hooks/useWebglSurface";+import { useWebglSupported } from "@/lib/graphDimension";+import { useSocietyRoster } from "../data";+import { SAMPLE_ROSTER } from "../mockRoster";+import { useCameraStore } from "./cameraStore";+import { Landmarks } from "./Landmarks";+import { PixelPass } from "./PixelPass";+import { PlaceLabels } from "./PlaceLabels";+import { Terrain, Water } from "./Terrain";+import { Trees } from "./Trees";+import { Village } from "./Village";+import { Walkers } from "./Walkers";+import { useWorldControls } from "./useWorldControls";+import { WorldCameraRig } from "./WorldCameraRig";+import { WorldHud } from "./WorldHud";+import { WorldKitProvider } from "./WorldKit";+import { PIXEL_SIZE, cameraOffset } from "./worldCamera";+import { SKY } from "./worldPalette";++export interface WorldStageProps {+ /** App-chrome content for the HUD's top-right corner (the World / Ledger switch). */+ topRight?: ReactNode;+ /** Where the fallback sends someone whose window cannot draw 3D. */+ onOpenLedger: () => void;+ /** A figure was clicked (or the selection cleared). The model card hooks in here. */+ onSelectAgent?: (agentId: string | null) => void;+}++const CAMERA_START = cameraOffset();++export function WorldStage({ topRight, onOpenLedger, onSelectAgent }: WorldStageProps) {+ const t = useT();+ const ready = useLocaleChunk("society");+ const hostRef = useRef<HTMLDivElement>(null);+ const { generation } = useWebglSurface(hostRef);+ const awake = useCanvasAwake(hostRef);+ const reduced = useReducedMotion() ?? false;+ const webgl = useWebglSupported();+ const roster = useSocietyRoster();+ const agents = roster.data ?? [];+ const sample = roster.data === SAMPLE_ROSTER;+ const [selected, setSelected] = useState<string | null>(null);++ useWorldControls(hostRef, webgl);++ const select = useCallback(+ (agentId: string | null) => {+ setSelected(agentId);+ onSelectAgent?.(agentId);+ },+ [onSelectAgent],+ );++ if (!webgl) {+ return (+ <div className="sw-fallback bg-background">+ <div className="max-w-sm space-y-3">+ <h3 className="font-display text-base font-semibold text-foreground">+ {t("society.world.webgl_missing_title")}+ </h3>+ <p className="text-sm text-muted-foreground">{t("society.world.webgl_missing_body")}</p>+ <button+ type="button"+ onClick={onOpenLedger}+ className="inline-flex h-8 items-center rounded-md bg-secondary px-3 text-sm font-medium text-foreground hover:bg-muted"+ >+ {t("society.world.open_ledger")}+ </button>+ </div>+ </div>+ );+ }++ const frameloop = !awake ? "never" : reduced ? "demand" : "always";++ return (+ <div className="relative h-full min-h-0 w-full">+ <div+ ref={hostRef}+ className="sw-stage"+ tabIndex={0}+ role="application"+ aria-label={ready ? t("society.world.mode_world") : undefined}+ >+ <Canvas+ key={generation}+ orthographic+ camera={{ position: CAMERA_START, near: 1, far: 1200, zoom: 1 }}+ dpr={1}+ flat+ gl={{ antialias: false, alpha: false, powerPreference: "high-performance", stencil: false }}+ frameloop={frameloop}+ onPointerMissed={() => {+ if (!useCameraStore.getState().dragging) select(null);+ }}+ >+ <color attach="background" args={[SKY.clear]} />+ <hemisphereLight args={[SKY.hemiSky, SKY.hemiGround, SKY.hemiIntensity * Math.PI]} />+ <directionalLight+ position={[SKY.sunFrom[0], SKY.sunFrom[1], SKY.sunFrom[2]]}+ intensity={SKY.sunIntensity * Math.PI * 0.75}+ color={SKY.sun}+ />+ <WorldKitProvider>+ <Terrain />+ <Water paused={reduced} />+ <Village paused={reduced} />+ <Landmarks paused={reduced} />+ <Trees />+ <Walkers agents={agents} paused={reduced} selectedId={selected} onSelect={select} />+ {ready && <PlaceLabels />}+ </WorldKitProvider>+ <WorldCameraRig />+ <PixelPass pixelSize={PIXEL_SIZE} />+ </Canvas>+ </div>+ {ready && (+ <WorldHud agents={agents} sample={sample} awake={awake} reducedMotion={reduced} topRight={topRight} />+ )}+ </div>+ );+}++export default WorldStage;diff --git a/jarvis/ui/web/frontend/src/components/society/world/cameraStore.ts b/jarvis/ui/web/frontend/src/components/society/world/cameraStore.tsnew file mode 100644index 0000000000..6f8c95463c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/cameraStore.ts@@ -0,0 +1,89 @@+/**+ * Where the viewer is looking: the camera target on the ground and the zoom+ * step. One store per page — the stage, the minimap and the HUD all read it,+ * the controls write it. Pixels are the client's business (MASTERPLAN §2.7),+ * so nothing here is ever persisted or synced.+ */+import { create } from "zustand";++import { DEFAULT_ZOOM, clampTarget, stepZoom, type ZoomLevel } from "./worldCamera";++export interface CameraState {+ /** Ground point the camera looks at, world metres. */+ target: [number, number];+ zoom: ZoomLevel;+ /** True while the pointer drags the world — figures ignore clicks then. */+ dragging: boolean;+ /** Keys currently held for keyboard panning (`ArrowUp`, `KeyW`, …). */+ heldKeys: Set<string>;+ /** Bumped when the viewport size or aspect changes — the minimap re-reads. */+ aspect: number;+ panBy: (dx: number, dz: number) => void;+ jumpTo: (x: number, z: number) => void;+ zoomStep: (direction: 1 | -1) => void;+ setDragging: (dragging: boolean) => void;+ setAspect: (aspect: number) => void;+ keyDown: (code: string) => void;+ keyUp: (code: string) => void;+ clearKeys: () => void;+}++/**+ * `?world=x,z[,zoom]` deep-links a spot on the island (metres from the centre,+ * zoom step 0–2) — for "show me the harbor" from voice or a shared link, and+ * for screenshots. Anything malformed falls back to the square.+ */+export function focusFromSearch(search: string): { target: [number, number]; zoom: ZoomLevel } | null {+ const raw = new URLSearchParams(search).get("world");+ if (!raw) return null;+ const parts = raw.split(",").map((v) => Number(v));+ if (parts.length < 2 || !parts.slice(0, 2).every(Number.isFinite)) return null;+ const target = clampTarget(parts[0], parts[1]);+ const z = parts.length > 2 && Number.isInteger(parts[2]) && parts[2] >= 0 && parts[2] <= 2 ? (parts[2] as ZoomLevel) : DEFAULT_ZOOM;+ return { target, zoom: z };+}++const initialFocus =+ typeof window !== "undefined" ? focusFromSearch(window.location.search) : null;++export const useCameraStore = create<CameraState>((set, get) => ({+ target: initialFocus?.target ?? [0, 0],+ zoom: initialFocus?.zoom ?? DEFAULT_ZOOM,+ dragging: false,+ heldKeys: new Set<string>(),+ aspect: 16 / 9,+ panBy: (dx, dz) => {+ const [x, z] = get().target;+ set({ target: clampTarget(x + dx, z + dz) });+ },+ jumpTo: (x, z) => set({ target: clampTarget(x, z) }),+ zoomStep: (direction) => set((s) => ({ zoom: stepZoom(s.zoom, direction) })),+ setDragging: (dragging) => set({ dragging }),+ setAspect: (aspect) => set({ aspect }),+ keyDown: (code) => {+ const keys = get().heldKeys;+ if (keys.has(code)) return;+ const next = new Set(keys);+ next.add(code);+ set({ heldKeys: next });+ },+ keyUp: (code) => {+ const keys = get().heldKeys;+ if (!keys.has(code)) return;+ const next = new Set(keys);+ next.delete(code);+ set({ heldKeys: next });+ },+ clearKeys: () => set({ heldKeys: new Set<string>() }),+}));++/** Screen-space pan direction for the held keys: [right, up] in −1..1. */+export function keyPanVector(keys: ReadonlySet<string>): [number, number] {+ let right = 0;+ let up = 0;+ if (keys.has("ArrowLeft") || keys.has("KeyA")) right -= 1;+ if (keys.has("ArrowRight") || keys.has("KeyD")) right += 1;+ if (keys.has("ArrowUp") || keys.has("KeyW")) up += 1;+ if (keys.has("ArrowDown") || keys.has("KeyS")) up -= 1;+ return [right, up];+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.ts b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.tsnew file mode 100644index 0000000000..b67d805e5f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.ts@@ -0,0 +1,165 @@+import { beforeAll, describe, expect, it } from "vitest";++import {+ CENTER_TILE,+ DOCK_TILES,+ FIELD_TILES,+ HEDGE_RING_TILES,+ ISLAND_FIELDS,+ ISLAND_TILES,+ LEVEL_Y,+ MARKET_FIELDS,+ MARKET_HALF_TILES,+ PLATEAU_LEVEL,+ PLAZA_RADIUS_TILES,+ TileKind,+ buildIsland,+ findPath,+ groundY,+ hash2,+ isWalkable,+ randomPlazaTile,+ smoothPath,+ tileIndex,+ tileToWorld,+ worldToTile,+ type Island,+} from "./islandLayout";++describe("islandLayout", () => {+ let island: Island;+ beforeAll(() => {+ island = buildIsland();+ });++ it("is a 10 × 10 field grid with a centred 4 × 4 market", () => {+ expect(ISLAND_FIELDS).toBe(10);+ expect(MARKET_FIELDS).toBe(4);+ expect(ISLAND_TILES).toBe(ISLAND_FIELDS * FIELD_TILES);+ // The market sits on fields 3..6 of 0..9 — symmetric around the centre.+ expect((ISLAND_FIELDS - MARKET_FIELDS) / 2).toBe(3);+ expect(CENTER_TILE - MARKET_HALF_TILES).toBe(3 * FIELD_TILES);+ });++ it("maps tiles to world metres and back around the island centre", () => {+ const [x, z] = tileToWorld(CENTER_TILE, CENTER_TILE);+ expect(x).toBeCloseTo(1); // half a tile east of the exact centre+ expect(z).toBeCloseTo(1);+ expect(worldToTile(x, z)).toEqual([CENTER_TILE, CENTER_TILE]);+ expect(worldToTile(-0.5, -0.5)).toEqual([CENTER_TILE - 1, CENTER_TILE - 1]);+ });++ it("is deterministic — the same island every build", () => {+ const again = buildIsland();+ expect(again.map.kind).toBe(island.map.kind); // cached+ // And stable in content: a fixed hash should not drift between platforms.+ expect(hash2(12, 34, 5)).toBe(hash2(12, 34, 5));+ expect(hash2(12, 34, 5)).not.toBe(hash2(34, 12, 5));+ });++ it("puts the sea around the land and a bay on the south coast", () => {+ const { map } = island;+ const corner = map.kind[tileIndex(map, 0, 0)];+ expect(corner).toBe(TileKind.water);+ // The bay: water south of the harbor, land north of it.+ expect(map.kind[tileIndex(map, CENTER_TILE, ISLAND_TILES - 2)]).toBe(TileKind.water);+ expect(map.kind[tileIndex(map, CENTER_TILE, CENTER_TILE + 40)]).not.toBe(TileKind.water);+ // Most of the grid is land (an island, not a rock in the sea).+ let land = 0;+ for (let i = 0; i < map.kind.length; i++) if (map.kind[i] !== TileKind.water) land++;+ expect(land / map.kind.length).toBeGreaterThan(0.45);+ expect(land / map.kind.length).toBeLessThan(0.85);+ });++ it("keeps the whole market district flat on the plateau level", () => {+ const { map } = island;+ for (let tz = CENTER_TILE - MARKET_HALF_TILES; tz < CENTER_TILE + MARKET_HALF_TILES; tz++) {+ for (let tx = CENTER_TILE - MARKET_HALF_TILES; tx < CENTER_TILE + MARKET_HALF_TILES; tx++) {+ const i = tileIndex(map, tx, tz);+ expect(map.kind[i], `tile ${tx},${tz}`).not.toBe(TileKind.water);+ expect(map.level[i], `tile ${tx},${tz}`).toBe(PLATEAU_LEVEL);+ }+ }+ });++ it("opens a paved square in the middle with a ring of houses around it", () => {+ const { map, content } = island;+ expect(map.kind[tileIndex(map, CENTER_TILE + 5, CENTER_TILE + 5)]).toBe(TileKind.plaza);+ expect(content.houses.length).toBe(12);+ for (const h of content.houses) {+ const r = Math.hypot(h.x, h.z) / 2;+ expect(r).toBeGreaterThan(PLAZA_RADIUS_TILES);+ expect(r).toBeLessThan(HEDGE_RING_TILES);+ // Doors face the square: local +z rotated by `rotation` points at the centre.+ const fx = Math.sin(h.rotation);+ const fz = Math.cos(h.rotation);+ const toCentre = [-h.x, -h.z];+ const dot = fx * toCentre[0] + fz * toCentre[1];+ expect(dot).toBeGreaterThan(0);+ }+ });++ it("leaves the four gates open in the hedge ring", () => {+ const { content } = island;+ const r = HEDGE_RING_TILES * 2;+ for (const [gx, gz] of [+ [0, -r],+ [0, r],+ [-r, 0],+ [r, 0],+ ]) {+ const nearest = Math.min(...content.hedges.map((h) => Math.hypot(h.x - gx, h.z - gz)));+ expect(nearest).toBeGreaterThan(4);+ }+ expect(content.hedges.length).toBeGreaterThan(100);+ });++ it("reads ground height from the level table and the dock from its own height", () => {+ const { map } = island;+ const [x, z] = tileToWorld(CENTER_TILE, CENTER_TILE);+ expect(groundY(map, x, z)).toBe(LEVEL_Y[PLATEAU_LEVEL]);+ const [dx, dz] = tileToWorld(CENTER_TILE, DOCK_TILES.to);+ expect(map.kind[tileIndex(map, CENTER_TILE, DOCK_TILES.to)]).toBe(TileKind.dock);+ expect(groundY(map, dx, dz)).toBeGreaterThan(LEVEL_Y[0]);+ expect(groundY(map, 10_000, 10_000)).toBe(LEVEL_Y[0]);+ });++ it("makes every place reachable on foot from the square", () => {+ const { map, content } = island;+ const start = randomPlazaTile(map, () => 0.5);+ expect(isWalkable(map, start[0], start[1])).toBe(true);+ for (const place of Object.values(content.places)) {+ expect(isWalkable(map, place.standTile[0], place.standTile[1]), place.id).toBe(true);+ const path = findPath(map, start, place.standTile);+ expect(path, `path to ${place.id}`).not.toBeNull();+ expect(path![0]).toEqual(start);+ expect(path![path!.length - 1]).toEqual(place.standTile);+ const smooth = smoothPath(map, path!);+ expect(smooth.length).toBeLessThanOrEqual(path!.length);+ expect(smooth[0]).toEqual(start);+ expect(smooth[smooth.length - 1]).toEqual(place.standTile);+ }+ });++ it("refuses paths into the sea and through buildings", () => {+ const { map, content } = island;+ const start = randomPlazaTile(map, () => 0.3);+ expect(findPath(map, start, [0, 0])).toBeNull();+ const house = content.houses[0];+ const [hx, hz] = worldToTile(house.x, house.z);+ expect(isWalkable(map, hx, hz)).toBe(false);+ });++ it("plants trees on grass only, never on roads or the square", () => {+ const { map, content } = island;+ expect(content.trees.length).toBeGreaterThan(150);+ for (const t of content.trees) {+ const [tx, tz] = worldToTile(t.x, t.z);+ const k = map.kind[tileIndex(map, tx, tz)];+ expect([TileKind.grass, TileKind.meadow]).toContain(k);+ expect(Math.hypot(tx + 0.5 - CENTER_TILE, tz + 0.5 - CENTER_TILE)).toBeGreaterThan(+ PLAZA_RADIUS_TILES,+ );+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/islandLayout.ts b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.tsnew file mode 100644index 0000000000..bdb0baaedc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.ts@@ -0,0 +1,871 @@+/**+ * The island as numbers — the pure model behind `components/society/world/`.+ *+ * Everything the renderer draws and the walkers walk on is derived here from a+ * fixed seed, so two windows (and a unit test) always see the SAME island.+ * Nothing in this file touches three.js or React; `islandLayout.test.ts` pins+ * the geometry the way `deckRoom.test.ts` pins the mission deck.+ *+ * Layout decisions (maintainer, 2026-09-01 — recorded in+ * docs/agent-society/world-art-direction.md):+ *+ * - The island is a 10 × 10 grid of "fields". One field is what the viewer+ * sees at the closest zoom without scrolling. Fields are the navigation+ * unit, not a visible grid.+ * - The central 4 × 4 fields are the MARKET DISTRICT: a village laid out like+ * a ring — houses around one open square, the way a classic comic village+ * stands around its meeting place — but built in a bright solarpunk+ * language. The lead agent's hub stands at the head of the square.+ * - Four quarters around the market carry the places the master plan names+ * (§4.1): the workshop (west), the archive (north), the harbor gate on the+ * southern bay, the lighthouse on the eastern cape; gardens and a solar+ * field fill the corners.+ *+ * Units: 1 world unit = 1 m (matches `lib/deckRoom.ts`). One tile is 2 m.+ * World origin is the island's centre; +x is east, +z is south, so the tile+ * with index (tx, tz) has its centre at ((tx + 0.5 − 80) · 2, (tz + 0.5 − 80) · 2).+ */++// ---------------------------------------------------------------------------+// Grid constants+// ---------------------------------------------------------------------------++/** Edge of one terrain tile in metres. */+export const TILE_M = 2;+/** Tiles along one edge of a "field" — the closest zoom shows about one field. */+export const FIELD_TILES = 16;+/** Fields along one island edge. */+export const ISLAND_FIELDS = 10;+/** Tiles along one island edge (160). */+export const ISLAND_TILES = FIELD_TILES * ISLAND_FIELDS;+/** Half the island edge in metres — the pan clamp. */+export const ISLAND_HALF_M = (ISLAND_TILES * TILE_M) / 2;+/** Fields along one edge of the central market district. */+export const MARKET_FIELDS = 4;+/** Tiles along one edge of the market district (64). */+export const MARKET_TILES = MARKET_FIELDS * FIELD_TILES;+/** Half the market edge in tiles, from the centre. */+export const MARKET_HALF_TILES = MARKET_TILES / 2;+/** The island centre in tile units — also the market's centre. */+export const CENTER_TILE = ISLAND_TILES / 2;++/** Fixed seed: the island is designed, not rolled. */+export const ISLAND_SEED = 20260901;++// ---------------------------------------------------------------------------+// Tiles+// ---------------------------------------------------------------------------++export const TileKind = {+ water: 0,+ sand: 1,+ grass: 2,+ meadow: 3,+ rock: 4,+ plaza: 5,+ path: 6,+ garden: 7,+ dock: 8,+} as const;+export type TileKind = (typeof TileKind)[keyof typeof TileKind];++/**+ * Ground height per terrain level, in metres. Level 0 is the water surface;+ * the steps are small enough that a walker crossing one reads as a step, not+ * a jump, and large enough that the cliff faces show under the pixel pass.+ */+export const LEVEL_Y: readonly number[] = [0, 0.35, 1.0, 1.7, 2.6];+/** The level every road and plot sits on — the walkable plateau. */+export const PLATEAU_LEVEL = 2;+/** Height of the wooden dock above the water. */+export const DOCK_Y = 0.55;++export interface IslandMap {+ /** Tiles along one edge. */+ size: number;+ /** `TileKind` per tile, row-major (index = tz * size + tx). */+ kind: Uint8Array;+ /** Terrain level per tile (index into `LEVEL_Y`). */+ level: Uint8Array;+ /** 1 where a walker may not stand: water, rock, buildings, tree trunks. */+ blocked: Uint8Array;+}++// ---------------------------------------------------------------------------+// Places, houses, trees — the designed content+// ---------------------------------------------------------------------------++export type PlaceId =+ | "market"+ | "hub"+ | "workshop"+ | "archive"+ | "harbor"+ | "lighthouse"+ | "gardens"+ | "solar";++export interface Place {+ id: PlaceId;+ /** Tile the place is anchored on. */+ tile: [number, number];+ /** Tile a walker stands on when "at" this place (always walkable). */+ standTile: [number, number];+ /** Heading (rad, y-axis) a walker turns to once it has arrived. */+ facing: number;+}++export type HouseVariant = "solar-barrel" | "garden-roof" | "glass-loft";++export interface HousePlot {+ /** Centre of the footprint, world metres. */+ x: number;+ z: number;+ /** Footprint in tiles (w along the house's local x, d along local z). */+ w: number;+ d: number;+ /** Rotation about y; the door faces local +z. */+ rotation: number;+ variant: HouseVariant;+ /** Deterministic 0..1 for per-house variation. */+ seed: number;+}++export interface TreeSpot {+ x: number;+ z: number;+ /** Ground height under the trunk. */+ y: number;+ /** 0..1 — trunk height and canopy radius scale with it. */+ size: number;+ /** 0..1 — picks between the two canopy greens. */+ shade: number;+}++export interface Post {+ x: number;+ z: number;+ y: number;+ /** Rotation about y so a hedge segment follows the ring. */+ rotation: number;+}++export interface IslandContent {+ places: Record<PlaceId, Place>;+ houses: HousePlot[];+ trees: TreeSpot[];+ /** Hedge segments forming the village ring, with gaps at the four gates. */+ hedges: Post[];+ /** Light posts along the ring and the spokes. */+ lamps: Post[];+ /** Solar panel rows in the north-west field (centre + rotation). */+ panels: Post[];+ /** Greenhouses in the gardens quarter. */+ greenhouses: Post[];+}++// ---------------------------------------------------------------------------+// Deterministic noise+// ---------------------------------------------------------------------------++/** Integer hash → 0..1. Stable across platforms (32-bit integer math only). */+export function hash2(x: number, z: number, seed: number): number {+ let h = (Math.imul(x, 374761393) + Math.imul(z, 668265263) + Math.imul(seed, 1442695041)) | 0;+ h = Math.imul(h ^ (h >>> 13), 1274126177);+ h ^= h >>> 16;+ return (h >>> 0) / 4294967296;+}++function lerp(a: number, b: number, t: number): number {+ return a + (b - a) * t;+}++/** Smooth value noise, 0..1. */+export function valueNoise(x: number, z: number, seed: number): number {+ const x0 = Math.floor(x);+ const z0 = Math.floor(z);+ const fx = x - x0;+ const fz = z - z0;+ const sx = fx * fx * (3 - 2 * fx);+ const sz = fz * fz * (3 - 2 * fz);+ const a = hash2(x0, z0, seed);+ const b = hash2(x0 + 1, z0, seed);+ const c = hash2(x0, z0 + 1, seed);+ const d = hash2(x0 + 1, z0 + 1, seed);+ return lerp(lerp(a, b, sx), lerp(c, d, sx), sz);+}++/** Three octaves of value noise, normalised to 0..1. */+export function fbm(x: number, z: number, seed: number, octaves = 3): number {+ let amp = 0.5;+ let freq = 1;+ let sum = 0;+ let norm = 0;+ for (let i = 0; i < octaves; i++) {+ sum += amp * valueNoise(x * freq, z * freq, seed + i * 101);+ norm += amp;+ amp *= 0.5;+ freq *= 2.1;+ }+ return sum / norm;+}++// ---------------------------------------------------------------------------+// Coordinate helpers+// ---------------------------------------------------------------------------++/** Centre of tile (tx, tz) in world metres. */+export function tileToWorld(tx: number, tz: number): [number, number] {+ return [(tx + 0.5 - CENTER_TILE) * TILE_M, (tz + 0.5 - CENTER_TILE) * TILE_M];+}++/** The tile under world point (x, z); may lie outside the map. */+export function worldToTile(x: number, z: number): [number, number] {+ return [Math.floor(x / TILE_M + CENTER_TILE), Math.floor(z / TILE_M + CENTER_TILE)];+}++export function inBounds(map: IslandMap, tx: number, tz: number): boolean {+ return tx >= 0 && tz >= 0 && tx < map.size && tz < map.size;+}++export function tileIndex(map: IslandMap, tx: number, tz: number): number {+ return tz * map.size + tx;+}++/** Ground height under world (x, z): the tile's level, water outside the map. */+export function groundY(map: IslandMap, x: number, z: number): number {+ const [tx, tz] = worldToTile(x, z);+ if (!inBounds(map, tx, tz)) return LEVEL_Y[0];+ const i = tileIndex(map, tx, tz);+ if (map.kind[i] === TileKind.dock) return DOCK_Y;+ return LEVEL_Y[map.level[i]];+}++export function isWalkable(map: IslandMap, tx: number, tz: number): boolean {+ if (!inBounds(map, tx, tz)) return false;+ return map.blocked[tileIndex(map, tx, tz)] === 0;+}++// ---------------------------------------------------------------------------+// Design: where things stand (tile units, from the island centre)+// ---------------------------------------------------------------------------++/** Radius of the open square in the middle of the village. */+export const PLAZA_RADIUS_TILES = 13;+/** Where the house ring stands. */+export const HOUSE_RING_TILES = 19;+/** The ring road around the houses. */+export const RING_ROAD_TILES = 25;+/** The hedge ring that closes the village, with gaps at the gates. */+export const HEDGE_RING_TILES = 29;+/** Half-width of a gate gap in the hedge ring, in tiles. */+export const GATE_GAP_TILES = 3;++/** The four spokes leave the square toward the quarters. `dir` is (dx, dz). */+const SPOKES: ReadonlyArray<{ dir: [number, number]; toTiles: number }> = [+ { dir: [0, -1], toTiles: 52 }, // north → archive+ { dir: [0, 1], toTiles: 52 }, // south → harbor+ { dir: [-1, 0], toTiles: 52 }, // west → workshop+ { dir: [1, 0], toTiles: 58 }, // east → lighthouse cape+];++/** Anchor tiles of the places (tile units, absolute). */+const PLACE_TILES: Record<PlaceId, [number, number]> = {+ market: [CENTER_TILE, CENTER_TILE],+ hub: [CENTER_TILE, CENTER_TILE - 20],+ archive: [CENTER_TILE, CENTER_TILE - 54],+ harbor: [CENTER_TILE, CENTER_TILE + 54],+ workshop: [CENTER_TILE - 54, CENTER_TILE],+ lighthouse: [CENTER_TILE + 62, CENTER_TILE],+ gardens: [CENTER_TILE + 30, CENTER_TILE + 34],+ solar: [CENTER_TILE - 32, CENTER_TILE - 32],+};++/** Half extents (tiles) of the flat plots each place is built on. */+const PLOT_HALF: Record<PlaceId, [number, number]> = {+ market: [0, 0],+ hub: [5, 4],+ archive: [6, 6],+ harbor: [7, 4],+ workshop: [8, 6],+ lighthouse: [3, 3],+ gardens: [9, 7],+ solar: [8, 6],+};++/** Building footprints (half extents, tiles) that block walking. */+const BUILDING_HALF: Partial<Record<PlaceId, [number, number]>> = {+ hub: [4, 3],+ archive: [3, 3],+ workshop: [6, 3],+ lighthouse: [1, 1],+};++/** Where the dock reaches into the bay: from the harbor plot southward. */+export const DOCK_TILES = { from: CENTER_TILE + 58, to: CENTER_TILE + 70, halfWidth: 1 } as const;++// ---------------------------------------------------------------------------+// Building the map+// ---------------------------------------------------------------------------++function fillRect(+ map: IslandMap,+ cx: number,+ cz: number,+ hw: number,+ hd: number,+ fn: (i: number) => void,+): void {+ for (let tz = cz - hd; tz <= cz + hd; tz++) {+ for (let tx = cx - hw; tx <= cx + hw; tx++) {+ if (inBounds(map, tx, tz)) fn(tileIndex(map, tx, tz));+ }+ }+}++function paintPlateau(map: IslandMap, i: number, kind: TileKind): void {+ map.level[i] = PLATEAU_LEVEL;+ map.kind[i] = kind;+ map.blocked[i] = 0;+}++/**+ * The terrain pass: island silhouette, bay, beaches, highland, rock, and the+ * flat market plateau in the middle.+ */+function buildTerrain(map: IslandMap): void {+ const C = CENTER_TILE;+ for (let tz = 0; tz < map.size; tz++) {+ for (let tx = 0; tx < map.size; tx++) {+ const i = tileIndex(map, tx, tz);+ const nx = (tx + 0.5 - C) / C;+ const nz = (tz + 0.5 - C) / C;+ const d = Math.hypot(nx, nz);+ const shapeNoise = fbm(nx * 1.8 + 3.1, nz * 1.8 + 7.7, ISLAND_SEED);+ const shape = d + (shapeNoise - 0.5) * 0.36;+ // The harbor bay bites into the south coast.+ const bayDist = Math.hypot(nx - 0.06, nz - 1.0);+ const inBay = bayDist < 0.27;+ const isLand = shape < 0.92 && !inBay;++ if (!isLand) {+ map.kind[i] = TileKind.water;+ map.level[i] = 0;+ map.blocked[i] = 1;+ continue;+ }++ const elev = 1 - d * d + (fbm(nx * 3.3 + 11, nz * 3.3 + 5, ISLAND_SEED + 7) - 0.5) * 0.5;+ const onEdge = shape > 0.8 || bayDist < 0.34;+ let level = onEdge ? 1 : elev > 0.72 ? 3 : 2;+ let kind: TileKind = level === 1 ? TileKind.sand : level === 3 ? TileKind.meadow : TileKind.grass;++ // The north-eastern highland turns to rock where it climbs highest.+ if (nx > 0.18 && nz < -0.18 && !onEdge) {+ const ridge = fbm(nx * 5 + 21, nz * 5 + 9, ISLAND_SEED + 3);+ if (elev + 0.35 * ridge > 1.02) {+ level = 4;+ kind = TileKind.rock;+ }+ }++ map.level[i] = level;+ map.kind[i] = kind;+ map.blocked[i] = level === 4 ? 1 : 0;+ }+ }++ // The market district is one flat plateau — the village needs level ground,+ // and a plateau with a low rim reads as "the town" from any distance.+ fillRect(map, C, C, MARKET_HALF_TILES + 4, MARKET_HALF_TILES + 4, (i) => {+ if (map.kind[i] === TileKind.water) return; // the sea stays the sea+ paintPlateau(map, i, TileKind.grass);+ });+}++/** Rasterise a filled disc of tiles around (cx, cz). */+function paintDisc(+ map: IslandMap,+ cx: number,+ cz: number,+ rMin: number,+ rMax: number,+ fn: (i: number, tx: number, tz: number) => void,+): void {+ const r = Math.ceil(rMax);+ for (let tz = cz - r; tz <= cz + r; tz++) {+ for (let tx = cx - r; tx <= cx + r; tx++) {+ if (!inBounds(map, tx, tz)) continue;+ const dist = Math.hypot(tx + 0.5 - cx, tz + 0.5 - cz);+ if (dist >= rMin && dist < rMax) fn(tileIndex(map, tx, tz), tx, tz);+ }+ }+}++/** The village: square, ring road, spokes, garden beds, plots and the dock. */+function buildVillage(map: IslandMap): void {+ const C = CENTER_TILE;++ // Open square with a ring of garden beds around it.+ paintDisc(map, C, C, 0, PLAZA_RADIUS_TILES, (i) => paintPlateau(map, i, TileKind.plaza));+ paintDisc(map, C, C, PLAZA_RADIUS_TILES, PLAZA_RADIUS_TILES + 1.5, (i, tx, tz) => {+ // Beds alternate with plaza so the square stays open toward every house.+ const a = Math.atan2(tz + 0.5 - C, tx + 0.5 - C);+ const bed = Math.floor(((a + Math.PI) / (2 * Math.PI)) * 16) % 2 === 0;+ paintPlateau(map, i, bed ? TileKind.garden : TileKind.plaza);+ });++ // Ring road around the houses.+ paintDisc(map, C, C, RING_ROAD_TILES - 1, RING_ROAD_TILES + 1, (i) =>+ paintPlateau(map, i, TileKind.path),+ );++ // Spokes from the square out to the quarters (width 3).+ for (const spoke of SPOKES) {+ for (let s = PLAZA_RADIUS_TILES - 1; s <= spoke.toTiles; s++) {+ for (let w = -1; w <= 1; w++) {+ const tx = C + spoke.dir[0] * s + spoke.dir[1] * w;+ const tz = C + spoke.dir[1] * s + spoke.dir[0] * w;+ if (!inBounds(map, tx, tz)) continue;+ const i = tileIndex(map, tx, tz);+ if (map.kind[i] === TileKind.water) continue;+ paintPlateau(map, i, TileKind.path);+ }+ }+ }++ // Flat plots for every place; the buildings on them block walking.+ for (const id of Object.keys(PLACE_TILES) as PlaceId[]) {+ const [px, pz] = PLACE_TILES[id];+ const [hw, hd] = PLOT_HALF[id];+ if (hw === 0 && hd === 0) continue;+ const kind =+ id === "gardens" ? TileKind.garden : id === "solar" ? TileKind.meadow : TileKind.plaza;+ fillRect(map, px, pz, hw, hd, (i) => {+ if (map.kind[i] === TileKind.water) return;+ paintPlateau(map, i, kind);+ });+ if (id === "lighthouse") {+ // The lighthouse stands on a rocky knob.+ fillRect(map, px, pz, hw, hd, (i) => {+ map.level[i] = 3;+ map.kind[i] = TileKind.rock;+ map.blocked[i] = 0;+ });+ }+ const bh = BUILDING_HALF[id];+ if (bh) fillRect(map, px, pz, bh[0], bh[1], (i) => (map.blocked[i] = 1));+ }++ // The dock runs from the harbor plot into the bay.+ for (let tz = DOCK_TILES.from; tz <= DOCK_TILES.to; tz++) {+ for (let tx = C - DOCK_TILES.halfWidth; tx <= C + DOCK_TILES.halfWidth; tx++) {+ if (!inBounds(map, tx, tz)) continue;+ const i = tileIndex(map, tx, tz);+ map.kind[i] = TileKind.dock;+ map.blocked[i] = 0;+ }+ }+}++/** The house ring: 16 slots, the four gate directions left open, the hub north. */+function placeHouses(): HousePlot[] {+ const houses: HousePlot[] = [];+ const variants: HouseVariant[] = ["solar-barrel", "garden-roof", "glass-loft"];+ const slots = 16;+ for (let k = 0; k < slots; k++) {+ if (k % 4 === 0) continue; // N, E, S, W are gates (N also holds the hub)+ const angle = (k / slots) * Math.PI * 2; // clockwise from north+ const r = HOUSE_RING_TILES * TILE_M;+ const x = Math.sin(angle) * r;+ const z = -Math.cos(angle) * r;+ const seed = hash2(k, 7, ISLAND_SEED);+ houses.push({+ x,+ z,+ w: 3,+ d: 2,+ // The door (local +z) faces the square: rotate so local +z points to the centre.+ rotation: Math.atan2(-x, -z),+ variant: variants[k % variants.length],+ seed,+ });+ }+ return houses;+}++/** Block the tiles under every house so walkers route around them. */+function blockHouses(map: IslandMap, houses: HousePlot[]): void {+ for (const h of houses) {+ // Rasterise the rotated footprint by sampling its four quadrants.+ const hw = (h.w * TILE_M) / 2;+ const hd = (h.d * TILE_M) / 2;+ const cos = Math.cos(h.rotation);+ const sin = Math.sin(h.rotation);+ for (let lx = -hw + 0.5; lx <= hw; lx += 1) {+ for (let lz = -hd + 0.5; lz <= hd; lz += 1) {+ const wx = h.x + lx * cos + lz * sin;+ const wz = h.z - lx * sin + lz * cos;+ const [tx, tz] = worldToTile(wx, wz);+ if (inBounds(map, tx, tz)) map.blocked[tileIndex(map, tx, tz)] = 1;+ }+ }+ }+}++/** The hedge ring with its four gates, and the lamps along ring and spokes. */+function placeRingFurniture(map: IslandMap): { hedges: Post[]; lamps: Post[] } {+ const hedges: Post[] = [];+ const lamps: Post[] = [];+ const r = HEDGE_RING_TILES * TILE_M;+ const circumference = 2 * Math.PI * r;+ const segments = Math.round(circumference / 2.2);+ for (let s = 0; s < segments; s++) {+ const angle = (s / segments) * Math.PI * 2;+ // A gate is a gap centred on each cardinal direction.+ const gapHalf = (GATE_GAP_TILES * TILE_M) / r;+ const toCardinal = Math.abs(((angle + Math.PI / 4) % (Math.PI / 2)) - Math.PI / 4);+ if (toCardinal < gapHalf) continue;+ const x = Math.sin(angle) * r;+ const z = -Math.cos(angle) * r;+ hedges.push({ x, z, y: groundY(map, x, z), rotation: -angle });+ const [tx, tz] = worldToTile(x, z);+ if (inBounds(map, tx, tz)) map.blocked[tileIndex(map, tx, tz)] = 1;+ }+ // Lamps: one at every gate post pair, and along the spokes every 8 tiles.+ for (const spoke of SPOKES) {+ for (let s = PLAZA_RADIUS_TILES + 3; s <= spoke.toTiles - 2; s += 8) {+ for (const side of [-2.5, 2.5]) {+ const x = (spoke.dir[0] * s + spoke.dir[1] * side) * TILE_M;+ const z = (spoke.dir[1] * s + spoke.dir[0] * side) * TILE_M;+ const y = groundY(map, x, z);+ if (y <= LEVEL_Y[0]) continue;+ lamps.push({ x, z, y, rotation: 0 });+ }+ }+ }+ return { hedges, lamps };+}++/** Solar panel rows and greenhouses — the solarpunk furniture of two quarters. */+function placeQuarterFurniture(map: IslandMap): { panels: Post[]; greenhouses: Post[] } {+ const panels: Post[] = [];+ const greenhouses: Post[] = [];+ const [sx, sz] = PLACE_TILES.solar;+ for (let row = -2; row <= 2; row++) {+ for (let col = -3; col <= 3; col++) {+ const tx = sx + col * 2;+ const tz = sz + row * 3;+ const [x, z] = tileToWorld(tx, tz);+ panels.push({ x, z, y: groundY(map, x, z), rotation: 0 });+ if (inBounds(map, tx, tz)) map.blocked[tileIndex(map, tx, tz)] = 1;+ }+ }+ const [gx, gz] = PLACE_TILES.gardens;+ for (let row = -1; row <= 1; row++) {+ for (let col = -1; col <= 1; col += 2) {+ const tx = gx + col * 4;+ const tz = gz + row * 4;+ const [x, z] = tileToWorld(tx, tz);+ greenhouses.push({ x, z, y: groundY(map, x, z), rotation: 0 });+ fillRect(map, tx, tz, 1, 1, (i) => (map.blocked[i] = 1));+ }+ }+ return { panels, greenhouses };+}++/** Trees wherever grass or meadow is free, away from roads and plots. */+function placeTrees(map: IslandMap): TreeSpot[] {+ const trees: TreeSpot[] = [];+ const C = CENTER_TILE;+ for (let tz = 1; tz < map.size - 1; tz++) {+ for (let tx = 1; tx < map.size - 1; tx++) {+ const i = tileIndex(map, tx, tz);+ const k = map.kind[i];+ if (k !== TileKind.grass && k !== TileKind.meadow) continue;+ if (map.blocked[i]) continue;+ const rTiles = Math.hypot(tx + 0.5 - C, tz + 0.5 - C);+ // Inside the village only a few trees, between the houses and the hedge.+ const inVillage = rTiles < HEDGE_RING_TILES + 1;+ if (inVillage && (rTiles < HOUSE_RING_TILES + 2 || rTiles > RING_ROAD_TILES + 1.5)) continue;+ const density = inVillage ? 0.05 : k === TileKind.meadow ? 0.13 : 0.07;+ if (hash2(tx, tz, ISLAND_SEED + 55) > density) continue;+ // Keep a clear margin to anything built or paved.+ let clear = true;+ for (let dz = -1; dz <= 1 && clear; dz++) {+ for (let dx = -1; dx <= 1; dx++) {+ const j = tileIndex(map, tx + dx, tz + dz);+ const kk = map.kind[j];+ if (kk === TileKind.path || kk === TileKind.plaza || kk === TileKind.dock || kk === TileKind.garden || (map.blocked[j] && kk !== TileKind.water && kk !== TileKind.rock)) {+ clear = false;+ break;+ }+ }+ }+ if (!clear) continue;+ const [x, z] = tileToWorld(tx, tz);+ trees.push({+ x: x + (hash2(tx, tz, 3) - 0.5) * 0.8,+ z: z + (hash2(tx, tz, 4) - 0.5) * 0.8,+ y: LEVEL_Y[map.level[i]],+ size: hash2(tx, tz, 5),+ shade: hash2(tx, tz, 6),+ });+ map.blocked[i] = 1;+ }+ }+ return trees;+}++function buildPlaces(map: IslandMap): Record<PlaceId, Place> {+ const C = CENTER_TILE;+ const facingCentre = (tx: number, tz: number) => Math.atan2(C - tx, C - tz);+ const place = (id: PlaceId, standTile: [number, number], facing: number): Place => ({+ id,+ tile: PLACE_TILES[id],+ standTile,+ facing,+ });+ const places: Record<PlaceId, Place> = {+ // The meeting spot: at the table under the tree, facing it.+ market: place("market", [C - 4, C + 3], Math.atan2(4, -3)),+ // In front of the hub's door, facing the door (north).+ hub: place("hub", [C, PLACE_TILES.hub[1] + 5], Math.PI),+ archive: place("archive", [C, PLACE_TILES.archive[1] + 5], Math.PI),+ harbor: place("harbor", [C, PLACE_TILES.harbor[1] + 2], 0),+ workshop: place("workshop", [PLACE_TILES.workshop[0] + 8, C], -Math.PI / 2),+ lighthouse: place("lighthouse", [PLACE_TILES.lighthouse[0] - 3, C], Math.PI / 2),+ gardens: place("gardens", [PLACE_TILES.gardens[0], PLACE_TILES.gardens[1]], 0),+ solar: place("solar", [PLACE_TILES.solar[0] + 1, PLACE_TILES.solar[1] + 8], Math.PI),+ };+ void facingCentre;+ // Make sure every stand tile is walkable — a place nobody can reach is a bug.+ for (const p of Object.values(places)) {+ const [tx, tz] = p.standTile;+ if (inBounds(map, tx, tz)) {+ const i = tileIndex(map, tx, tz);+ map.blocked[i] = 0;+ if (map.kind[i] === TileKind.water) paintPlateau(map, i, TileKind.path);+ }+ }+ return places;+}++/** The central tree and the round table block the middle of the square. */+function blockSquareFurniture(map: IslandMap): void {+ const C = CENTER_TILE;+ fillRect(map, C, C, 1, 1, (i) => (map.blocked[i] = 1)); // trunk+}++export interface Island {+ map: IslandMap;+ content: IslandContent;+}++let cached: Island | null = null;++/** Build (once) the whole island. Deterministic: same numbers every call. */+export function buildIsland(): Island {+ if (cached) return cached;+ const size = ISLAND_TILES;+ const map: IslandMap = {+ size,+ kind: new Uint8Array(size * size),+ level: new Uint8Array(size * size),+ blocked: new Uint8Array(size * size),+ };+ buildTerrain(map);+ buildVillage(map);+ const houses = placeHouses();+ blockHouses(map, houses);+ blockSquareFurniture(map);+ const { hedges, lamps } = placeRingFurniture(map);+ const { panels, greenhouses } = placeQuarterFurniture(map);+ const trees = placeTrees(map);+ const places = buildPlaces(map);+ cached = { map, content: { places, houses, trees, hedges, lamps, panels, greenhouses } };+ return cached;+}++/** Tests that need a fresh build. */+export function resetIslandCache(): void {+ cached = null;+}++// ---------------------------------------------------------------------------+// Pathfinding — A* over walkable tiles, eight neighbours, no corner cutting+// ---------------------------------------------------------------------------++const SQRT2 = Math.SQRT2;++class MinHeap {+ private keys: number[] = [];+ private vals: number[] = [];+ get size(): number {+ return this.keys.length;+ }+ push(key: number, val: number): void {+ this.keys.push(key);+ this.vals.push(val);+ let i = this.keys.length - 1;+ while (i > 0) {+ const p = (i - 1) >> 1;+ if (this.keys[p] <= this.keys[i]) break;+ this.swap(i, p);+ i = p;+ }+ }+ pop(): number {+ const top = this.vals[0];+ const lastKey = this.keys.pop() as number;+ const lastVal = this.vals.pop() as number;+ if (this.keys.length > 0) {+ this.keys[0] = lastKey;+ this.vals[0] = lastVal;+ let i = 0;+ for (;;) {+ const l = 2 * i + 1;+ const r = l + 1;+ let m = i;+ if (l < this.keys.length && this.keys[l] < this.keys[m]) m = l;+ if (r < this.keys.length && this.keys[r] < this.keys[m]) m = r;+ if (m === i) break;+ this.swap(i, m);+ i = m;+ }+ }+ return top;+ }+ private swap(a: number, b: number): void {+ const k = this.keys[a];+ this.keys[a] = this.keys[b];+ this.keys[b] = k;+ const v = this.vals[a];+ this.vals[a] = this.vals[b];+ this.vals[b] = v;+ }+}++/** A step between two tiles is allowed when both are walkable and at most one level apart. */+function canStep(map: IslandMap, from: number, tx: number, tz: number): boolean {+ if (!isWalkable(map, tx, tz)) return false;+ const to = tileIndex(map, tx, tz);+ return Math.abs(map.level[to] - map.level[from]) <= 1;+}++/**+ * Shortest path from tile `from` to tile `to`, as a list of tiles INCLUDING the+ * start; `null` when no path exists (or the search budget runs out). Costs are+ * 1 / √2 per step, octile heuristic, corner cutting between two blocked tiles+ * forbidden so figures never clip a house corner.+ */+export function findPath(+ map: IslandMap,+ from: [number, number],+ to: [number, number],+ maxExpansions = 40_000,+): Array<[number, number]> | null {+ if (!isWalkable(map, to[0], to[1]) || !isWalkable(map, from[0], from[1])) return null;+ const n = map.size * map.size;+ const start = tileIndex(map, from[0], from[1]);+ const goal = tileIndex(map, to[0], to[1]);+ if (start === goal) return [from];+ const g = new Float32Array(n).fill(Infinity);+ const parent = new Int32Array(n).fill(-1);+ const closed = new Uint8Array(n);+ const heap = new MinHeap();+ const h = (i: number) => {+ const dx = Math.abs((i % map.size) - to[0]);+ const dz = Math.abs(Math.floor(i / map.size) - to[1]);+ return Math.max(dx, dz) + (SQRT2 - 1) * Math.min(dx, dz);+ };+ g[start] = 0;+ heap.push(h(start), start);+ let expansions = 0;+ while (heap.size > 0) {+ const cur = heap.pop();+ if (closed[cur]) continue;+ if (cur === goal) break;+ closed[cur] = 1;+ if (++expansions > maxExpansions) return null;+ const cx = cur % map.size;+ const cz = Math.floor(cur / map.size);+ for (let dz = -1; dz <= 1; dz++) {+ for (let dx = -1; dx <= 1; dx++) {+ if (dx === 0 && dz === 0) continue;+ const nx = cx + dx;+ const nz = cz + dz;+ if (!canStep(map, cur, nx, nz)) continue;+ if (dx !== 0 && dz !== 0) {+ // No squeezing diagonally between two blocked tiles.+ if (!isWalkable(map, cx + dx, cz) || !isWalkable(map, cx, cz + dz)) continue;+ }+ const ni = tileIndex(map, nx, nz);+ if (closed[ni]) continue;+ const cost = g[cur] + (dx !== 0 && dz !== 0 ? SQRT2 : 1);+ if (cost < g[ni]) {+ g[ni] = cost;+ parent[ni] = cur;+ heap.push(cost + h(ni), ni);+ }+ }+ }+ }+ if (parent[goal] === -1) return null;+ const path: Array<[number, number]> = [];+ for (let i = goal; i !== -1; i = parent[i]) {+ path.push([i % map.size, Math.floor(i / map.size)]);+ }+ path.reverse();+ return path;+}++/**+ * String-pulling: drop every waypoint that can be skipped along a straight,+ * fully walkable line, so a figure walks a polyline instead of zig-zagging+ * tile edges. Line walkability is sampled every half tile.+ */+export function smoothPath(map: IslandMap, path: Array<[number, number]>): Array<[number, number]> {+ if (path.length <= 2) return path;+ const out: Array<[number, number]> = [path[0]];+ let anchor = 0;+ while (anchor < path.length - 1) {+ let far = anchor + 1;+ for (let j = path.length - 1; j > anchor + 1; j--) {+ if (lineIsWalkable(map, path[anchor], path[j])) {+ far = j;+ break;+ }+ }+ out.push(path[far]);+ anchor = far;+ }+ return out;+}++function lineIsWalkable(map: IslandMap, a: [number, number], b: [number, number]): boolean {+ const steps = Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1])) * 2);+ let last = tileIndex(map, a[0], a[1]);+ for (let s = 1; s <= steps; s++) {+ const t = s / steps;+ const tx = Math.floor(a[0] + 0.5 + (b[0] - a[0]) * t);+ const tz = Math.floor(a[1] + 0.5 + (b[1] - a[1]) * t);+ if (!isWalkable(map, tx, tz)) return false;+ const i = tileIndex(map, tx, tz);+ if (Math.abs(map.level[i] - map.level[last]) > 1) return false;+ last = i;+ }+ return true;+}++/** A random walkable tile within the open square, for idle wandering. */+export function randomPlazaTile(map: IslandMap, rng: () => number): [number, number] {+ for (let attempt = 0; attempt < 32; attempt++) {+ const angle = rng() * Math.PI * 2;+ const r = 3 + rng() * (PLAZA_RADIUS_TILES - 4);+ const tx = Math.floor(CENTER_TILE + Math.cos(angle) * r);+ const tz = Math.floor(CENTER_TILE + Math.sin(angle) * r);+ if (isWalkable(map, tx, tz)) return [tx, tz];+ }+ return [CENTER_TILE + 4, CENTER_TILE + 4];+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/terrainGeometry.test.ts b/jarvis/ui/web/frontend/src/components/society/world/terrainGeometry.test.tsnew file mode 100644index 0000000000..1ad1151bec--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/terrainGeometry.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";++import { buildIsland, tileIndex, TileKind } from "./islandLayout";+import { buildTerrainGeometry, triangleCount } from "./terrainGeometry";++describe("terrainGeometry", () => {+ it("builds one coloured mesh with a top quad per land tile plus cliff sides", () => {+ const { map } = buildIsland();+ const geo = buildTerrainGeometry(map);+ let land = 0;+ for (let i = 0; i < map.kind.length; i++) if (map.kind[i] !== TileKind.water) land++;+ const tris = triangleCount(geo);+ expect(tris).toBeGreaterThanOrEqual(land * 2);+ // Sides exist (coast + plateau rim) but stay a fraction of the tops.+ expect(tris).toBeLessThan(land * 2 * 2.5);+ expect(geo.getAttribute("color").itemSize).toBe(3);+ expect(geo.getAttribute("normal").count).toBe(geo.getAttribute("position").count);+ expect(geo.boundingSphere).not.toBeNull();+ });++ it("keeps every top vertex on a level height", () => {+ const { map } = buildIsland();+ const geo = buildTerrainGeometry(map);+ const pos = geo.getAttribute("position");+ const nor = geo.getAttribute("normal");+ const heights = new Set<number>();+ for (let v = 0; v < pos.count; v++) {+ if (nor.getY(v) === 1) heights.add(Math.round(pos.getY(v) * 100) / 100);+ }+ // Levels 1..4 plus the dock: never a stray height.+ expect(heights.size).toBeLessThanOrEqual(5);+ const i = tileIndex(map, 80, 80);+ expect(map.kind[i]).toBe(TileKind.plaza);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/terrainGeometry.ts b/jarvis/ui/web/frontend/src/components/society/world/terrainGeometry.tsnew file mode 100644index 0000000000..7127e48d7a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/terrainGeometry.ts@@ -0,0 +1,127 @@+/**+ * The island's terrain as ONE merged mesh — stepped tiles with vertex colours.+ *+ * Every land tile contributes a flat top quad at its level's height and, where+ * a neighbour sits lower (or is sea), a vertical side quad down to that+ * neighbour: cliffs, beach steps and the plateau rim come out of the level+ * map for free. Colours are per tile (two alternating shades per kind, so the+ * ground has the tile-art flicker under the pixel pass) and per side.+ *+ * Pure three.js, no React: a test can build it under vitest, and the renderer+ * mounts the result once. ~13 k land tiles → roughly 40 k triangles.+ */+import { BufferAttribute, BufferGeometry, Color } from "three";++import {+ DOCK_Y,+ LEVEL_Y,+ TILE_M,+ TileKind,+ hash2,+ inBounds,+ tileIndex,+ type IslandMap,+} from "./islandLayout";+import { TILE_COLORS } from "./worldPalette";++/** How far below the water surface the coast walls reach (never a visible gap). */+const SEA_FLOOR_Y = -0.6;++type Vec3 = [number, number, number];++class MeshBuilder {+ positions: number[] = [];+ normals: number[] = [];+ colors: number[] = [];++ /** A quad from four corners in counter-clockwise order (seen from `normal`). */+ quad(a: Vec3, b: Vec3, c: Vec3, d: Vec3, normal: Vec3, color: Color): void {+ this.tri(a, b, c, normal, color);+ this.tri(a, c, d, normal, color);+ }++ private tri(a: Vec3, b: Vec3, c: Vec3, n: Vec3, col: Color): void {+ this.positions.push(...a, ...b, ...c);+ this.normals.push(...n, ...n, ...n);+ this.colors.push(col.r, col.g, col.b, col.r, col.g, col.b, col.r, col.g, col.b);+ }++ build(): BufferGeometry {+ const geo = new BufferGeometry();+ geo.setAttribute("position", new BufferAttribute(new Float32Array(this.positions), 3));+ geo.setAttribute("normal", new BufferAttribute(new Float32Array(this.normals), 3));+ geo.setAttribute("color", new BufferAttribute(new Float32Array(this.colors), 3));+ geo.computeBoundingSphere();+ return geo;+ }+}++const UP: Vec3 = [0, 1, 0];+const SOUTH: Vec3 = [0, 0, 1];+const NORTH: Vec3 = [0, 0, -1];+const EAST: Vec3 = [1, 0, 0];+const WEST: Vec3 = [-1, 0, 0];++const colorCache = new Map<string, Color>();+function color(hex: string): Color {+ let c = colorCache.get(hex);+ if (!c) {+ c = new Color(hex);+ colorCache.set(hex, c);+ }+ return c;+}++/** Height of a tile's top surface; the sea floor for water and out-of-map. */+function topY(map: IslandMap, tx: number, tz: number): number {+ if (!inBounds(map, tx, tz)) return SEA_FLOOR_Y;+ const i = tileIndex(map, tx, tz);+ const kind = map.kind[i];+ if (kind === TileKind.water) return SEA_FLOOR_Y;+ if (kind === TileKind.dock) return DOCK_Y;+ return LEVEL_Y[map.level[i]];+}++/** Build the terrain mesh for the whole map. */+export function buildTerrainGeometry(map: IslandMap): BufferGeometry {+ const b = new MeshBuilder();+ const half = (map.size * TILE_M) / 2;+ for (let tz = 0; tz < map.size; tz++) {+ for (let tx = 0; tx < map.size; tx++) {+ const i = tileIndex(map, tx, tz);+ const kind = map.kind[i] as TileKind;+ if (kind === TileKind.water) continue;+ const y = topY(map, tx, tz);+ const x0 = tx * TILE_M - half;+ const x1 = x0 + TILE_M;+ const z0 = tz * TILE_M - half;+ const z1 = z0 + TILE_M;+ const shades = TILE_COLORS[kind];+ const shade = hash2(tx, tz, 91) < 0.5 ? 0 : 1;+ // Garden beds: the second shade is the flower colour, sprinkled sparsely.+ const topIdx = kind === TileKind.garden ? (hash2(tx, tz, 92) < 0.3 ? 1 : 0) : shade;+ const top = color(shades.top[topIdx]);+ b.quad([x0, y, z0], [x0, y, z1], [x1, y, z1], [x1, y, z0], UP, top);++ const side = color(shades.side);+ // Dock planks stand on posts, not on a wall: no side faces, they float.+ if (kind === TileKind.dock) continue;++ const south = topY(map, tx, tz + 1);+ if (south < y) b.quad([x0, south, z1], [x1, south, z1], [x1, y, z1], [x0, y, z1], SOUTH, side);+ const north = topY(map, tx, tz - 1);+ if (north < y) b.quad([x1, north, z0], [x0, north, z0], [x0, y, z0], [x1, y, z0], NORTH, side);+ const east = topY(map, tx + 1, tz);+ if (east < y) b.quad([x1, east, z1], [x1, east, z0], [x1, y, z0], [x1, y, z1], EAST, side);+ const west = topY(map, tx - 1, tz);+ if (west < y) b.quad([x0, west, z0], [x0, west, z1], [x0, y, z1], [x0, y, z0], WEST, side);+ }+ }+ return b.build();+}++/** Triangle count of a non-indexed geometry — for tests and the dev HUD. */+export function triangleCount(geo: BufferGeometry): number {+ const pos = geo.getAttribute("position");+ return pos ? pos.count / 3 : 0;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.ts b/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.tsnew file mode 100644index 0000000000..8c6297ad21--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/useWorldControls.ts@@ -0,0 +1,114 @@+/**+ * Pointer and keyboard navigation over the island: drag to pan, wheel to step+ * the zoom, arrow keys / WASD to glide. Plain DOM listeners on the stage+ * host — never through React state on the move path, and never through R3F's+ * pointer events (those belong to the figures).+ */+import { useEffect, type RefObject } from "react";++import { useCameraStore } from "./cameraStore";+import { ZOOM_WIDTHS_M, dragToPan } from "./worldCamera";++/** Pointer travel below this is a click, not a drag. */+const DRAG_THRESHOLD_PX = 4;+/** One zoom step per wheel gesture, not per tick. */+const WHEEL_COOLDOWN_MS = 160;++const PAN_KEYS = new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "KeyW", "KeyA", "KeyS", "KeyD"]);++export function useWorldControls(hostRef: RefObject<HTMLElement | null>, enabled: boolean): void {+ useEffect(() => {+ const host = hostRef.current;+ if (!host || !enabled) return;+ const store = useCameraStore;++ let pointerId: number | null = null;+ let lastX = 0;+ let lastY = 0;+ let travelled = 0;+ let lastWheel = 0;++ const onPointerDown = (e: PointerEvent) => {+ if (e.button !== 0) return;+ pointerId = e.pointerId;+ lastX = e.clientX;+ lastY = e.clientY;+ travelled = 0;+ host.focus({ preventScroll: true });+ };++ const onPointerMove = (e: PointerEvent) => {+ if (pointerId !== e.pointerId) return;+ const dx = e.clientX - lastX;+ const dy = e.clientY - lastY;+ lastX = e.clientX;+ lastY = e.clientY;+ travelled += Math.abs(dx) + Math.abs(dy);+ if (travelled < DRAG_THRESHOLD_PX) return;+ if (!store.getState().dragging) {+ store.getState().setDragging(true);+ try {+ host.setPointerCapture(e.pointerId);+ } catch {+ /* a synthetic pointer without capture support still pans */+ }+ }+ const width = ZOOM_WIDTHS_M[store.getState().zoom];+ const [px, pz] = dragToPan(dx, dy, width, host.clientWidth || 1);+ store.getState().panBy(px, pz);+ };++ const endDrag = (e: PointerEvent) => {+ if (pointerId !== e.pointerId) return;+ pointerId = null;+ if (store.getState().dragging) {+ // Let the click that ends a drag pass first, then re-enable figure clicks.+ window.setTimeout(() => store.getState().setDragging(false), 0);+ }+ };++ const onWheel = (e: WheelEvent) => {+ e.preventDefault();+ const now = performance.now();+ if (now - lastWheel < WHEEL_COOLDOWN_MS) return;+ lastWheel = now;+ store.getState().zoomStep(e.deltaY > 0 ? 1 : -1);+ };++ const onKeyDown = (e: KeyboardEvent) => {+ if (PAN_KEYS.has(e.code)) {+ e.preventDefault();+ store.getState().keyDown(e.code);+ } else if (e.code === "Equal" || e.code === "NumpadAdd") {+ store.getState().zoomStep(-1);+ } else if (e.code === "Minus" || e.code === "NumpadSubtract") {+ store.getState().zoomStep(1);+ }+ };+ const onKeyUp = (e: KeyboardEvent) => {+ if (PAN_KEYS.has(e.code)) store.getState().keyUp(e.code);+ };+ const onBlur = () => store.getState().clearKeys();++ host.addEventListener("pointerdown", onPointerDown);+ host.addEventListener("pointermove", onPointerMove);+ host.addEventListener("pointerup", endDrag);+ host.addEventListener("pointercancel", endDrag);+ host.addEventListener("wheel", onWheel, { passive: false });+ host.addEventListener("keydown", onKeyDown);+ host.addEventListener("keyup", onKeyUp);+ host.addEventListener("blur", onBlur);+ return () => {+ host.removeEventListener("pointerdown", onPointerDown);+ host.removeEventListener("pointermove", onPointerMove);+ host.removeEventListener("pointerup", endDrag);+ host.removeEventListener("pointercancel", endDrag);+ host.removeEventListener("wheel", onWheel);+ host.removeEventListener("keydown", onKeyDown);+ host.removeEventListener("keyup", onKeyUp);+ host.removeEventListener("blur", onBlur);+ store.getState().clearKeys();+ store.getState().setDragging(false);+ };+ }, [hostRef, enabled]);+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/walkerKinematics.test.ts b/jarvis/ui/web/frontend/src/components/society/world/walkerKinematics.test.tsnew file mode 100644index 0000000000..d4de319eee--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/walkerKinematics.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from "vitest";++import {+ ARRIVE_SLOW_M,+ arrivalFactor,+ headingFor,+ isMoving,+ lateralOffset,+ shortestArc,+ stepAlong,+ turnToward,+} from "./walkerKinematics";++describe("walkerKinematics", () => {+ it("faces where it walks: +Z is heading 0, +X is heading +90°", () => {+ expect(headingFor(0, 1)).toBeCloseTo(0);+ expect(headingFor(1, 0)).toBeCloseTo(Math.PI / 2);+ expect(headingFor(0, -1)).toBeCloseTo(Math.PI);+ expect(headingFor(-1, 0)).toBeCloseTo(-Math.PI / 2);+ expect(headingFor(1, 1)).toBeCloseTo(Math.PI / 4);+ expect(headingFor(-1, -1)).toBeCloseTo((-3 * Math.PI) / 4);+ });++ it("turns the short way round across the ±π seam", () => {+ expect(shortestArc(0.9 * Math.PI, -0.9 * Math.PI)).toBeCloseTo(0.2 * Math.PI);+ expect(shortestArc(-0.9 * Math.PI, 0.9 * Math.PI)).toBeCloseTo(-0.2 * Math.PI);+ expect(shortestArc(0, Math.PI / 2)).toBeCloseTo(Math.PI / 2);+ const next = turnToward(0.95 * Math.PI, -0.95 * Math.PI, 0.05);+ expect(shortestArc(0.95 * Math.PI, next)).toBeGreaterThan(0);+ });++ it("never exceeds the turn step and lands exactly when close", () => {+ expect(turnToward(0, 0.01, 0.1)).toBe(0.01);+ const stepped = turnToward(0, 2, 0.3);+ expect(stepped).toBeGreaterThan(0);+ expect(stepped).toBeLessThanOrEqual(0.3 + 1e-9);+ });++ it("keeps the heading frozen at rest", () => {+ expect(isMoving(0.01, 0.01)).toBe(false);+ expect(isMoving(0.1, 0)).toBe(true);+ });++ it("decelerates into the last waypoint and reaches it exactly", () => {+ expect(arrivalFactor(10)).toBe(1);+ expect(arrivalFactor(ARRIVE_SLOW_M / 2)).toBeCloseTo(0.5);+ expect(arrivalFactor(0)).toBe(0.35);+ let x = 0;+ let z = 0;+ let index = 0;+ const path: Array<[number, number]> = [+ [0, 2],+ [2, 2],+ ];+ let steps = 0;+ for (; steps < 1000; steps++) {+ const r = stepAlong(x, z, path, index, 1.0, 1 / 60);+ x = r.x;+ z = r.z;+ index = r.index;+ if (r.arrived) break;+ }+ expect(x).toBeCloseTo(2, 6);+ expect(z).toBeCloseTo(2, 6);+ expect(steps).toBeGreaterThan(4 * 60 - 5); // ≥ 4 m at ≤ 1 m/s+ });++ it("passes through corners without stopping and reports the velocity", () => {+ const r = stepAlong(0, 0, [[0, 1], [1, 1]], 0, 2.0, 1.0);+ // 2 m of budget: 1 m north to the corner, then 1 m east.+ expect(r.x).toBeCloseTo(1);+ expect(r.z).toBeCloseTo(1);+ expect(r.arrived).toBe(true);+ expect(Math.hypot(r.vx, r.vz)).toBeGreaterThan(1);+ });++ it("offsets walkers deterministically within ±0.3 m", () => {+ expect(lateralOffset("scout")).toBe(lateralOffset("scout"));+ for (const id of ["jarvis", "scout", "archivist", "quill"]) {+ expect(Math.abs(lateralOffset(id))).toBeLessThanOrEqual(0.3);+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/walkerKinematics.ts b/jarvis/ui/web/frontend/src/components/society/world/walkerKinematics.tsnew file mode 100644index 0000000000..750db96063--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/walkerKinematics.ts@@ -0,0 +1,122 @@+/**+ * The locomotion rules that keep a figure from walking backwards, sliding or+ * snapping — docs/agent-society/character-pipeline.md §6, as pure functions.+ * The R3F walker reads these and holds no math of its own;+ * `walkerKinematics.test.ts` pins them.+ */++/** Below this speed a figure keeps its last heading (§6.2). */+export const MOVING_EPS_MPS = 0.05;+/** Nominal biped walking speed: a 1.28 m stride over a 1.0 s clip (§6.3). */+export const NOMINAL_WALK_MPS = 1.28;+/** Wander walks calmer than a purposeful move (§6.3). */+export const WANDER_SPEED_MPS = NOMINAL_WALK_MPS * 0.8;+/** Maximum yaw rate for a biped, 540 °/s (§6.2). */+export const TURN_RATE_RAD_S = (540 * Math.PI) / 180;+/** Arrival: decelerate over the last 0.4 m (§6.2). */+export const ARRIVE_SLOW_M = 0.4;+/** A target more than 120° behind is a reversal: turn in place first (§6.2). */+export const REVERSAL_RAD = (120 * Math.PI) / 180;+export const REVERSAL_HOLD_S = 0.15;++/**+ * Heading for a ground velocity. A figure faces +Z in its own space, and+ * `rotation.y = θ` maps local +Z to world (sin θ, 0, cos θ), hence+ * atan2(vx, vz) — not atan2(vz, vx).+ */+export function headingFor(vx: number, vz: number): number {+ return Math.atan2(vx, vz);+}++/** The signed shortest rotation from `from` to `to`, in (−π, π]. */+export function shortestArc(from: number, to: number): number {+ let d = (to - from) % (2 * Math.PI);+ if (d > Math.PI) d -= 2 * Math.PI;+ if (d <= -Math.PI) d += 2 * Math.PI;+ return d;+}++/**+ * Turn `current` toward `target` by at most `maxStep` radians along the+ * shortest arc, with an ease-out over the last stretch so the stop is soft.+ */+export function turnToward(current: number, target: number, maxStep: number): number {+ const d = shortestArc(current, target);+ if (Math.abs(d) <= maxStep) return target;+ const eased = Math.min(maxStep, Math.abs(d) * 0.55 + maxStep * 0.45);+ return current + Math.sign(d) * eased;+}++export function isMoving(vx: number, vz: number): boolean {+ return Math.hypot(vx, vz) > MOVING_EPS_MPS;+}++/** Speed factor for the remaining distance to the final waypoint. */+export function arrivalFactor(remainingM: number): number {+ if (remainingM >= ARRIVE_SLOW_M) return 1;+ return Math.max(0.35, remainingM / ARRIVE_SLOW_M);+}++export interface StepResult {+ x: number;+ z: number;+ /** Index of the waypoint being approached after this step. */+ index: number;+ /** Ground velocity over this step, m/s. */+ vx: number;+ vz: number;+ /** True once the final waypoint is reached. */+ arrived: boolean;+}++/**+ * Advance along a polyline of waypoints for `dt` seconds at `speed`, passing+ * through corners without stopping, decelerating into the last point. The+ * figure never overshoots the final waypoint.+ */+export function stepAlong(+ x: number,+ z: number,+ waypoints: ReadonlyArray<[number, number]>,+ index: number,+ speed: number,+ dt: number,+): StepResult {+ if (index >= waypoints.length) return { x, z, index, vx: 0, vz: 0, arrived: true };+ const startX = x;+ const startZ = z;+ const last = waypoints[waypoints.length - 1];+ const remainingToEnd = Math.hypot(last[0] - x, last[1] - z);+ let budget = speed * arrivalFactor(remainingToEnd) * dt;+ let i = index;+ while (budget > 0 && i < waypoints.length) {+ const [wx, wz] = waypoints[i];+ const dx = wx - x;+ const dz = wz - z;+ const dist = Math.hypot(dx, dz);+ if (dist <= budget) {+ x = wx;+ z = wz;+ budget -= dist;+ i++;+ } else {+ x += (dx / dist) * budget;+ z += (dz / dist) * budget;+ budget = 0;+ }+ }+ const arrived = i >= waypoints.length;+ const vx = dt > 0 ? (x - startX) / dt : 0;+ const vz = dt > 0 ? (z - startZ) / dt : 0;+ return { x, z, index: i, vx, vz, arrived };+}++/**+ * Two walkers sharing a tile stand a little apart: a deterministic lateral+ * offset keyed by the agent id (§6.4), ±0.3 m, never simulated avoidance.+ */+export function lateralOffset(agentId: string): number {+ let h = 0;+ for (let i = 0; i < agentId.length; i++) h = (h * 31 + agentId.charCodeAt(i)) | 0;+ return (((h >>> 0) % 1000) / 1000 - 0.5) * 0.6;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/walkerRegistry.ts b/jarvis/ui/web/frontend/src/components/society/world/walkerRegistry.tsnew file mode 100644index 0000000000..58c47795e3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/walkerRegistry.ts@@ -0,0 +1,25 @@+/**+ * Where every walker is right now — a plain mutable map the walkers write+ * each frame and the minimap reads a few times a second. Not React state on+ * purpose: positions change every frame and nothing but the minimap cares.+ */+export interface WalkerPin {+ x: number;+ z: number;+ color: string;+ name: string;+}++const pins = new Map<string, WalkerPin>();++export function setWalkerPin(agentId: string, pin: WalkerPin): void {+ pins.set(agentId, pin);+}++export function clearWalkerPin(agentId: string): void {+ pins.delete(agentId);+}++export function walkerPins(): ReadonlyMap<string, WalkerPin> {+ return pins;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/wander.test.ts b/jarvis/ui/web/frontend/src/components/society/world/wander.test.tsnew file mode 100644index 0000000000..2f1063a9c3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/wander.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";++import {+ DWELL_MAX_S,+ DWELL_MEAN_S,+ DWELL_MIN_S,+ REST_PROBABILITY,+ dwellSeconds,+ mulberry32,+ nextBeat,+ seedFromString,+} from "./wander";++describe("wander", () => {+ it("rests on most beats", () => {+ const rng = mulberry32(7);+ let rests = 0;+ const n = 5000;+ for (let i = 0; i < n; i++) if (nextBeat(rng).kind === "rest") rests++;+ expect(rests / n).toBeGreaterThan(REST_PROBABILITY - 0.03);+ expect(rests / n).toBeLessThan(REST_PROBABILITY + 0.03);+ });++ it("dwells exponentially around the mean, inside the clamp band", () => {+ const rng = mulberry32(11);+ let sum = 0;+ const n = 4000;+ for (let i = 0; i < n; i++) {+ const d = dwellSeconds(rng);+ expect(d).toBeGreaterThanOrEqual(DWELL_MIN_S);+ expect(d).toBeLessThanOrEqual(DWELL_MAX_S);+ sum += d;+ }+ // Clamping pulls the mean a little; it must still sit near the target.+ expect(sum / n).toBeGreaterThan(DWELL_MEAN_S - 0.8);+ expect(sum / n).toBeLessThan(DWELL_MEAN_S + 0.8);+ });++ it("is repeatable per seed and different across seeds", () => {+ const a = mulberry32(seedFromString("scout"));+ const b = mulberry32(seedFromString("scout"));+ const c = mulberry32(seedFromString("archivist"));+ expect(a()).toBe(b());+ expect(a()).not.toBe(c());+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/wander.ts b/jarvis/ui/web/frontend/src/components/society/world/wander.tsnew file mode 100644index 0000000000..ba8d5ed5bf--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/wander.ts@@ -0,0 +1,52 @@+/**+ * Idle life at zero token cost: the rest-biased wander model.+ *+ * MASTERPLAN §2.7/§2.8 — idle agents wander client-side, no LLM, no sync+ * between windows. The behaviour is re-implemented from the published+ * description of ambient pet AI (GameAIPro ch. 36 as cited by Hermes' roam+ * model; no code taken): most decision beats REST, and dwell times are+ * exponentially distributed so nothing ticks like a metronome.+ */++/** Share of decision beats that rest instead of walking. */+export const REST_PROBABILITY = 0.62;+/** Mean rest length in seconds; clamped to the band below. */+export const DWELL_MEAN_S = 4.2;+export const DWELL_MIN_S = 1.5;+export const DWELL_MAX_S = 13;+/** How long a working agent holds its desk pose before the next idle beat. */+export const WORK_BEAT_S = 6;++export type Beat = { kind: "rest"; seconds: number } | { kind: "walk" };++/** Exponential dwell with the documented mean, clamped so it reads as calm. */+export function dwellSeconds(rng: () => number): number {+ const u = Math.min(1 - 1e-9, Math.max(1e-9, rng()));+ const raw = -Math.log(1 - u) * DWELL_MEAN_S;+ return Math.min(DWELL_MAX_S, Math.max(DWELL_MIN_S, raw));+}++export function nextBeat(rng: () => number): Beat {+ if (rng() < REST_PROBABILITY) return { kind: "rest", seconds: dwellSeconds(rng) };+ return { kind: "walk" };+}++/** A small seeded PRNG so two windows wander differently but a test repeats. */+export function mulberry32(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++export function seedFromString(s: string): number {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/waterTexture.ts b/jarvis/ui/web/frontend/src/components/society/world/waterTexture.tsnew file mode 100644index 0000000000..e4656d1d05--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/waterTexture.ts@@ -0,0 +1,56 @@+/**+ * A tiny pixel-art water tile, drawn on a canvas at runtime: flat surface with+ * a few lighter ripple strokes and rare foam dots. Nearest-filtered and+ * repeated over the sea plane, then scrolled slowly — the classic animated+ * pixel water. No asset file, no network.+ */+import { CanvasTexture, NearestFilter, RepeatWrapping, SRGBColorSpace } from "three";++import { WATER } from "./worldPalette";+import { hash2 } from "./islandLayout";++/** Texels per tile side. One tile of texture covers `WATER_TILE_M` metres. */+export const WATER_TEXELS = 32;+export const WATER_TILE_M = 8;++export function makeWaterTexture(): CanvasTexture | null {+ if (typeof document === "undefined") return null;+ const canvas = document.createElement("canvas");+ canvas.width = WATER_TEXELS;+ canvas.height = WATER_TEXELS;+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ ctx.fillStyle = WATER.surface;+ ctx.fillRect(0, 0, WATER_TEXELS, WATER_TEXELS);+ // Darker patches so the sea is not one flat sheet.+ ctx.fillStyle = WATER.deep;+ for (let i = 0; i < 14; i++) {+ const x = Math.floor(hash2(i, 1, 7) * WATER_TEXELS);+ const y = Math.floor(hash2(i, 2, 7) * WATER_TEXELS);+ const w = 3 + Math.floor(hash2(i, 3, 7) * 5);+ ctx.fillRect(x, y, w, 1);+ }+ // Ripple strokes: short horizontal light lines.+ ctx.fillStyle = WATER.ripple;+ for (let i = 0; i < 10; i++) {+ const x = Math.floor(hash2(i, 4, 7) * WATER_TEXELS);+ const y = Math.floor(hash2(i, 5, 7) * WATER_TEXELS);+ const w = 2 + Math.floor(hash2(i, 6, 7) * 4);+ ctx.fillRect(x, y, w, 1);+ }+ // Foam: single bright pixels.+ ctx.fillStyle = WATER.foam;+ for (let i = 0; i < 4; i++) {+ const x = Math.floor(hash2(i, 8, 7) * WATER_TEXELS);+ const y = Math.floor(hash2(i, 9, 7) * WATER_TEXELS);+ ctx.fillRect(x, y, 1, 1);+ }+ const tex = new CanvasTexture(canvas);+ tex.magFilter = NearestFilter;+ tex.minFilter = NearestFilter;+ tex.generateMipmaps = false;+ tex.wrapS = RepeatWrapping;+ tex.wrapT = RepeatWrapping;+ tex.colorSpace = SRGBColorSpace;+ return tex;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/world.css b/jarvis/ui/web/frontend/src/components/society/world/world.cssnew file mode 100644index 0000000000..b28750d6e4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/world.css@@ -0,0 +1,213 @@+/*+ * The world viewport's own skin — MASTERPLAN §4.3: everything drawn inside the+ * island (labels, nameplates, the game HUD) carries the world's bright+ * branding, NOT the app's theme tokens. That is why this file uses literal+ * colours; they are the world palette (worldPalette.ts LABEL), the same in+ * light and dark mode by design, because the island has its own daylight.+ * The World / Ledger switch handed in from the section is app chrome and+ * keeps its Tailwind theme classes.+ */++.sw-stage {+ position: relative;+ width: 100%;+ height: 100%;+ min-height: 0;+ overflow: hidden;+ background: #a5dbff;+ outline: none;+ touch-action: none;+ user-select: none;+ cursor: grab;+}+.sw-stage:active {+ cursor: grabbing;+}+.sw-stage canvas {+ display: block;+ image-rendering: pixelated;+}++/* ---- in-world text ------------------------------------------------------ */++.sw-nameplate,+.sw-placelabel {+ font-family: "Pixelify Sans", "Space Grotesk", ui-sans-serif, system-ui, sans-serif;+ color: #1f2a3a;+ white-space: nowrap;+ line-height: 1;+}++.sw-nameplate {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 3px 7px 4px 6px;+ font-size: 13px;+ font-weight: 500;+ background: rgba(255, 252, 245, 0.88);+ border: 1px solid rgba(31, 42, 58, 0.18);+ border-radius: 4px;+ box-shadow: 0 2px 0 rgba(31, 42, 58, 0.25);+}+.sw-nameplate[data-selected] {+ background: #fff8dc;+ border-color: #1f2a3a;+}+.sw-nameplate[data-state="paused"] {+ opacity: 0.72;+}+.sw-nameplate-dot {+ width: 8px;+ height: 8px;+ border-radius: 2px;+ border: 1px solid rgba(31, 42, 58, 0.4);+ flex: none;+}+.sw-nameplate[data-state="working"] .sw-nameplate-dot {+ animation: sw-pulse 1.2s ease-in-out infinite;+}+@keyframes sw-pulse {+ 0%,+ 100% {+ transform: scale(1);+ }+ 50% {+ transform: scale(1.35);+ }+}++.sw-placelabel {+ padding: 4px 9px 5px;+ font-size: 15px;+ font-weight: 600;+ letter-spacing: 0.02em;+ color: #fffaf0;+ background: rgba(31, 42, 58, 0.62);+ border-radius: 5px;+ text-shadow: 0 1px 0 rgba(0, 0, 0, 0.35);+}++/* ---- the game HUD ------------------------------------------------------- */++.sw-hud {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ padding: 12px;+ pointer-events: none;+ font-family: "Pixelify Sans", "Space Grotesk", ui-sans-serif, system-ui, sans-serif;+}+.sw-hud > * > * {+ pointer-events: auto;+}+.sw-hud-top,+.sw-hud-bottom {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 12px;+}+.sw-hud-bottom {+ align-items: flex-end;+}+.sw-chip-row {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}+.sw-chip {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 6px 10px 7px;+ font-size: 14px;+ color: #1f2a3a;+ background: rgba(255, 252, 245, 0.9);+ border: 1px solid rgba(31, 42, 58, 0.2);+ border-radius: 6px;+ box-shadow: 0 2px 0 rgba(31, 42, 58, 0.25);+}+.sw-chip strong {+ font-weight: 600;+}+.sw-chip-sep {+ width: 1px;+ height: 12px;+ background: rgba(31, 42, 58, 0.25);+}+.sw-chip-note {+ font-size: 12px;+ color: #4a5568;+ background: rgba(255, 248, 220, 0.9);+}+.sw-hint {+ font-size: 12px;+ color: #1f2a3a;+ background: rgba(255, 252, 245, 0.7);+ padding: 4px 8px;+ border-radius: 4px;+}+.sw-corner {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 8px;+}+.sw-zoom {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 3px;+ background: rgba(255, 252, 245, 0.9);+ border: 1px solid rgba(31, 42, 58, 0.2);+ border-radius: 6px;+ box-shadow: 0 2px 0 rgba(31, 42, 58, 0.25);+}+.sw-zoom-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 26px;+ height: 26px;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: #1f2a3a;+ cursor: pointer;+}+.sw-zoom-btn:hover:not(:disabled) {+ background: rgba(31, 42, 58, 0.1);+}+.sw-zoom-btn:disabled {+ opacity: 0.35;+ cursor: default;+}+.sw-zoom-level {+ min-width: 44px;+ text-align: center;+ font-size: 12px;+ color: #1f2a3a;+}+.sw-minimap {+ width: 168px;+ height: 168px;+ image-rendering: pixelated;+ border: 2px solid rgba(255, 252, 245, 0.95);+ border-radius: 6px;+ box-shadow: 0 2px 0 rgba(31, 42, 58, 0.35);+ cursor: crosshair;+}++/* ---- fallback (no WebGL) ------------------------------------------------ */++.sw-fallback {+ display: flex;+ height: 100%;+ align-items: center;+ justify-content: center;+ padding: 24px;+ text-align: center;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.ts b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.tsnew file mode 100644index 0000000000..0c058cae30--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";++import { focusFromSearch } from "./cameraStore";+import { ISLAND_HALF_M } from "./islandLayout";+import {+ CAMERA_PITCH_DEG,+ CAMERA_YAW_DEG,+ DEFAULT_ZOOM,+ ZOOM_WIDTHS_M,+ cameraOffset,+ clampTarget,+ dragToPan,+ groundBasis,+ orthoHalfExtents,+ stepZoom,+ visibleGroundCorners,+} from "./worldCamera";++describe("worldCamera", () => {+ it("looks down steeply from the south-east", () => {+ expect(CAMERA_PITCH_DEG).toBe(50);+ expect(CAMERA_YAW_DEG).toBe(45);+ const [x, y, z] = cameraOffset();+ expect(x).toBeGreaterThan(0);+ expect(z).toBeGreaterThan(0);+ expect(x).toBeCloseTo(z, 3);+ // Steeper than 45°: more height than ground distance.+ expect(y).toBeGreaterThan(Math.hypot(x, z));+ });++ it("zooms in three fixed steps and clamps at both ends", () => {+ expect(ZOOM_WIDTHS_M).toEqual([32, 64, 128]);+ expect(stepZoom(DEFAULT_ZOOM, 1)).toBe(2);+ expect(stepZoom(2, 1)).toBe(2);+ expect(stepZoom(0, -1)).toBe(0);+ expect(stepZoom(1, -1)).toBe(0);+ });++ it("sizes the frustum from the visible width and the aspect", () => {+ const { halfW, halfH } = orthoHalfExtents(64, 16 / 9);+ expect(halfW).toBe(32);+ expect(halfH).toBeCloseTo(18, 3);+ });++ it("maps screen-right to north-east and screen-up to north-west at 45° yaw", () => {+ const { right, forward } = groundBasis();+ expect(right[0]).toBeCloseTo(Math.SQRT1_2, 5);+ expect(right[1]).toBeCloseTo(-Math.SQRT1_2, 5);+ expect(forward[0]).toBeCloseTo(-Math.SQRT1_2, 5);+ expect(forward[1]).toBeCloseTo(-Math.SQRT1_2, 5);+ // Perpendicular unit vectors.+ expect(right[0] * forward[0] + right[1] * forward[1]).toBeCloseTo(0, 6);+ });++ it("pans the target against the drag so the world follows the pointer", () => {+ const widthM = 64;+ const stagePx = 1280; // 0.05 m per px+ const { right, forward } = groundBasis();+ // Drag right by 200 px → target moves 10 m to screen-left.+ const [dx, dz] = dragToPan(200, 0, widthM, stagePx);+ expect(dx).toBeCloseTo(-10 * right[0], 4);+ expect(dz).toBeCloseTo(-10 * right[1], 4);+ // Drag down by 100 px → target moves forward (up-screen), stretched by 1/sin(50°).+ const [fx, fz] = dragToPan(0, 100, widthM, stagePx);+ const ground = 5 / Math.sin((50 * Math.PI) / 180);+ expect(fx).toBeCloseTo(ground * forward[0], 4);+ expect(fz).toBeCloseTo(ground * forward[1], 4);+ expect(dragToPan(10, 10, widthM, 0)).toEqual([0, 0]);+ });++ it("keeps the target on the island", () => {+ expect(clampTarget(10_000, -10_000)).toEqual([ISLAND_HALF_M, -ISLAND_HALF_M]);+ expect(clampTarget(3, -4)).toEqual([3, -4]);+ });++ it("draws the viewport as a rectangle centred on the target, deeper than wide on the ground", () => {+ const corners = visibleGroundCorners([0, 0], 64, 16 / 9);+ expect(corners).toHaveLength(4);+ const cx = corners.reduce((s, c) => s + c[0], 0) / 4;+ const cz = corners.reduce((s, c) => s + c[1], 0) / 4;+ expect(cx).toBeCloseTo(0, 4);+ expect(cz).toBeCloseTo(0, 4);+ const width = Math.hypot(corners[1][0] - corners[0][0], corners[1][1] - corners[0][1]);+ const depth = Math.hypot(corners[3][0] - corners[0][0], corners[3][1] - corners[0][1]);+ expect(width).toBeCloseTo(64, 3);+ expect(depth).toBeCloseTo(36 / Math.sin((50 * Math.PI) / 180), 3);+ });++ it("reads a ?world=x,z,zoom deep link and ignores garbage", () => {+ expect(focusFromSearch("?view=agents&world=12,-30,0")).toEqual({ target: [12, -30], zoom: 0 });+ expect(focusFromSearch("?world=5,5")).toEqual({ target: [5, 5], zoom: 1 });+ expect(focusFromSearch("?world=9999,0,7")?.target[0]).toBe(ISLAND_HALF_M);+ expect(focusFromSearch("?world=abc")).toBeNull();+ expect(focusFromSearch("?view=agents")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.tsnew file mode 100644index 0000000000..85e778f0ea--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts@@ -0,0 +1,131 @@+/**+ * The bird's-eye camera as numbers: pitch, yaw, the three zoom steps and the+ * conversions between screen pixels and ground metres. Pure, pinned by+ * `worldCamera.test.ts`; the R3F rig only reads these.+ *+ * Decisions (maintainer, 2026-09-01): a STEEP bird's-eye view — 50° below+ * the horizon at the classic 45° dimetric yaw — so the island reads as "seen+ * from above" while house fronts and figure silhouettes stay visible. Zoom+ * is three fixed steps (one field, four fields, the whole market district),+ * never continuous: with an integer pixel size every step stays crisp.+ */+import { ISLAND_HALF_M } from "./islandLayout";++export const CAMERA_PITCH_DEG = 50;+export const CAMERA_YAW_DEG = 45;+/** Far enough that nothing on the island reaches behind the camera. */+export const CAMERA_DISTANCE_M = 420;++/** Ground width the orthographic frustum shows per zoom step, in metres. */+export const ZOOM_WIDTHS_M = [32, 64, 128] as const;+export type ZoomLevel = 0 | 1 | 2;+/** Start on the middle step: the whole village square fits, figures stay readable. */+export const DEFAULT_ZOOM: ZoomLevel = 1;++/**+ * Screen pixels per rendered pixel — the "fine" grain the maintainer chose+ * (a 1280-px-wide stage renders at 640 px). 3 would be "light", 4 "coarse".+ */+export const PIXEL_SIZE = 2;++/** Keyboard pan speed as a fraction of the visible width per second. */+export const KEY_PAN_PER_S = 0.9;++const DEG = Math.PI / 180;++/** Camera position relative to its target for the given pitch/yaw/distance. */+export function cameraOffset(+ pitchDeg = CAMERA_PITCH_DEG,+ yawDeg = CAMERA_YAW_DEG,+ distance = CAMERA_DISTANCE_M,+): [number, number, number] {+ const p = pitchDeg * DEG;+ const y = yawDeg * DEG;+ return [+ round(distance * Math.cos(p) * Math.sin(y)),+ round(distance * Math.sin(p)),+ round(distance * Math.cos(p) * Math.cos(y)),+ ];+}++/** Half extents of the orthographic frustum for a visible ground width. */+export function orthoHalfExtents(widthM: number, aspect: number): { halfW: number; halfH: number } {+ const halfW = widthM / 2;+ return { halfW, halfH: halfW / Math.max(aspect, 1e-6) };+}++/**+ * The two ground directions the screen axes map to: `right` is screen-right,+ * `forward` is screen-up projected onto the ground (away from the camera).+ * Both are unit vectors in the xz plane, given as [x, z].+ */+export function groundBasis(yawDeg = CAMERA_YAW_DEG): { right: [number, number]; forward: [number, number] } {+ const y = yawDeg * DEG;+ return {+ right: [round(Math.cos(y)), round(-Math.sin(y))],+ forward: [round(-Math.sin(y)), round(-Math.cos(y))],+ };+}++/**+ * How far the camera target moves for a pointer drag of (dx, dy) pixels —+ * the world follows the pointer, so the target moves the other way. Vertical+ * pixels cover more ground than horizontal ones because the camera looks down+ * at `pitch`: one screen metre up is 1 / sin(pitch) metres of ground.+ */+export function dragToPan(+ dxPx: number,+ dyPx: number,+ widthM: number,+ stageWidthPx: number,+ pitchDeg = CAMERA_PITCH_DEG,+ yawDeg = CAMERA_YAW_DEG,+): [number, number] {+ if (stageWidthPx <= 0) return [0, 0];+ const mpp = widthM / stageWidthPx;+ const { right, forward } = groundBasis(yawDeg);+ const along = -dxPx * mpp;+ const ahead = (dyPx * mpp) / Math.sin(pitchDeg * DEG);+ return [round(along * right[0] + ahead * forward[0]), round(along * right[1] + ahead * forward[1])];+}++/** Keep the target on the island (with a small margin of sea). */+export function clampTarget(x: number, z: number, half = ISLAND_HALF_M): [number, number] {+ return [Math.min(half, Math.max(-half, x)), Math.min(half, Math.max(-half, z))];+}++export function stepZoom(level: ZoomLevel, direction: 1 | -1): ZoomLevel {+ const next = Math.min(ZOOM_WIDTHS_M.length - 1, Math.max(0, level + direction));+ return next as ZoomLevel;+}++/**+ * The four ground corners the viewport covers around `target`, in screen+ * order (top-left, top-right, bottom-right, bottom-left). Used by the minimap+ * to draw the viewport as a rotated rectangle.+ */+export function visibleGroundCorners(+ target: [number, number],+ widthM: number,+ aspect: number,+ pitchDeg = CAMERA_PITCH_DEG,+ yawDeg = CAMERA_YAW_DEG,+): Array<[number, number]> {+ const { right, forward } = groundBasis(yawDeg);+ const { halfW, halfH } = orthoHalfExtents(widthM, aspect);+ const depth = halfH / Math.sin(pitchDeg * DEG);+ const corner = (sx: number, sz: number): [number, number] => [+ round(target[0] + sx * halfW * right[0] + sz * depth * forward[0]),+ round(target[1] + sx * halfW * right[1] + sz * depth * forward[1]),+ ];+ return [corner(-1, 1), corner(1, 1), corner(1, -1), corner(-1, -1)];+}++/** Exponential follow factor for one frame of `dt` seconds at `rate` per second. */+export function followAlpha(dt: number, rate: number): number {+ return 1 - Math.exp(-rate * Math.max(0, dt));+}++function round(v: number): number {+ return Math.round(v * 1e6) / 1e6;+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldMaterials.ts b/jarvis/ui/web/frontend/src/components/society/world/worldMaterials.tsnew file mode 100644index 0000000000..68cc0bca92--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/worldMaterials.ts@@ -0,0 +1,106 @@+/**+ * Shared materials and geometries for everything built from primitives.+ * One Lambert material per palette colour (flat, chunky lighting — never PBR+ * on a 16-colour world, character-pipeline.md §9.3), created once per stage+ * mount and disposed with it.+ */+import { useEffect, useMemo } from "react";+import {+ BoxGeometry,+ Color,+ CylinderGeometry,+ IcosahedronGeometry,+ MeshBasicMaterial,+ MeshLambertMaterial,+ SphereGeometry,+ TorusGeometry,+} from "three";++import { BUILDING, NATURE } from "./worldPalette";++export interface WorldMaterials {+ lit: (hex: string) => MeshLambertMaterial;+ glow: (hex: string) => MeshBasicMaterial;+ dispose: () => void;+}++/** Build the material cache. Every colour is created at most once. */+export function createWorldMaterials(): WorldMaterials {+ const lit = new Map<string, MeshLambertMaterial>();+ const glow = new Map<string, MeshBasicMaterial>();+ return {+ lit: (hex) => {+ let m = lit.get(hex);+ if (!m) {+ m = new MeshLambertMaterial({ color: new Color(hex) });+ lit.set(hex, m);+ }+ return m;+ },+ glow: (hex) => {+ let m = glow.get(hex);+ if (!m) {+ m = new MeshBasicMaterial({ color: new Color(hex) });+ glow.set(hex, m);+ }+ return m;+ },+ dispose: () => {+ for (const m of lit.values()) m.dispose();+ for (const m of glow.values()) m.dispose();+ lit.clear();+ glow.clear();+ },+ };+}++export function useWorldMaterials(): WorldMaterials {+ const materials = useMemo(createWorldMaterials, []);+ useEffect(() => () => materials.dispose(), [materials]);+ return materials;+}++/** Unit geometries, scaled per use. Shared by every house, tree and lamp. */+export interface WorldGeometries {+ box: BoxGeometry;+ cylinder: CylinderGeometry;+ halfCylinder: CylinderGeometry;+ cone: CylinderGeometry;+ blob: IcosahedronGeometry;+ sphere: SphereGeometry;+ dome: SphereGeometry;+ ring: TorusGeometry;+ dispose: () => void;+}++export function createWorldGeometries(): WorldGeometries {+ const box = new BoxGeometry(1, 1, 1);+ const cylinder = new CylinderGeometry(0.5, 0.5, 1, 10);+ const halfCylinder = new CylinderGeometry(0.5, 0.5, 1, 10, 1, false, 0, Math.PI);+ const cone = new CylinderGeometry(0, 0.5, 1, 8);+ const blob = new IcosahedronGeometry(0.5, 0); // 20 faces: chunky canopies under the pixel pass+ const sphere = new SphereGeometry(0.5, 10, 8);+ const dome = new SphereGeometry(0.5, 12, 6, 0, Math.PI * 2, 0, Math.PI / 2);+ const ring = new TorusGeometry(0.5, 0.06, 6, 24);+ const all = [box, cylinder, halfCylinder, cone, blob, sphere, dome, ring];+ return {+ box,+ cylinder,+ halfCylinder,+ cone,+ blob,+ sphere,+ dome,+ ring,+ dispose: () => all.forEach((g) => g.dispose()),+ };+}++export function useWorldGeometries(): WorldGeometries {+ const geometries = useMemo(createWorldGeometries, []);+ useEffect(() => () => geometries.dispose(), [geometries]);+ return geometries;+}++/** The palette entries most components reach for, re-exported for brevity. */+export const PAL = { ...BUILDING, ...NATURE };diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldPalette.ts b/jarvis/ui/web/frontend/src/components/society/world/worldPalette.tsnew file mode 100644index 0000000000..b397e01c55--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/worldPalette.ts@@ -0,0 +1,105 @@+/**+ * The world's OWN palette — MASTERPLAN §4.3: the island is a game inside the+ * app and never wears Ink & Paper. Every colour rendered inside the viewport+ * comes from here; the surrounding chrome keeps the app's theme tokens.+ *+ * Direction (maintainer, 2026-09-01, docs/agent-society/world-art-direction.md):+ * a bright pixel island in the warm light of a late afternoon — saturated,+ * friendly greens and blues, warm sand and stone — with a SOLARPUNK village on+ * it: white walls, glass, solar barrels, garden roofs, wood accents. Two+ * shades per terrain kind give the tile-art flicker under the pixel pass.+ */+import { TileKind } from "./islandLayout";++export interface TileShades {+ /** The two top shades a tile alternates between. */+ top: [string, string];+ /** The cliff/side face colour where the tile steps down. */+ side: string;+}++export const TILE_COLORS: Record<TileKind, TileShades> = {+ [TileKind.water]: { top: ["#3d8fd1", "#3d8fd1"], side: "#2c6fa8" },+ [TileKind.sand]: { top: ["#f3e2ad", "#ead597"], side: "#d5bf86" },+ [TileKind.grass]: { top: ["#7ccb5c", "#6fbe51"], side: "#8e6a44" },+ [TileKind.meadow]: { top: ["#97d46c", "#8ac860"], side: "#8e6a44" },+ [TileKind.rock]: { top: ["#a8a7b3", "#9a99a6"], side: "#6f6e7c" },+ [TileKind.plaza]: { top: ["#ece1cf", "#e2d5c0"], side: "#b8a58a" },+ [TileKind.path]: { top: ["#dcc9a5", "#d0bd97"], side: "#a48c66" },+ [TileKind.garden]: { top: ["#b7dc6a", "#e18db1"], side: "#8e6a44" },+ [TileKind.dock]: { top: ["#b6853f", "#a87634"], side: "#7d5623" },+};++/** Water: the animated surface and its pixel highlights. */+export const WATER = {+ deep: "#2f7fc4",+ surface: "#44a0dd",+ ripple: "#8fd0f4",+ foam: "#d9f2ff",+};++/** Sky and light. NoToneMapping keeps these exact. */+export const SKY = {+ clear: "#a5dbff",+ hemiSky: "#d6ecff",+ hemiGround: "#7f9c5a",+ sun: "#fff1d6",+ sunIntensity: 1.35,+ hemiIntensity: 0.95,+ /** Direction the sun shines FROM (unit-ish vector; warm afternoon, south-west). */+ sunFrom: [-60, 90, 45] as const,+};++/** The solarpunk village. */+export const BUILDING = {+ wall: "#f7f3ea",+ wallShade: "#e6e0d2",+ trim: "#c9c2b2",+ glass: "#8ed2f0",+ glassEmissive: "#4fa8d6",+ solar: "#26375a",+ solarLine: "#3e5f95",+ gardenRoof: "#6fbf55",+ gardenRoofBush: "#4c9c3d",+ wood: "#b57f45",+ woodDark: "#8c5e2f",+ door: "#e0893b",+ hubAccent: "#2f6f8f",+ hubGlass: "#bfe7ff",+ beacon: "#ffe08a",+ beaconCore: "#fff6d5",+ workshopRoof: "#d86a4a",+ archiveDome: "#5aa7c8",+ lighthouseStripe: "#e05a5a",+ metal: "#8b8f9c",+};++export const NATURE = {+ trunk: "#7a5230",+ canopyA: "#4faf49",+ canopyB: "#6cc35e",+ canopyLight: "#93da7c",+ bigCanopy: "#57b84f",+ bigCanopyLight: "#8fdc7a",+ hedge: "#3f8f3f",+ hedgeLight: "#57a94f",+ flower: "#ef8fb6",+ lampPost: "#5c5f6a",+ lampLight: "#ffe9b0",+ tableWood: "#c58d4f",+ bench: "#a9723a",+};++/** In-world labels (drawn as DOM over the canvas, in the world's own type). */+export const LABEL = {+ font: '"Pixelify Sans", "Space Grotesk", ui-sans-serif, sans-serif',+ ink: "#1f2a3a",+ chip: "rgba(255, 252, 245, 0.88)",+ chipRim: "rgba(31, 42, 58, 0.18)",+ shadow: "rgba(31, 42, 58, 0.35)",+};++/** Colours for the 2D minimap, one per tile kind (top shade 0). */+export function minimapColor(kind: TileKind): string {+ return TILE_COLORS[kind].top[0];+}diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.tsindex 4dbfa8ba06..d215368fbd 100644--- a/jarvis/ui/web/frontend/src/i18n/index.ts+++ b/jarvis/ui/web/frontend/src/i18n/index.ts@@ -79,7 +79,7 @@ const RESOURCES: Record<UiLanguage, Record<string, unknown>> = {* it mounts. Until the chunk has arrived, `t()` returns the key, so a view* that cares waits for `ready` before it paints.*/-export type LocaleChunk = "marketplace" | "local_models";+export type LocaleChunk = "marketplace" | "local_models" | "society";const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknown>>> = {marketplace: {@@ -92,6 +92,11 @@ const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknowde: () => import("./locales/local_models/de.json"),es: () => import("./locales/local_models/es.json"),},+ society: {+ en: () => import("./locales/society/en.json"),+ de: () => import("./locales/society/de.json"),+ es: () => import("./locales/society/es.json"),+ },};const EXTRA: Record<UiLanguage, Record<string, unknown>[]> = { en: [], de: [], es: [] };diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonnew file mode 100644index 0000000000..94721764b8--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -0,0 +1,30 @@+{+ "society": {+ "world": {+ "mode_label": "Agenten-Ansicht",+ "mode_world": "Welt",+ "mode_ledger": "Ledger",+ "hud_agents": "{count} Agenten",+ "hud_active": "{count} aktiv",+ "sample_badge": "Beispiel-Roster",+ "reduced_motion_note": "Reduzierte Bewegung: die Insel steht still",+ "controls_hint": "Ziehen zum Schwenken · Scrollen zum Zoomen · Pfeiltasten zum Bewegen",+ "zoom_label": "Zoom",+ "zoom_in": "Hineinzoomen",+ "zoom_out": "Herauszoomen",+ "minimap_label": "Inselkarte – klicken, um dorthin zu springen",+ "webgl_missing_title": "Die Insel braucht WebGL",+ "webgl_missing_body": "Dieses Fenster kann gerade kein 3D zeichnen. Das Ledger zeigt dieselben Agenten.",+ "open_ledger": "Ledger öffnen",+ "loading": "Die Insel wird gebaut…",+ "place_market": "Marktplatz",+ "place_hub": "Jarvis-Hub",+ "place_workshop": "Werkstatt",+ "place_archive": "Archiv",+ "place_harbor": "Hafentor",+ "place_lighthouse": "Leuchtturm",+ "place_gardens": "Gärten",+ "place_solar": "Solarfeld"+ }+ }+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonnew file mode 100644index 0000000000..0e42243870--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -0,0 +1,30 @@+{+ "society": {+ "world": {+ "mode_label": "Agents view",+ "mode_world": "World",+ "mode_ledger": "Ledger",+ "hud_agents": "{count} agents",+ "hud_active": "{count} active",+ "sample_badge": "Sample roster",+ "reduced_motion_note": "Reduced motion: the island holds still",+ "controls_hint": "Drag to pan · Scroll to zoom · Arrow keys to move",+ "zoom_label": "Zoom",+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "minimap_label": "Island map — click to jump there",+ "webgl_missing_title": "The island needs WebGL",+ "webgl_missing_body": "This window cannot draw 3D right now. The ledger lists the same agents.",+ "open_ledger": "Open the ledger",+ "loading": "Building the island…",+ "place_market": "Market Square",+ "place_hub": "Jarvis Hub",+ "place_workshop": "Workshop",+ "place_archive": "Archive",+ "place_harbor": "Harbor Gate",+ "place_lighthouse": "Lighthouse",+ "place_gardens": "Gardens",+ "place_solar": "Solar Field"+ }+ }+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonnew file mode 100644index 0000000000..010daa8f58--- /dev/null+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -0,0 +1,30 @@+{+ "society": {+ "world": {+ "mode_label": "Vista de agentes",+ "mode_world": "Mundo",+ "mode_ledger": "Registro",+ "hud_agents": "{count} agentes",+ "hud_active": "{count} activos",+ "sample_badge": "Plantilla de ejemplo",+ "reduced_motion_note": "Movimiento reducido: la isla se queda quieta",+ "controls_hint": "Arrastra para desplazar · Rueda para zoom · Flechas para moverte",+ "zoom_label": "Zoom",+ "zoom_in": "Acercar",+ "zoom_out": "Alejar",+ "minimap_label": "Mapa de la isla: haz clic para saltar allí",+ "webgl_missing_title": "La isla necesita WebGL",+ "webgl_missing_body": "Esta ventana no puede dibujar 3D ahora mismo. El registro muestra los mismos agentes.",+ "open_ledger": "Abrir el registro",+ "loading": "Construyendo la isla…",+ "place_market": "Plaza del Mercado",+ "place_hub": "Centro Jarvis",+ "place_workshop": "Taller",+ "place_archive": "Archivo",+ "place_harbor": "Puerta del Puerto",+ "place_lighthouse": "Faro",+ "place_gardens": "Jardines",+ "place_solar": "Campo Solar"+ }+ }+}diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsxindex 2f33a018d7..4c6d834416 100644--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx@@ -26,7 +26,7 @@* shared `components/extensions/primitives` so this section looks like Spend,* Skills, Plugins, MCPs and CLIs rather than like a screen of its own.*/-import { useCallback, useEffect, useMemo, useState } from "react";+import { Suspense, lazy, useCallback, useEffect, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import { useSubAgentStore, type SubAgentNode, type SubAgentTreeSnapshot } from "@/store/jarvisAgents";@@ -40,10 +40,68 @@ import { useMissionWebSocket } from "@/components/missions/useMissionWebSocket";import { useMissionsStore } from "@/components/missions/store";import { useOutputsList } from "@/hooks/useOutputs";import { useSectionHealth } from "@/hooks/useProviders";+import { SegmentedFilter } from "@/components/extensions/primitives";+import { useLocaleChunk, useT } from "@/i18n";+import { detectWebgl } from "@/lib/graphDimension";/** The query parameter the Artifacts section reads to pre-select a run. */const RUN_PARAM = "run";+/**+ * The section's two faces (MASTERPLAN §4.1): the 3D island is the face, the+ * board stays as the data-dense "Ledger" and the declared fallback wherever+ * WebGL is absent. The world is a lazy chunk — three.js and the island never+ * load for someone who only ever reads the ledger.+ */+type AgentsMode = "world" | "ledger";+const MODE_KEY = "jarvis.agents.mode";++const WorldStage = lazy(() =>+ import("@/components/society/world/WorldStage").then((m) => ({ default: m.WorldStage })),+);++function readMode(): AgentsMode {+ try {+ const raw = localStorage.getItem(MODE_KEY);+ if (raw === "world" || raw === "ledger") return raw;+ } catch {+ /* private mode: fall through to the default */+ }+ return detectWebgl() ? "world" : "ledger";+}++function writeMode(mode: AgentsMode): void {+ try {+ localStorage.setItem(MODE_KEY, mode);+ } catch {+ /* not persisted, still switched */+ }+}++function ModeSwitch({ mode, onChange }: { mode: AgentsMode; onChange: (m: AgentsMode) => void }) {+ const t = useT();+ const ready = useLocaleChunk("society");+ if (!ready) return null;+ return (+ <div className="rounded-md border border-border bg-popover p-0.5 shadow-float">+ <SegmentedFilter<AgentsMode>+ value={mode}+ onChange={onChange}+ label={t("society.world.mode_label")}+ options={[+ { id: "world", label: t("society.world.mode_world") },+ { id: "ledger", label: t("society.world.mode_ledger") },+ ]}+ />+ </div>+ );+}++/** Shown while the world chunk loads: a quiet sky-coloured block, no invented numbers. */+function WorldLoading() {+ return <div className="h-full w-full animate-pulse bg-secondary" aria-hidden />;+}+export function JarvisAgentsView() {const { health } = useSectionHealth();const subAgents = useSubAgentStore((s) => s.subAgents);@@ -54,6 +112,11 @@ export function JarvisAgentsView() {// The run whose insight page is open, by dash-stripped id. Kept as an id// rather than a node so the page follows the row through live updates.const [openTraceId, setOpenTraceId] = useState<string | null>(null);+ const [mode, setMode] = useState<AgentsMode>(readMode);+ const switchMode = useCallback((next: AgentsMode) => {+ writeMode(next);+ setMode(next);+ }, []);// One row per task: collapse each worker into its mission row so a single// dispatched task shows once (the mission "Sub-Agent" carrying the task@@ -178,6 +241,18 @@ export function JarvisAgentsView() {);}+ const modeSwitch = <ModeSwitch mode={mode} onChange={switchMode} />;++ if (mode === "world") {+ return (+ <div className="h-full min-h-0">+ <Suspense fallback={<WorldLoading />}>+ <WorldStage topRight={modeSwitch} onOpenLedger={() => switchMode("ledger")} />+ </Suspense>+ </div>+ );+ }+return (<DepartureBoardagents={nodesList}@@ -185,6 +260,7 @@ export function JarvisAgentsView() {health={health["subagents"] ?? null}historyError={historyQuery.isError}onOpen={onOpen}+ headerActions={modeSwitch}/>);}diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsxindex 1f3cbbb7b2..a3459e24c1 100644--- a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx+++ b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx@@ -19,7 +19,7 @@* The brand comes from `agentBrand`, so the board follows whatever wake word is* configured rather than a product name (see lib/agentBrand.ts).*/-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useState, type ReactNode } from "react";import { AlertTriangle, Bot, CheckCircle2, ChevronRight, CircleAlert, Radio, Wrench } from "lucide-react";import type { SubAgentNode } from "@/store/jarvisAgents";@@ -119,6 +119,8 @@ interface Props {historyError?: boolean;/** A row was clicked: open that run's insight page. */onOpen?: (agent: SubAgentNode) => void;+ /** Right-aligned controls in the header (the section's World / Ledger switch). */+ headerActions?: ReactNode;}export function DepartureBoard({@@ -127,6 +129,7 @@ export function DepartureBoard({health = null,historyError = false,onOpen,+ headerActions,}: Props) {const t = useT();const assistantName = useEventStore((s) => s.assistantName);@@ -171,6 +174,7 @@ export function DepartureBoard({active: activeCount,total: agents.length,})}+ actions={headerActions}/>{health && (health.status === "needs_setup" || health.status === "error") && (diff --git a/scripts/ci/check_webgl_contexts_released.py b/scripts/ci/check_webgl_contexts_released.pyindex d633efaa21..fe9770d4e7 100644--- a/scripts/ci/check_webgl_contexts_released.py+++ b/scripts/ci/check_webgl_contexts_released.py@@ -25,6 +25,7 @@ Static analysis only — it never runs a bundler, so it is cheap anddependency-free. Run from CI and covered by``tests/unit/ui/test_webgl_contexts_released.py``."""+from __future__ import annotationsimport argparse@@ -39,10 +40,22 @@ _FRONTEND = _REPO / "jarvis" / "ui" / "web" / "frontend" / "src"#: raw WebGL context. Type-only imports are excluded at the call site: a module#: that merely names `NodeObject` never owns a context._MOUNTS: tuple[tuple[str, re.Pattern[str]], ...] = (- ("react-force-graph-3d", re.compile(r"^\s*import\s+(?!type\b)[^\n]*react-force-graph-3d", re.M)),+ (+ "react-force-graph-3d",+ re.compile(r"^\s*import\s+(?!type\b)[^\n]*react-force-graph-3d", re.M),+ ),("new WebGLRenderer", re.compile(r"\bnew\s+(?:THREE\.)?WebGLRenderer\b")),- ("@react-three/fiber", re.compile(r"^\s*import\s+(?!type\b)[^\n]*@react-three/fiber", re.M)),- ("getContext(\"webgl\")", re.compile(r"""getContext\(\s*['"]webgl2?['"]""")),+ # Only `Canvas` mounts a renderer; a module that imports hooks (useFrame,+ # useThree) or event types renders INSIDE someone else's canvas and owns+ # no context of its own.+ (+ "@react-three/fiber Canvas",+ re.compile(+ r"^\s*import\s+(?!type\b)\{[^}]*\bCanvas\b[^}]*\}\s*from\s*['\"]@react-three/fiber",+ re.M,+ ),+ ),+ ('getContext("webgl")', re.compile(r"""getContext\(\s*['"]webgl2?['"]""")),)#: Proof that the module hands the context back. `useWebglSurface` is the