Skip to content

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.

feat(society): integrate authored city and metro workstations

rubenluetke10-beep38ebfe07bf6c
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityAssets.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityAssets.tsx
new file mode 100644
index 0000000000..efc5e9ef56
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/CityAssets.tsx
@@ -0,0 +1,290 @@
+/** Authored assets: static geometry batches, with independent moving metro parts. */
+import { memo, useEffect, useMemo, useRef } from "react";
+import { useFrame, useThree } from "@react-three/fiber";
+import { useGLTF } from "@react-three/drei";
+import {
+ Group,
+ InstancedMesh,
+ Matrix4,
+ Mesh,
+ MeshStandardMaterial,
+ Plane,
+ Quaternion,
+ Vector3,
+ type Material,
+ type Object3D,
+} from "three";
+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";
+import type { Vec3 } from "./cityModel";
+import { trainAt, type CitySimulation } from "./citySimulation";
+import { releaseCityInstances } from "./cityInstances";
+import station from "../../../../../../../../art/studies/city-realism-study/exports/station.glb";
+import terminal from "../../../../../../../../art/studies/city-realism-study/exports/building.glb";
+import central from "../../../../../../../../art/studies/city-realism-study/exports/central.glb";
+import knowledge from "../../../../../../../../art/studies/city-realism-study/exports/knowledge.glb";
+import workshop from "../../../../../../../../art/studies/city-realism-study/exports/fabrication.glb";
+import communications from "../../../../../../../../art/studies/city-realism-study/exports/communications.glb";
+import office from "../../../../../../../../art/studies/city-realism-study/exports/skyline-office.glb";
+import tower from "../../../../../../../../art/studies/city-realism-study/exports/skyline-tower.glb";
+import residence from "../../../../../../../../art/studies/city-realism-study/exports/skyline-residence.glb";
+import lamp from "../../../../../../../../art/studies/city-realism-study/exports/streetlamp.glb";
+import tree from "../../../../../../../../art/studies/city-realism-study/exports/tree.glb";
+import metro from "../../../../../../../../art/studies/city-realism-study/exports/train.glb";
+export const CITY_ASSETS = {
+ station,
+ terminal,
+ central,
+ knowledge,
+ workshop,
+ communications,
+ office,
+ tower,
+ residence,
+ lamp,
+ tree,
+ metro,
+};
+export interface InstancePose {
+ position: Vec3;
+ yaw?: number;
+ scale?: number;
+}
+
+function prepare(scene: Object3D) {
+ scene.updateMatrixWorld(true);
+ const groups = new Map<Material, Mesh[]>();
+ scene.traverse((object) => {
+ if (!(object instanceof Mesh)) return;
+ if (Array.isArray(object.material))
+ throw new Error("City GLBs must export one material per mesh primitive");
+ const meshes = groups.get(object.material) ?? [];
+ meshes.push(object);
+ groups.set(object.material, meshes);
+ });
+ return [...groups].map(([source, meshes]) => {
+ const pieces = meshes.map((mesh) =>
+ mesh.geometry.clone().applyMatrix4(mesh.matrixWorld),
+ );
+ const geometry = mergeGeometries(pieces);
+ pieces.forEach((piece) => piece.dispose());
+ if (!geometry) throw new Error("Incompatible city mesh attributes");
+ return { geometry, material: source.clone() };
+ });
+}
+export const CityAsset = memo(function CityAsset({
+ url,
+ position,
+ yaw = 0,
+ onClick,
+ working = false,
+ cutaway = false,
+}: {
+ url: string;
+ position: Vec3;
+ yaw?: number;
+ onClick?: () => void;
+ working?: boolean;
+ cutaway?: boolean;
+}) {
+ const { scene } = useGLTF(url);
+ const invalidate = useThree((state) => state.invalidate);
+ const parts = useMemo(() => prepare(scene), [scene]);
+ useEffect(
+ () => () => {
+ parts.forEach((part) => {
+ part.geometry.dispose();
+ part.material.dispose();
+ });
+ },
+ [parts],
+ );
+ useEffect(() => {
+ for (const { material } of parts)
+ if (
+ material instanceof MeshStandardMaterial &&
+ /screen/i.test(material.name)
+ )
+ material.emissiveIntensity = working ? 2 : 0.5;
+ }, [working, parts]);
+ useEffect(() => {
+ const planes = cutaway
+ ? [new Plane(new Vector3(0, -1, 0), position[1] + 4.8)]
+ : [];
+ for (const { material } of parts) {
+ material.clippingPlanes = planes;
+ material.needsUpdate = true;
+ }
+ invalidate();
+ }, [cutaway, parts, position, invalidate]);
+ return (
+ <group
+ position={position}
+ rotation={[0, yaw, 0]}
+ onClick={
+ onClick
+ ? (event) => {
+ // Raycasting sees geometry that the shader clipped away; let those hits pass through.
+ if (cutaway && event.point.y > position[1] + 4.8) return;
+ event.stopPropagation();
+ onClick();
+ }
+ : undefined
+ }
+ >
+ {parts.map((part, index) => (
+ <mesh
+ key={index}
+ geometry={part.geometry}
+ material={part.material}
+ castShadow
+ receiveShadow
+ dispose={null}
+ />
+ ))}
+ </group>
+ );
+});
+
+/** One preparation per asset family, independent instances, no copies per tree/window. */
+export const CityInstances = memo(function CityInstances({
+ url,
+ poses,
+ shadows = false,
+}: {
+ url: string;
+ poses: InstancePose[];
+ shadows?: boolean;
+}) {
+ const { scene } = useGLTF(url);
+ const parts = useMemo(() => prepare(scene), [scene]);
+ const group = useMemo(() => {
+ const result = new Group();
+ const matrix = new Matrix4();
+ const quaternion = new Quaternion();
+ const scale = new Vector3();
+ const position = new Vector3();
+ for (const part of parts) {
+ const mesh = new InstancedMesh(
+ part.geometry,
+ part.material,
+ poses.length,
+ );
+ poses.forEach((pose, i) => {
+ quaternion.setFromAxisAngle(new Vector3(0, 1, 0), pose.yaw ?? 0);
+ scale.setScalar(pose.scale ?? 1);
+ position.set(...pose.position);
+ matrix.compose(position, quaternion, scale);
+ mesh.setMatrixAt(i, matrix);
+ });
+ mesh.instanceMatrix.needsUpdate = true;
+ mesh.computeBoundingSphere();
+ mesh.castShadow = shadows;
+ mesh.receiveShadow = shadows;
+ result.add(mesh);
+ }
+ return result;
+ }, [parts, poses, shadows]);
+ useEffect(
+ () => () => {
+ group.traverse((object) => {
+ if (object instanceof InstancedMesh) releaseCityInstances(object);
+ });
+ },
+ [group],
+ );
+ useEffect(
+ () => () => {
+ parts.forEach((part) => {
+ part.geometry.dispose();
+ part.material.dispose();
+ });
+ },
+ [parts],
+ );
+ return <primitive object={group} dispose={null} />;
+});
+
+export function Metro({
+ sim,
+ paused,
+ follow,
+}: {
+ sim: CitySimulation;
+ paused: boolean;
+ follow: string | null;
+}) {
+ const { scene } = useGLTF(metro);
+ const root = useRef<Group>(null);
+ const clone = useMemo(() => {
+ const object = scene.clone(true);
+ const materials = new Map<Material, Material>();
+ object.traverse((child) => {
+ if (!(child instanceof Mesh)) return;
+ const original = child.material as Material;
+ if (!materials.has(original)) {
+ const material = original.clone();
+ if (
+ material instanceof MeshStandardMaterial &&
+ material.name === "Glazing"
+ ) {
+ material.transparent = true;
+ material.opacity = 0.42;
+ material.depthWrite = false;
+ }
+ materials.set(original, material);
+ }
+ child.material = materials.get(original)!;
+ });
+ return object;
+ }, [scene]);
+ useEffect(
+ () => () => {
+ const materials = new Set<Material>();
+ clone.traverse((child) => {
+ if (child instanceof Mesh) materials.add(child.material as Material);
+ });
+ materials.forEach((m) => m.dispose());
+ },
+ [clone],
+ );
+ const doors = useMemo(
+ () =>
+ ["Door_Platform_Left", "Door_Platform_Right"]
+ .map((name, i) => {
+ const object = clone.getObjectByName(name);
+ return object
+ ? { object, x: object.position.x, sign: i ? 1 : -1 }
+ : null;
+ })
+ .filter((door): door is NonNullable<typeof door> => door !== null),
+ [clone],
+ );
+ const opening = useRef(trainAt(sim.time).doorsOpen ? 1 : 0);
+ const interior = useRef(false);
+ const plane = useMemo(() => new Plane(new Vector3(0, -1, 0), 14.5), []);
+ useFrame((_, dt) => {
+ const state = trainAt(sim.time);
+ const passenger = follow ? sim.citizens.get(follow) : null;
+ const inspect = passenger?.seat !== null && passenger?.seat !== undefined;
+ if (inspect !== interior.current) {
+ interior.current = inspect;
+ clone.traverse((object) => { if (object instanceof Mesh) { const material = object.material as Material; material.clippingPlanes = inspect ? [plane] : []; material.needsUpdate = true; } });
+ }
+ if (root.current) {
+ root.current.position.set(...state.position);
+ root.current.rotation.y = state.heading;
+ }
+ const target = state.doorsOpen ? 1 : 0;
+ if (!paused)
+ opening.current +=
+ Math.sign(target - opening.current) *
+ Math.min(Math.abs(target - opening.current), dt * 3);
+ for (const door of doors)
+ door.object.position.x = door.x + door.sign * opening.current * 1.25;
+ });
+ return (
+ <group ref={root}>
+ <primitive object={clone} dispose={null} />
+ </group>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityEnvironment.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityEnvironment.tsx
new file mode 100644
index 0000000000..ff0229157a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/CityEnvironment.tsx
@@ -0,0 +1,315 @@
+/** A continuous urban setting assembled from individually reviewed Blender modules. */
+import { memo, useEffect, useMemo } from "react";
+import { Html } from "@react-three/drei";
+import {
+ BoxGeometry,
+ Color,
+ InstancedMesh,
+ Matrix4,
+ MeshStandardMaterial,
+ Quaternion,
+ Vector3,
+} from "three";
+import { useT } from "@/i18n";
+import { releaseCityInstances } from "./cityInstances";
+import {
+ CITY_ASSETS,
+ CityAsset,
+ CityInstances,
+ type InstancePose,
+} from "./CityAssets";
+import {
+ DISTRICTS,
+ LIFTS,
+ MATERIALS,
+ RAIL_POINTS,
+ graphWalkways,
+ transformPoint,
+ type Placements,
+ type RouteGraph,
+ type Stop,
+ type Vec3,
+} from "./cityModel";
+
+interface BoxPose extends InstancePose {
+ size: Vec3;
+ color?: string;
+}
+const UP = new Vector3(0, 1, 0);
+function Boxes({
+ poses,
+ color,
+ shadows = false,
+}: {
+ poses: BoxPose[];
+ color: string;
+ shadows?: boolean;
+}) {
+ const mesh = useMemo(() => {
+ const geometry = new BoxGeometry(1, 1, 1);
+ const material = new MeshStandardMaterial({ color, roughness: 0.82 });
+ const result = new InstancedMesh(geometry, material, poses.length);
+ const matrix = new Matrix4(),
+ position = new Vector3(),
+ rotation = new Quaternion(),
+ scale = new Vector3();
+ poses.forEach((pose, index) => {
+ matrix.compose(
+ position.set(...pose.position),
+ rotation.setFromAxisAngle(UP, pose.yaw ?? 0),
+ scale.set(...pose.size),
+ );
+ result.setMatrixAt(index, matrix);
+ if (pose.color) result.setColorAt(index, new Color(pose.color));
+ });
+ result.instanceMatrix.needsUpdate = true;
+ result.computeBoundingSphere();
+ result.castShadow = shadows;
+ result.receiveShadow = true;
+ return result;
+ }, [poses, color, shadows]);
+ useEffect(
+ () => () => {
+ mesh.geometry.dispose();
+ (mesh.material as MeshStandardMaterial).dispose();
+ releaseCityInstances(mesh);
+ },
+ [mesh],
+ );
+ return <primitive object={mesh} dispose={null} />;
+}
+function segment(
+ a: Vec3,
+ b: Vec3,
+ width: number,
+ thickness: number,
+ lower = 0,
+): BoxPose {
+ return {
+ position: [
+ (a[0] + b[0]) / 2,
+ (a[1] + b[1]) / 2 - thickness / 2 - lower,
+ (a[2] + b[2]) / 2,
+ ],
+ size: [Math.hypot(b[0] - a[0], b[2] - a[2]) + 0.25, thickness, width],
+ yaw: -Math.atan2(b[2] - a[2], b[0] - a[0]),
+ };
+}
+function hash(x: number, z: number): number {
+ const value = Math.sin(x * 127.1 + z * 311.7) * 43758.5453;
+ return value - Math.floor(value);
+}
+const stationPoses: InstancePose[] = DISTRICTS.map((d) => ({
+ position: [d.stationPosition[0], 12.08, d.stationPosition[2]],
+ yaw: d.stationYaw,
+}));
+const dressing = (() => {
+ const offices: InstancePose[] = [],
+ towers: InstancePose[] = [],
+ residences: InstancePose[] = [],
+ trees: InstancePose[] = [],
+ lamps: InstancePose[] = [],
+ far: BoxPose[] = [],
+ roads: BoxPose[] = [];
+ // Streets continue beyond the operational boundary, with a cheap distant silhouette.
+ for (let x = -3000; x <= 3000; x += 240)
+ roads.push({ position: [x, -0.12, 0], size: [18, 0.18, 6500] });
+ for (let z = -3000; z <= 3000; z += 240)
+ roads.push({ position: [0, -0.12, z], size: [6500, 0.18, 18] });
+ for (let x = -2700; x <= 2700; x += 90)
+ for (let z = -2250; z <= 2250; z += 90) {
+ if (Math.abs(x % 240) < 25 || Math.abs(z % 240) < 25) continue;
+ const onRing =
+ Math.abs((x / 500) ** 2 + ((z + 110) / 280) ** 2 - 1) < 0.48;
+ if (
+ onRing ||
+ DISTRICTS.some((d) => Math.hypot(x - d.x, z - d.z) < 108) ||
+ (Math.abs(x) < 45 && z > 20 && z < 320)
+ )
+ continue;
+ const choice = hash(x, z),
+ scale = 0.7 + hash(z, x) * 0.5;
+ const pose: InstancePose = {
+ position: [x + choice * 16, -0.15, z + choice * 10],
+ yaw: choice > 0.5 ? Math.PI / 2 : 0,
+ scale,
+ };
+ // The authored skyline kit is already only 288–636 triangles per model.
+ // Reuse it into the distance instead of a visible wall of unrelated boxes.
+ (choice < 0.35 ? offices : choice < 0.65 ? towers : residences).push(pose);
+ }
+ for (const d of DISTRICTS) {
+ for (const side of [-1, 1])
+ for (let z = 26; z < 132; z += 14) {
+ trees.push({
+ position: transformPoint(
+ [d.stationPosition[0], 0, d.stationPosition[2]],
+ d.stationYaw,
+ [side * 38, 0, z],
+ ),
+ scale: 0.8 + hash(z, side) * 0.35,
+ });
+ if (z % 28 === 12)
+ lamps.push({
+ position: transformPoint(
+ [d.stationPosition[0], 0, d.stationPosition[2]],
+ d.stationYaw,
+ [side * 25, 0, z],
+ ),
+ yaw: d.stationYaw,
+ });
+ }
+ }
+ return { offices, towers, residences, trees, lamps, far, roads };
+})();
+const infrastructure = (() => {
+ const decks: BoxPose[] = [],
+ rails: BoxPose[] = [],
+ pillars: BoxPose[] = [];
+ RAIL_POINTS.slice(1).forEach((b, index) => {
+ const a = RAIL_POINTS[index];
+ decks.push(segment(a, b, 6.4, 0.7, 1.5));
+ const dx = b[0] - a[0],
+ dz = b[2] - a[2],
+ length = Math.hypot(dx, dz);
+ for (const side of [-1, 1]) {
+ const offsetX = (-dz / length) * side * 1.65,
+ offsetZ = (dx / length) * side * 1.65;
+ rails.push(
+ segment(
+ [a[0] + offsetX, 10.88, a[2] + offsetZ],
+ [b[0] + offsetX, 10.88, b[2] + offsetZ],
+ 0.14,
+ 0.15,
+ ),
+ );
+ }
+ if (index % 8 === 0)
+ pillars.push({ position: [a[0], 5, a[2]], size: [1.4, 10, 1.4] });
+ });
+ return { decks, rails, pillars };
+})();
+export const CityEnvironment = memo(function CityEnvironment({
+ graph,
+ placements,
+ activeStops,
+ onSelect,
+ interiorStop,
+}: {
+ graph: RouteGraph;
+ placements: Placements;
+ activeStops: Set<Stop>;
+ onSelect: (stop: Stop) => void;
+ interiorStop: Stop | null;
+}) {
+ const t = useT();
+ const paths = useMemo(
+ () =>
+ graphWalkways(graph).map((way) => segment(way.a, way.b, way.width, 0.18)),
+ [graph],
+ );
+ const safetyRails = useMemo(
+ () =>
+ graphWalkways(graph)
+ .filter((way) => way.layer === "bridge")
+ .flatMap((way) => {
+ const dx = way.b[0] - way.a[0],
+ dz = way.b[2] - way.a[2],
+ length = Math.hypot(dx, dz);
+ return [-1, 1].map((side) => {
+ const x = ((-dz / length) * side * way.width) / 2,
+ z = ((dx / length) * side * way.width) / 2;
+ return segment(
+ [way.a[0] + x, way.a[1] + 1.2, way.a[2] + z],
+ [way.b[0] + x, way.b[1] + 1.2, way.b[2] + z],
+ 0.12,
+ 0.12,
+ );
+ });
+ }),
+ [graph],
+ );
+ const plazas = useMemo(
+ () =>
+ DISTRICTS.map((d): BoxPose => ({
+ position: transformPoint(
+ [d.stationPosition[0], 0, d.stationPosition[2]],
+ d.stationYaw,
+ [0, -0.25, 73],
+ ),
+ size: [96, 0.3, 132],
+ yaw: d.stationYaw,
+ })),
+ [],
+ );
+ return (
+ <>
+ <mesh
+ rotation={[-Math.PI / 2, 0, 0]}
+ position={[0, -0.35, 0]}
+ receiveShadow
+ >
+ <planeGeometry args={[18000, 18000]} />
+ <meshStandardMaterial color="#819085" roughness={1} />
+ </mesh>
+ <Boxes poses={dressing.roads} color="#3d4c53" />
+ <Boxes poses={dressing.far} color="#65737b" />
+ <CityInstances url={CITY_ASSETS.office} poses={dressing.offices} />
+ <CityInstances url={CITY_ASSETS.tower} poses={dressing.towers} />
+ <CityInstances url={CITY_ASSETS.residence} poses={dressing.residences} />
+ <CityInstances url={CITY_ASSETS.tree} poses={dressing.trees} />
+ <CityInstances url={CITY_ASSETS.lamp} poses={dressing.lamps} />
+ <Boxes poses={plazas} color={MATERIALS.concrete} />
+ <Boxes poses={paths} color="#c3c8bf" />
+ <Boxes poses={safetyRails} color={MATERIALS.metal} />
+ <Boxes poses={infrastructure.decks} color={MATERIALS.graphite} />
+ <Boxes poses={infrastructure.rails} color={MATERIALS.metal} />
+ <Boxes
+ poses={infrastructure.pillars}
+ color={MATERIALS.concrete}
+ shadows
+ />
+ <CityInstances url={CITY_ASSETS.station} poses={stationPoses} shadows />
+ {LIFTS.map((lift) => (
+ <group key={lift.id} position={lift.a}>
+ <mesh position={[0, (lift.b[1] - lift.a[1]) / 2, 0]}>
+ <boxGeometry args={[5, lift.b[1] - lift.a[1], 5]} />
+ <meshStandardMaterial
+ color="#8ab3c5"
+ transparent
+ opacity={0.12}
+ depthWrite={false}
+ roughness={0.2}
+ />
+ </mesh>
+ <mesh position={[0, lift.b[1] - lift.a[1] - 0.15, 0]}>
+ <boxGeometry args={[5.5, 0.3, 5.5]} />
+ <meshStandardMaterial color={MATERIALS.metal} />
+ </mesh>
+ </group>
+ ))}
+ {DISTRICTS.map((d) => (
+ <group key={d.stop}>
+ <CityAsset
+ url={CITY_ASSETS[d.id]}
+ position={placements[d.stop]}
+ yaw={d.buildingRotation}
+ working={activeStops.has(d.stop)}
+ cutaway={interiorStop === d.stop}
+ onClick={() => onSelect(d.stop)}
+ />
+ <Html
+ position={[d.stationPosition[0], 24, d.stationPosition[2]]}
+ zIndexRange={[1, 0]}
+ center
+ style={{ pointerEvents: "none" }}
+ >
+ <span className="whitespace-nowrap rounded border border-border bg-popover/95 px-2 py-1 text-xs text-popover-foreground">
+ {t(d.labelKey)}
+ </span>
+ </Html>
+ </group>
+ ))}
+ </>
+ );
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityRuntime.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityRuntime.tsx
new file mode 100644
index 0000000000..6c00445f1a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/CityRuntime.tsx
@@ -0,0 +1,326 @@
+import {
+ memo,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type MutableRefObject,
+} from "react";
+import { useFrame, useThree } from "@react-three/fiber";
+import { Html, OrbitControls, useGLTF } from "@react-three/drei";
+import {
+ AnimationMixer,
+ Color,
+ Fog,
+ Group,
+ Mesh,
+ PMREMGenerator,
+ Vector3,
+ type DirectionalLight,
+ type HemisphereLight,
+} from "three";
+import type { OrbitControls as OrbitControlsType } from "three-stdlib";
+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+import { FigureRig, type FigureDrive } from "../figures/FigureRig";
+import type { FigureRecipe } from "../figures/figureRecipe";
+import { CAMERA_BOUNDS, type Vec3 } from "./cityModel";
+import { daylight, type Citizen, type CitySimulation } from "./citySimulation";
+import { tickCityClock, type CityClock } from "./cityClock";
+import { Metro } from "./CityAssets";
+import citizenUrl from "../../../../../../../../art/studies/city-realism-study/exports/citizen.glb";
+
+export interface CityActor {
+ id: string;
+ label: string;
+ recipe?: FigureRecipe | null;
+ checkpoint: string;
+ state: string;
+}
+export interface CityMetrics {
+ fps: number;
+ calls: number;
+ triangles: number;
+ geometries: number;
+ textures: number;
+}
+export interface CameraFocus {
+ position: Vec3;
+ distance: number;
+ yaw: number;
+ key: number;
+}
+export const OVERVIEW: CameraFocus = {
+ position: [0, 0, -60],
+ distance: 950,
+ yaw: 0.65,
+ key: 0,
+};
+function ReferenceCitizen({
+ citizen,
+ paused,
+}: {
+ citizen: Citizen;
+ paused: boolean;
+}) {
+ const { scene, animations } = useGLTF(citizenUrl);
+ const clone = useMemo(() => scene.clone(true), [scene]);
+ const mixer = useMemo(() => new AnimationMixer(clone), [clone]);
+ const moving = useRef(false);
+ const phase = useRef(0);
+ useEffect(() => {
+ for (const clip of animations) mixer.clipAction(clip).play();
+ return () => {
+ mixer.stopAllAction();
+ mixer.uncacheRoot(clone);
+ };
+ }, [animations, clone, mixer]);
+ useFrame((_, dt) => {
+ const walking = !paused && citizen.speed > 0;
+ if (walking) mixer.update((Math.min(dt, 0.1) * citizen.speed) / 1.28);
+ else if (moving.current) mixer.setTime(0);
+ moving.current = walking;
+ const working = citizen.atWork && citizen.taskActive && !paused;
+ if (!paused) phase.current += Math.min(dt, 0.1);
+ for (const [index, side] of ["L", "R"].entries()) {
+ const arm = clone.getObjectByName(`Arm_${side}`),
+ forearm = clone.getObjectByName(`Forearm_${side}`);
+ if (arm) arm.rotation.x = working ? -0.45 : 0;
+ if (forearm)
+ forearm.rotation.x = working
+ ? -1.1 + Math.sin(phase.current * 8 + index * Math.PI) * 0.07
+ : 0;
+ }
+ });
+ return <primitive object={clone} dispose={null} />;
+}
+export const MovingActor = memo(function MovingActor({
+ actor,
+ sim,
+ paused,
+ selected,
+ onSelect,
+}: {
+ actor: CityActor;
+ sim: CitySimulation;
+ paused: boolean;
+ selected: boolean;
+ onSelect: (id: string) => void;
+}) {
+ const root = useRef<Group>(null),
+ body = useRef<Group>(null),
+ distant = useRef<Mesh>(null);
+ const nearRef = useRef(true);
+ const [near, setNear] = useState(true);
+ const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });
+ const citizen = sim.citizens.get(actor.id);
+ useFrame(({ camera }) => {
+ if (!root.current || !citizen) return;
+ root.current.position.set(...citizen.position);
+ root.current.rotation.y = citizen.heading;
+ const detail =
+ selected || camera.position.distanceTo(root.current.position) < 100;
+ if (detail !== nearRef.current) {
+ nearRef.current = detail;
+ setNear(detail);
+ }
+ if (body.current) body.current.visible = detail;
+ if (distant.current) distant.current.visible = !detail;
+ drive.current.mode =
+ citizen.speed > 0
+ ? "walk"
+ : citizen.atWork && citizen.taskActive
+ ? "work"
+ : "idle";
+ drive.current.speed = citizen.speed;
+ });
+ if (!citizen) return null;
+ return (
+ <group
+ ref={root}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect(actor.id);
+ }}
+ >
+ <group ref={body}>
+ {actor.recipe ? (
+ <FigureRig
+ recipe={actor.recipe}
+ drive={drive}
+ paused={paused || !near}
+ />
+ ) : (
+ <ReferenceCitizen citizen={citizen} paused={paused || !near} />
+ )}
+ </group>
+ <mesh ref={distant} position={[0, 0.85, 0]} visible={false}>
+ <capsuleGeometry args={[0.24, 1.2, 3, 6]} />
+ <meshStandardMaterial color="#5595a4" roughness={0.8} />
+ </mesh>
+ {selected && (
+ <>
+ <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.025, 0]}>
+ <ringGeometry args={[0.65, 0.82, 24]} />
+ <meshBasicMaterial color="#ebc772" />
+ </mesh>
+ <Html
+ position={[0, 2.4, 0]}
+ center
+ zIndexRange={[1, 0]}
+ style={{ pointerEvents: "none" }}
+ >
+ <span className="whitespace-nowrap rounded border border-border bg-popover px-2 py-1 text-xs text-popover-foreground">
+ {actor.label}
+ </span>
+ </Html>
+ </>
+ )}
+ </group>
+ );
+});
+
+export const CityRuntime = memo(function CityRuntime({
+ sim,
+ clock,
+ paused,
+ focus,
+ follow,
+ metrics,
+ requestFrame,
+}: {
+ sim: CitySimulation;
+ clock: CityClock;
+ paused: boolean;
+ focus: CameraFocus;
+ follow: string | null;
+ metrics: MutableRefObject<CityMetrics>;
+ requestFrame: MutableRefObject<() => void>;
+}) {
+ const sun = useRef<DirectionalLight>(null),
+ sky = useRef<HemisphereLight>(null),
+ controls = useRef<OrbitControlsType>(null);
+ const { scene, camera, gl, invalidate } = useThree();
+ const samples = useRef({ seconds: 0, frames: 0 });
+ const light = useMemo(
+ () => ({
+ night: new Color("#182b3c"),
+ day: new Color("#a6beca"),
+ background: new Color(),
+ target: new Vector3(),
+ delta: new Vector3(),
+ }),
+ [],
+ );
+ useEffect(() => {
+ requestFrame.current = invalidate;
+ gl.localClippingEnabled = true;
+ const room = new RoomEnvironment(),
+ generator = new PMREMGenerator(gl),
+ target = generator.fromScene(room, 0.04);
+ scene.environment = target.texture;
+ scene.fog = new Fog("#a6beca", 1100, 4400);
+ room.dispose();
+ generator.dispose();
+ invalidate();
+ return () => {
+ scene.environment = null;
+ scene.fog = null;
+ target.dispose();
+ requestFrame.current = () => undefined;
+ };
+ }, [gl, scene, invalidate, requestFrame]);
+ useEffect(() => {
+ if (!controls.current) return;
+ const [x, y, z] = focus.position;
+ controls.current.target.set(x, y, z);
+ camera.position.set(
+ x + Math.sin(focus.yaw) * focus.distance,
+ y + focus.distance * 0.6,
+ z + Math.cos(focus.yaw) * focus.distance,
+ );
+ controls.current.update();
+ invalidate();
+ }, [focus, camera, invalidate]);
+ useEffect(() => {
+ const citizen = follow ? sim.citizens.get(follow) : null;
+ if (!citizen || !controls.current) return;
+ const [x, y, z] = citizen.position;
+ controls.current.target.set(x, y + 1, z);
+ camera.position.set(x + 12, y + 9, z - 16);
+ controls.current.update();
+ invalidate();
+ }, [follow, camera, sim, invalidate]);
+ useFrame((_, dt) => {
+ tickCityClock(clock, sim, performance.now(), paused);
+ const strength = daylight(clock.hour);
+ light.background.copy(light.night).lerp(light.day, strength);
+ scene.background = light.background;
+ if (scene.fog instanceof Fog) scene.fog.color.copy(light.background);
+ scene.environmentIntensity = 0.25 + strength * 0.6;
+ if (sky.current) sky.current.intensity = 0.7 + strength * 1.1;
+ if (sun.current) {
+ sun.current.intensity = 0.2 + strength * 2.1;
+ sun.current.position.set(
+ Math.cos((clock.hour / 24) * Math.PI * 2) * 350,
+ 160 + strength * 250,
+ 240,
+ );
+ }
+ const orbit = controls.current;
+ if (orbit) {
+ const citizen = follow ? sim.citizens.get(follow) : null;
+ if (citizen) {
+ light.target.set(...citizen.position);
+ light.target.y += 1;
+ light.delta.copy(light.target).sub(orbit.target);
+ camera.position.add(light.delta);
+ orbit.target.copy(light.target);
+ }
+ light.target.copy(orbit.target);
+ orbit.target.x = Math.max(
+ CAMERA_BOUNDS.minX,
+ Math.min(CAMERA_BOUNDS.maxX, orbit.target.x),
+ );
+ orbit.target.z = Math.max(
+ CAMERA_BOUNDS.minZ,
+ Math.min(CAMERA_BOUNDS.maxZ, orbit.target.z),
+ );
+ camera.position.add(light.delta.copy(orbit.target).sub(light.target));
+ camera.position.y = Math.max(2.5, camera.position.y);
+ orbit.update();
+ // City-scale distances need a larger near plane to prevent road/plaza z-fighting.
+ const near = Math.max(0.2, Math.min(15, camera.position.distanceTo(orbit.target) / 100));
+ if (Math.abs(camera.near - near) > 0.05) { camera.near = near; camera.updateProjectionMatrix(); }
+ }
+ if (dt > 0) {
+ samples.current.seconds += dt;
+ samples.current.frames++;
+ }
+ if (samples.current.seconds >= 1) {
+ metrics.current = {
+ fps: Math.round(samples.current.frames / samples.current.seconds),
+ calls: gl.info.render.calls,
+ triangles: gl.info.render.triangles,
+ geometries: gl.info.memory.geometries,
+ textures: gl.info.memory.textures,
+ };
+ samples.current = { seconds: 0, frames: 0 };
+ }
+ }, -1);
+ return (
+ <>
+ <hemisphereLight ref={sky} args={["#d2e0e9", "#697266", 1.5]} />
+ <directionalLight ref={sun} position={[250, 350, 240]} intensity={2.2} />
+ <OrbitControls
+ ref={controls}
+ makeDefault
+ target={[0, 0, -60]}
+ minDistance={CAMERA_BOUNDS.minDistance}
+ maxDistance={CAMERA_BOUNDS.maxDistance}
+ maxPolarAngle={Math.PI / 2 - 0.025}
+ enableDamping={!paused}
+ />
+ <Metro sim={sim} paused={paused} follow={follow} />
+ </>
+ );
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityStage.test.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityStage.test.tsx
new file mode 100644
index 0000000000..a694a00a63
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/CityStage.test.tsx
@@ -0,0 +1,47 @@
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ translations: 0, pending: false, roster: { sample: false, agents: [{ agentId: "real-agent", name: "Agent", figure: null, checkpoint: "idle", state: "idle" }] } }));
+vi.mock("@/i18n", () => ({ useLocaleChunk: () => true, useT: () => {
+ if (++fixture.translations > 30) throw new Error("City entered a reconciliation loop");
+ return (key: string) => key;
+} }));
+vi.mock("../data", () => ({ useSocietyRoster: () => ({ data: fixture.pending ? undefined : fixture.roster, isError: false }) }));
+vi.mock("@/hooks/useWebglSurface", () => ({ useWebglSurface: () => ({ generation: 0 }) }));
+vi.mock("@/hooks/useCanvasAwake", () => ({ useCanvasAwake: () => false }));
+vi.mock("@/lib/graphDimension", () => ({ useWebglSupported: () => false }));
+vi.mock("./CityEnvironment", () => ({ CityEnvironment: () => null }));
+vi.mock("./CityRuntime", () => ({ CityRuntime: () => null, MovingActor: () => null, OVERVIEW: { position: [0, 0, 0], distance: 100, yaw: 0, key: 0 } }));
+
+import { CityStage } from "./CityStage";
+import { citySessions } from "./citySession";
+import { defaultPlacements } from "./cityModel";
+import { addCitizen, setTarget, stepSimulation } from "./citySimulation";
+afterEach(() => { cleanup(); fixture.translations = 0; fixture.pending = false; fixture.roster.sample = false; });
+it("settles roster reconciliation with an unstable translation function", () => {
+ const view = render(<CityStage onOpenLedger={() => undefined} />);
+ expect(view.getByTestId("city-reference").getAttribute("data-version")).toBe("1");
+ expect(fixture.translations).toBeLessThan(10);
+});
+it("discloses successful sample responses instead of claiming a live feed", () => {
+ fixture.roster.sample = true;
+ const view = render(<CityStage onOpenLedger={() => undefined} />);
+ expect(view.getByText("society.city.sample_notice")).toBeTruthy();
+ expect(view.queryByText("society.city.live")).toBeNull();
+});
+it("retains cached live journeys while a returning roster fetch is pending", () => {
+ const live = citySessions.get("live", defaultPlacements, performance.now());
+ const citizen = addCitizen(live.sim, "real-agent", "west");
+ setTarget(live.sim, citizen.id, "east", citizen.revision + 1); stepSimulation(live.sim, 10);
+ const position = [...citizen.position]; fixture.pending = true;
+ const view = render(<CityStage onOpenLedger={() => undefined} />);
+ expect(live.sim.citizens.get(citizen.id)).toBe(citizen);
+ fixture.pending = false; view.rerender(<CityStage onOpenLedger={() => undefined} />);
+ expect(live.sim.citizens.get(citizen.id)).toBe(citizen); expect(citizen.position).toEqual(position);
+});
+it("never replaces live journeys with offline sample actors", () => {
+ const live = citySessions.get("live", defaultPlacements, performance.now());
+ const citizen = live.sim.citizens.get("real-agent");
+ fixture.roster.sample = true; render(<CityStage onOpenLedger={() => undefined} />);
+ expect(live.sim.citizens.get("real-agent")).toBe(citizen);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx
index 4e607dcc44..d36ad0f21f 100644
--- a/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx
@@ -1,65 +1,52 @@
-/** Isolated city reference. Existing catalogs and saved island positions remain intact. */
+/** Live city surface: authored districts, physical metro journeys and real work state. */
import {
Suspense,
+ useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
-import { Canvas, useFrame, useThree } from "@react-three/fiber";
-import { Html, OrbitControls, useGLTF } from "@react-three/drei";
-import { useCityReducedMotion } from "./cityMotion";
-import {
- AnimationMixer,
- Color,
- Group,
- Mesh,
- PMREMGenerator,
- Vector3,
- type DirectionalLight,
- type HemisphereLight,
-} from "three";
-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";
-import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
-import type { OrbitControls as OrbitControlsType } from "three-stdlib";
+import { Canvas } from "@react-three/fiber";
import { useCanvasAwake } from "@/hooks/useCanvasAwake";
import { useWebglSurface } from "@/hooks/useWebglSurface";
import { useWebglSupported } from "@/lib/graphDimension";
import { useLocaleChunk, useT } from "@/i18n";
+import { useEventStore } from "@/store/events";
import { useSocietyRoster } from "../data";
-import { FigureRig, type FigureDrive } from "../figures/FigureRig";
-import type { FigureRecipe } from "../figures/figureRecipe";
import type { PlaceId } from "../world/islandLayout";
import {
+ CAMERA_BOUNDS,
CITY,
DISTRICTS,
- MATERIALS,
- PLOTS,
checkpointStop,
- stopX,
- validPlacement,
+ district,
+ restoreLayout,
+ transformPoint,
type Stop,
- type Vec3,
} from "./cityModel";
import {
addCitizen,
- advanceHour,
- createSimulation,
- daylight,
- previewCrossing,
- safeDestination,
+ cancelJourney,
+ moveBuilding,
setTarget,
- stepSimulation,
+ setTaskActive,
trainAt,
- type CitySimulation,
- type Citizen,
+ type JourneyStage,
} from "./citySimulation";
-import stationUrl from "../../../../../../../../art/studies/city-realism-study/exports/station.glb";
-import buildingUrl from "../../../../../../../../art/studies/city-realism-study/exports/building.glb";
-import trainUrl from "../../../../../../../../art/studies/city-realism-study/exports/train.glb";
-import treeUrl from "../../../../../../../../art/studies/city-realism-study/exports/tree.glb";
-import citizenUrl from "../../../../../../../../art/studies/city-realism-study/exports/citizen.glb";
+import { tickCityClock } from "./cityClock";
+import { citySessions } from "./citySession";
+import { useCityReducedMotion } from "./cityMotion";
+import { CityEnvironment } from "./CityEnvironment";
+import {
+ CityRuntime,
+ MovingActor,
+ OVERVIEW,
+ type CameraFocus,
+ type CityActor,
+ type CityMetrics,
+} from "./CityRuntime";
interface Props {
topRight?: ReactNode;
@@ -67,516 +54,84 @@ interface Props {
onSelectAgent?: (id: string | null) => void;
onSelectPlace?: (place: PlaceId) => void;
}
-interface Actor {
- id: string;
- label: string;
- recipe?: FigureRecipe | null;
- checkpoint: string;
- state: string;
-}
-interface Metrics {
- fps: number;
- calls: number;
- triangles: number;
- geometries: number;
- textures: number;
+const LAYOUT_KEY = "jarvis.city.layout.v2";
+function initialLayout() {
+ try {
+ return restoreLayout(
+ JSON.parse(localStorage.getItem(LAYOUT_KEY) ?? "null"),
+ );
+ } catch {
+ return restoreLayout(null); /* Private storage uses default city plots. */
+ }
}
-const INITIAL_METRICS: Metrics = {
+const DEMO_CHECKPOINT: Record<Stop, string> = {
+ west: "meeting",
+ east: "hub:cli",
+ knowledge: "archive",
+ workshop: "hub:skills",
+ communications: "hub:comms",
+};
+const EMPTY_METRICS: CityMetrics = {
fps: 0,
calls: 0,
triangles: 0,
geometries: 0,
textures: 0,
};
-
-function Asset({
- url,
- ...props
-}: {
- url: string;
- position?: Vec3;
- rotation?: Vec3;
- scale?: number;
- onClick?: () => void;
-}) {
- const { scene } = useGLTF(url);
- // Reference structures have no animated subnodes. Merge by material to keep
- // the artist's authored detail without one draw call for every facade strip.
- const clone = useMemo(() => {
- scene.updateMatrixWorld(true);
- const groups = new Map<Mesh["material"], Mesh[]>();
- scene.traverse((o) => {
- if (o instanceof Mesh) {
- const list = groups.get(o.material) ?? [];
- list.push(o);
- groups.set(o.material, list);
- }
- });
- const result = new Group();
- for (const [material, meshes] of groups) {
- const pieces = meshes.map((mesh) =>
- mesh.geometry.clone().applyMatrix4(mesh.matrixWorld),
- );
- const geometry = mergeGeometries(pieces);
- pieces.forEach((piece) => piece.dispose());
- if (!geometry)
- throw new Error("Reference asset has incompatible geometry attributes");
- const mesh = new Mesh(geometry, material);
- mesh.castShadow = true;
- mesh.receiveShadow = true;
- result.add(mesh);
- }
- return result;
- }, [scene]);
- useEffect(
- () => () => {
- clone.traverse((o) => {
- if (o instanceof Mesh) o.geometry.dispose();
- });
- },
- [clone],
- );
- return <primitive object={clone} {...props} dispose={null} />;
-}
-function Solid({
- at,
- size,
- color = MATERIALS.concrete,
-}: {
- at: Vec3;
- size: Vec3;
- color?: string;
-}) {
- return (
- <mesh position={at} receiveShadow castShadow>
- <boxGeometry args={size} />
- <meshStandardMaterial color={color} roughness={0.8} />
- </mesh>
- );
-}
-function Connection({
- a,
- b,
- width,
- color,
-}: {
- a: Vec3;
- b: Vec3;
- width: number;
- color: string;
-}) {
- const direction = new Vector3(...b).sub(new Vector3(...a));
- const center = new Vector3(...a).add(new Vector3(...b)).multiplyScalar(0.5);
- const group = useRef<Group>(null);
- useEffect(() => {
- group.current?.quaternion.setFromUnitVectors(
- new Vector3(0, 1, 0),
- direction.clone().normalize(),
- );
- }, [a[0], a[1], a[2], b[0], b[1], b[2]]);
- return (
- <group ref={group} position={center}>
- <Solid
- at={[0, 0, 0]}
- size={[width, direction.length(), width]}
- color={color}
- />
- </group>
- );
-}
-function District({
- placements,
- onPlace,
-}: {
- placements: Record<Stop, Vec3>;
- onPlace: (stop: Stop) => void;
-}) {
- const t = useT();
- return (
- <>
- <Solid
- at={[0, -1.3, 0]}
- size={[CITY.width, 2, CITY.depth]}
- color="#6d7468"
- />
- <Solid at={[0, -0.06, 40]} size={[590, 0.1, 12]} color="#535c60" />
- <Solid
- at={[0, -0.03, 43]}
- size={[590, 0.08, 0.15]}
- color={MATERIALS.light}
- />
- <Solid
- at={[0, 10.9, 0]}
- size={[276, 1, 5.5]}
- color={MATERIALS.graphite}
- />
- {[-1.7, 1.7].map((z) => (
- <Solid
- key={z}
- at={[0, 11.65, z]}
- size={[276, 0.15, 0.12]}
- color={MATERIALS.metal}
- />
- ))}
- {[-120, -80, -40, 0, 40, 80, 120].map((x) => (
- <Connection
- key={x}
- a={[x - 3, 0, 0]}
- b={[x + 3, 10.4, 0]}
- width={1}
- color={MATERIALS.graphite}
- />
- ))}
- <Solid at={[0, 19.6, 20]} size={[6, 0.8, 120]} />
- {[-3, 3].map((x) => (
- <Solid
- key={x}
- at={[x, 20.7, 20]}
- size={[0.16, 1.4, 120]}
- color={MATERIALS.metal}
- />
- ))}
- <Solid at={[0, 10, 80]} size={[4, 20, 4]} color={MATERIALS.glass} />
- {(["west", "east"] as Stop[]).map((s) => (
- <group key={s}>
- <Solid at={[stopX(s), -0.15, 69]} size={[76, 0.3, 116]} />
- <Asset url={stationUrl} position={[stopX(s), 12, 0]} />
- <Solid at={[stopX(s), 11.75, 15]} size={[6, 0.5, 6]} />
- <mesh position={[stopX(s), 6, 16]}>
- <boxGeometry args={[4, 12, 4]} />
- <meshStandardMaterial
- color={MATERIALS.glass}
- transparent
- opacity={0.18}
- roughness={0.2}
- depthWrite={false}
- />
- </mesh>
- {[-2, 2].map((offset) => (
- <Solid
- key={offset}
- at={[stopX(s) + offset, 6, 16]}
- size={[0.15, 12, 4]}
- color={MATERIALS.metal}
- />
- ))}
- <Asset
- url={buildingUrl}
- position={placements[s]}
- rotation={[0, Math.PI, 0]}
- onClick={() => onPlace(s)}
- />
- <Html
- zIndexRange={[1, 0]}
- position={[stopX(s), 23, 7]}
- center
- distanceFactor={180}
- style={{ pointerEvents: "none" }}
- >
- <span className="whitespace-nowrap rounded border border-border bg-popover px-3 py-1 text-xs text-popover-foreground">
- {t(`society.city.${s}`)}
- </span>
- </Html>
- {[-1, 1].flatMap((side) =>
- [24, 48, 72, 112].map((z) => (
- <Asset
- key={`${side}:${z}`}
- url={treeUrl}
- position={[stopX(s) + side * 32, 0, z]}
- />
- )),
- )}
- </group>
- ))}
- {DISTRICTS.slice(2).map((d) => (
- <group key={d.id} position={[d.x, 0, d.z]}>
- {[0, 1, 2].map((i) => (
- <Solid
- key={i}
- at={[i * 55 - 55, 25 + i * 12, 0]}
- size={[32, 50 + i * 24, 34]}
- color={MATERIALS.graphite}
- />
- ))}
- <Html
- zIndexRange={[1, 0]}
- position={[0, 110, 0]}
- center
- style={{ pointerEvents: "none" }}
- >
- <span className="whitespace-nowrap rounded bg-popover px-2 py-1 text-xs text-popover-foreground">
- {t(`society.city.${d.id}`)} · {t("society.city.blockout")}
- </span>
- </Html>
- </group>
- ))}
- </>
- );
-}
-
-function ReferenceCitizen({
- citizen,
- paused,
- detailed,
-}: {
- citizen: Citizen;
- paused: boolean;
- detailed: { current: boolean };
-}) {
- const { scene, animations } = useGLTF(citizenUrl);
- const clone = useMemo(() => scene.clone(true), [scene]);
- const mixer = useMemo(() => new AnimationMixer(clone), [clone]);
- const wasMoving = useRef(false);
- useEffect(() => {
- for (const clip of animations) mixer.clipAction(clip).play();
- return () => {
- mixer.stopAllAction();
- mixer.uncacheRoot(clone);
- };
- }, [animations, clone, mixer]);
- useFrame((_, dt) => {
- const moving = !paused && detailed.current && citizen.speed > 0;
- if (moving) mixer.update((dt * citizen.speed) / 1.28);
- else if (wasMoving.current) mixer.setTime(0);
- wasMoving.current = moving;
- });
- return <primitive object={clone} dispose={null} />;
-}
-function MovingActor({
- actor,
- sim,
- paused,
- selected,
- onClick,
-}: {
- actor: Actor;
- sim: CitySimulation;
- paused: boolean;
- selected: boolean;
- onClick: () => void;
-}) {
- const root = useRef<Group>(null);
- const body = useRef<Group>(null);
- const distant = useRef<Mesh>(null);
- const detailed = useRef(true);
- const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });
- const citizen = sim.citizens.get(actor.id)!;
- useFrame(({ camera }) => {
- if (!root.current) return;
- root.current.position.set(...citizen.position);
- root.current.rotation.y = citizen.heading;
- detailed.current = selected || camera.position.distanceTo(root.current.position) < 80;
- if (body.current) body.current.visible = detailed.current;
- if (distant.current) distant.current.visible = !detailed.current;
- drive.current.mode = citizen.speed > 0 ? "walk" : "idle";
- drive.current.speed = citizen.speed;
- });
- return (
- <group
- ref={root}
- position={citizen.position}
- onClick={(event) => {
- event.stopPropagation();
- onClick();
- }}
- >
- <group ref={body}>
- {actor.recipe ? (
- <FigureRig recipe={actor.recipe} drive={drive} paused={paused} />
- ) : (
- <ReferenceCitizen citizen={citizen} paused={paused} detailed={detailed} />
- )}
- </group>
- <mesh ref={distant} position={[0, 0.85, 0]} visible={false}>
- <capsuleGeometry args={[0.24, 1.2, 3, 6]} />
- <meshStandardMaterial color="#438c9e" roughness={0.8} />
- </mesh>
- {selected && (
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.03, 0]}>
- <ringGeometry args={[0.7, 0.85, 24]} />
- <meshBasicMaterial color="#e7c56b" />
- </mesh>
- )}
- {selected && (
- <Html zIndexRange={[1, 0]} position={[0, 2.5, 0]} center>
- <span className="whitespace-nowrap rounded bg-popover px-2 py-1 text-xs text-popover-foreground">
- {actor.label}
- </span>
- </Html>
- )}
- </group>
- );
-}
-
-function Runtime({
- sim,
- hour,
- paused,
- awake,
- follow,
- overview,
- onMetrics,
-}: {
- sim: CitySimulation;
- hour: number;
- paused: boolean;
- awake: boolean;
- follow: string | null;
- overview: number;
- onMetrics: (m: Metrics) => void;
-}) {
- const train = useRef<Group>(null);
- const sun = useRef<DirectionalLight>(null);
- const sky = useRef<HemisphereLight>(null);
- const controls = useRef<OrbitControlsType>(null);
- const { scene, camera, gl, invalidate } = useThree();
- const lastTime = useRef(performance.now());
- const sample = useRef({ seconds: 0, frames: 0 });
- const colors = useMemo(
- () => ({ night: new Color("#263449"), day: new Color("#afc9da") }),
- [],
- );
- useEffect(() => {
- // A local reflection environment keeps metal/glass legible without a network HDRI.
- const room = new RoomEnvironment();
- const generator = new PMREMGenerator(gl);
- const target = generator.fromScene(room, 0.04);
- const previous = scene.environment;
- scene.environment = target.texture;
- room.dispose(); generator.dispose(); invalidate();
- return () => { scene.environment = previous; target.dispose(); };
- }, [gl, scene, invalidate]);
- useEffect(() => {
- lastTime.current = performance.now();
- invalidate();
- }, [paused, awake, invalidate]);
- useEffect(() => {
- camera.position.set(200, 140, 240);
- controls.current?.target.set(0, 0, 45);
- controls.current?.update();
- invalidate();
- }, [overview, camera, invalidate]);
- useEffect(() => {
- const citizen = follow ? sim.citizens.get(follow) : null;
- if (citizen && controls.current) {
- const [x, y, z] = citizen.position;
- controls.current.target.set(x, y + 1, z);
- camera.position.set(x + 14, y + 10, z - 18);
- controls.current.update();
- invalidate();
- }
- }, [follow, camera, sim, invalidate]);
- useFrame((_, dt) => {
- const now = performance.now();
- if (!paused)
- stepSimulation(sim, Math.max(0, (now - lastTime.current) / 1000));
- lastTime.current = now;
- const currentTrain = trainAt(sim.time);
- train.current?.position.set(...currentTrain.position);
- const strength = daylight(hour);
- scene.background = colors.night.clone().lerp(colors.day, strength);
- scene.environmentIntensity = 0.2 + strength * 0.6;
- if (sun.current) {
- sun.current.intensity = 0.25 + strength * 2.5;
- sun.current.position.set(
- Math.cos((hour / 24) * Math.PI * 2) * 180,
- 60 + strength * 220,
- 120,
- );
- }
- if (sky.current) sky.current.intensity = 0.65 + strength * 1.2;
- if (follow && controls.current) {
- const citizen = sim.citizens.get(follow);
- if (citizen) {
- const target = new Vector3(...citizen.position);
- camera.position.add(target.clone().sub(controls.current.target));
- controls.current.target.copy(target);
- controls.current.update();
- }
- }
- sample.current.seconds += dt;
- sample.current.frames++;
- if (sample.current.seconds >= 1) {
- onMetrics({
- fps: Math.round(sample.current.frames / sample.current.seconds),
- calls: gl.info.render.calls,
- triangles: gl.info.render.triangles,
- geometries: gl.info.memory.geometries,
- textures: gl.info.memory.textures,
- });
- sample.current = { seconds: 0, frames: 0 };
- }
- }, -1);
- return (
- <>
- <hemisphereLight ref={sky} args={["#c6d8e9", "#69695a", 1.4]} />
- <directionalLight
- ref={sun}
- castShadow
- position={[100, 180, 120]}
- intensity={2}
- shadow-mapSize={[1024, 1024]}
- shadow-camera-left={-220}
- shadow-camera-right={220}
- shadow-camera-top={200}
- shadow-camera-bottom={-200}
- shadow-camera-far={700}
- shadow-bias={-0.0005}
- />
- <OrbitControls
- ref={controls}
- makeDefault
- target={[0, 0, 45]}
- minDistance={5}
- maxDistance={1800}
- maxPolarAngle={Math.PI / 2 - 0.02}
- enableDamping={!paused}
- />
- <group ref={train}>
- <Asset url={trainUrl} />
- </group>
- </>
+export function CityStage(props: Props) {
+ const ready = useLocaleChunk("society");
+ return ready ? (
+ <ReadyCity {...props} />
+ ) : (
+ <div className="h-full animate-pulse bg-secondary" aria-busy="true" />
);
}
-
-export function CityStage({
+function ReadyCity({
topRight,
onOpenLedger,
onSelectAgent,
onSelectPlace,
}: Props) {
const t = useT();
- const ready = useLocaleChunk("society");
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
const host = useRef<HTMLDivElement>(null);
const { generation } = useWebglSurface(host);
- const awake = useCanvasAwake(host);
- const webgl = useWebglSupported();
- const reduced = useCityReducedMotion();
+ const awake = useCanvasAwake(host),
+ webgl = useWebglSupported(),
+ reduced = useCityReducedMotion();
const roster = useSocietyRoster();
- const sim = useMemo(createSimulation, []);
const [demo, setDemo] = useState(false);
- const [count, setCount] = useState(1);
- const [selected, setSelected] = useState<string | null>(null);
- const [follow, setFollow] = useState<string | null>(null);
- const [overview, setOverview] = useState(0);
- const [hour, setHour] = useState(10);
- const [dayPaused, setDayPaused] = useState(false);
- const [metrics, setMetrics] = useState(INITIAL_METRICS);
- const [tick, setTick] = useState(0);
- const [activePlot, setActivePlot] = useState<Stop | null>(null);
- const [placementError, setPlacementError] = useState(false);
- const [placements, setPlacements] = useState<Record<Stop, Vec3>>({
- west: [-120, 0, 104],
- east: [120, 0, 104],
- });
- const actors = useMemo<Actor[]>(
+ const sample = !demo && roster.data?.sample === true;
+ const loading = !demo && !roster.data;
+ const { sim, clock } = useMemo(() => citySessions.get(demo ? "demo" : sample ? "sample" : "live", () => initialLayout().placements, performance.now()), [demo, sample]);
+ const metrics = useRef<CityMetrics>({ ...EMPTY_METRICS }),
+ requestFrame = useRef<() => void>(() => undefined);
+ const signatures = useRef(new Map<string, string>());
+ const [count, setCount] = useState(8),
+ [demoStop, setDemoStop] = useState<Stop>("east");
+ const [selected, setSelected] = useState<string | null>(null),
+ [follow, setFollow] = useState<string | null>(null);
+ const [selectedStop, setSelectedStop] = useState<Stop | null>(null),
+ [focus, setFocus] = useState<CameraFocus>(OVERVIEW);
+ const [interiorStop, setInteriorStop] = useState<Stop | null>(null);
+ const [details, setDetails] = useState(false),
+ [message, setMessage] = useState<string | null>(null);
+ const [version, setVersion] = useState(0),
+ [snapshot, setSnapshot] = useState({
+ hour: 10,
+ time: 0,
+ workKey: "",
+ debt: 0,
+ });
+ const demoLabel = t("society.city.reference_agent");
+ const actors = useMemo<CityActor[]>(
() =>
demo
? Array.from({ length: count }, (_, i) => ({
- id: `reference-${i}`,
- label: `${t("society.city.reference_agent")} ${i + 1}`,
- checkpoint: "idle",
- state: "demo",
+ id: `city-demo-${i}`,
+ label: `${demoLabel} ${i + 1}`,
+ checkpoint: DEMO_CHECKPOINT[demoStop],
+ state: "working",
}))
: (roster.data?.agents ?? []).map((a) => ({
id: a.agentId,
@@ -585,14 +140,10 @@ export function CityStage({
checkpoint: a.checkpoint,
state: a.state,
})),
- [demo, count, roster.data, t],
+ [demo, count, demoStop, roster.data, demoLabel],
);
- // Reconcile outside the render loop; a changed checkpoint replaces intent, not position.
- const signatures = useRef(new Map<string, string>());
- for (const actor of actors)
- if (!sim.citizens.has(actor.id))
- addCitizen(sim, actor.id, checkpointStop(actor.checkpoint) ?? "west");
useEffect(() => {
+ if (!demo && !roster.data) return; // A pending fetch is not an empty roster.
const ids = new Set(actors.map((a) => a.id));
for (const id of sim.citizens.keys())
if (!ids.has(id)) {
@@ -600,122 +151,131 @@ export function CityStage({
signatures.current.delete(id);
}
for (const actor of actors) {
+ const created = !sim.citizens.has(actor.id);
+ const citizen = addCitizen(sim, actor.id, "west");
const signature = `${actor.checkpoint}:${actor.state}`;
- if (signatures.current.get(actor.id) === signature) continue;
+ if (!created && signatures.current.get(actor.id) === signature) continue;
signatures.current.set(actor.id, signature);
- const citizen = sim.citizens.get(actor.id)!;
const target = checkpointStop(actor.checkpoint);
- if (target) setTarget(sim, actor.id, target, citizen.revision + 1);
- else if (!demo && citizen.stage !== "arrived") {
- const safeStop = safeDestination(sim, citizen);
- setTarget(sim, actor.id, safeStop, citizen.revision + 1);
+ if (actor.state === "paused" || !target) {
+ setTaskActive(sim, actor.id, false);
+ if (citizen.stage !== "arrived")
+ cancelJourney(sim, actor.id, citizen.revision + 1);
+ } else {
+ setTarget(sim, actor.id, target, citizen.revision + 1);
+ setTaskActive(sim, actor.id, actor.state === "working");
}
}
- }, [actors, sim, demo]);
+ setVersion((v) => v + 1);
+ requestFrame.current();
+ }, [actors, sim, demo, roster.data]);
useEffect(() => {
- let last = performance.now();
const timer = window.setInterval(() => {
- const now = performance.now(),
- dt = (now - last) / 1000;
- last = now;
- if (!awake && !reduced) stepSimulation(sim, dt);
- setHour((h) => advanceHour(h, dt, dayPaused || reduced));
- setTick((n) => n + 1);
+ tickCityClock(clock, sim, performance.now(), reduced);
+ setSnapshot({
+ hour: clock.hour,
+ time: sim.time,
+ workKey: [...sim.citizens.values()]
+ .filter((c) => c.atWork && c.taskActive)
+ .map((c) => c.target)
+ .sort()
+ .join(","),
+ debt: sim.debt,
+ });
}, 250);
return () => window.clearInterval(timer);
- }, [sim, awake, reduced, dayPaused]);
- function travel(stop: Stop) {
- for (const c of sim.citizens.values())
- setTarget(sim, c.id, stop, c.revision + 1);
- setTick((n) => n + 1);
+ }, [clock, sim, reduced]);
+ const activeStops = useMemo(
+ () => new Set(snapshot.workKey.split(",").filter(Boolean) as Stop[]),
+ [snapshot.workKey],
+ );
+ const selectActor = useCallback((id: string) => {
+ setSelected(id);
+ requestFrame.current();
+ }, []);
+ const selectStop = useCallback(
+ (stop: Stop) => {
+ const d = district(stop);
+ setSelectedStop(stop);
+ setFollow(null);
+ setMessage(null);
+ setInteriorStop(stop);
+ const position = transformPoint(
+ sim.placements[stop],
+ d.buildingRotation,
+ [0, 0, -8],
+ );
+ setFocus((f) => ({
+ position,
+ distance: 88,
+ yaw: d.buildingRotation + Math.PI + 0.3,
+ key: f.key + 1,
+ }));
+ },
+ [sim],
+ );
+ function overview() {
+ setFollow(null);
+ setSelectedStop(null);
+ setInteriorStop(null);
+ setFocus((f) => ({ ...OVERVIEW, key: f.key + 1 }));
}
- function movePlot(delta: number) {
- if (!activePlot) return;
- const current = placements[activePlot];
- const x = current[0] + delta;
- const valid = validPlacement(
- PLOTS.find((p) => p.id === activePlot)!,
- x,
- current[2],
- 48,
- 42,
- [],
- );
- setPlacementError(!valid);
- if (valid)
- setPlacements({ ...placements, [activePlot]: [x, 0, current[2]] });
+ function movePlot(dx: number, dz: number) {
+ if (!selectedStop) return;
+ const p = sim.placements[selectedStop];
+ if (!moveBuilding(sim, selectedStop, [p[0] + dx, p[1], p[2] + dz])) {
+ setMessage("invalid_plot");
+ return;
+ }
+ if (demo || sample) { setMessage("demo_plot"); setVersion((v) => v + 1); requestFrame.current(); return; }
+ try {
+ localStorage.setItem(
+ LAYOUT_KEY,
+ JSON.stringify({ version: 2, placements: sim.placements }),
+ );
+ setMessage("saved_plot");
+ } catch {
+ setMessage("session_plot");
+ }
+ setVersion((v) => v + 1);
+ requestFrame.current();
}
- const selectedActor = actors.find((a) => a.id === selected);
- const citizen = selected ? sim.citizens.get(selected) : null;
+ const citizen = selected ? sim.citizens.get(selected) : undefined;
+ const actor = actors.find((a) => a.id === selected),
+ train = trainAt(snapshot.time);
const button =
- "rounded border border-border bg-background px-2 py-1 text-xs text-foreground hover:bg-muted disabled:opacity-40";
- if (!ready) return null;
+ "rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground transition-colors hover:bg-muted focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring";
+ const activeDistrict = selectedStop ? district(selectedStop) : null;
+ const stageText = (stage: JourneyStage, workspaceQueue = false) =>
+ t(
+ workspaceQueue
+ ? "society.city.waiting_workspace"
+ : `society.city.stage_${stage}`,
+ );
return (
<div
className="relative flex h-full min-h-0 flex-col bg-background text-foreground"
data-testid="city-reference"
+ data-version={version}
>
<div className="flex flex-wrap items-center gap-2 border-b border-border bg-popover p-2">
<strong className="mr-auto text-sm">{t("society.city.title")}</strong>
{topRight}
- <label className="flex items-center gap-1 text-xs">
- <input
- type="checkbox"
- checked={demo}
- onChange={(e) => {
- setDemo(e.target.checked);
- setSelected(null);
- setFollow(null);
- }}
- />
- {t("society.city.demo")}
- </label>
- {demo && (
- <>
- <select
- className={button}
- aria-label={t("society.city.agent_count")}
- value={count}
- onChange={(e) => setCount(Number(e.target.value))}
- >
- {[1, 8, 30].map((n) => (
- <option key={n}>{n}</option>
- ))}
- </select>
- <button className={button} onClick={() => travel("west")}>
- {t("society.city.west")}
- </button>
- <button className={button} onClick={() => travel("east")}>
- {t("society.city.east")}
- </button>
- <button
- className={button}
- disabled={
- !actors.some((a) =>
- ["arrived", "waiting", "unreachable"].includes(
- sim.citizens.get(a.id)?.stage ?? "",
- ),
- )
- }
- onClick={() => {
- for (const actor of actors) previewCrossing(sim, actor.id);
- }}
- >
- {t("society.city.bridge_walk")}
- </button>
- </>
- )}
+ <button className={button} onClick={overview}>
+ {t("society.city.overview")}
+ </button>
<button
className={button}
onClick={() => {
- setFollow(null);
- setOverview((n) => n + 1);
+ clock.dayPaused = !clock.dayPaused;
+ setSnapshot((s) => ({ ...s }));
}}
>
- {t("society.city.overview")}
- </button>
- <button className={button} onClick={() => setDayPaused(!dayPaused)}>
- {t(dayPaused ? "society.city.resume_day" : "society.city.pause_day")}
+ {t(
+ clock.dayPaused
+ ? "society.city.resume_day"
+ : "society.city.pause_day",
+ )}
</button>
<label className="flex items-center gap-1 text-xs">
{t("society.city.hour")}
@@ -726,57 +286,113 @@ export function CityStage({
min="0"
max="23.9"
step="0.1"
- value={hour}
+ value={snapshot.hour}
onChange={(e) => {
- setHour(Number(e.target.value));
- setDayPaused(true);
+ clock.hour = Number(e.target.value);
+ clock.dayPaused = true;
+ setSnapshot((s) => ({ ...s, hour: clock.hour }));
+ requestFrame.current();
}}
/>
- {String(Math.floor(hour)).padStart(2, "0")}:00
+ {String(Math.floor(snapshot.hour)).padStart(2, "0")}:00
</label>
+ <button
+ className={button}
+ aria-expanded={details}
+ onClick={() => setDetails(!details)}
+ >
+ {t("society.city.options")}
+ </button>
</div>
+ {details && (
+ <div className="flex flex-wrap items-center gap-2 border-b border-border bg-muted/40 p-2 text-xs">
+ <label className="flex items-center gap-1">
+ <input
+ type="checkbox"
+ checked={demo}
+ onChange={(e) => {
+ setDemo(e.target.checked);
+ setSelected(null);
+ setFollow(null);
+ }}
+ />
+ {t("society.city.demo")}
+ </label>
+ {demo && (
+ <>
+ <select
+ className={button}
+ aria-label={t("society.city.agent_count")}
+ value={count}
+ onChange={(e) => setCount(Number(e.target.value))}
+ >
+ {[1, 8, 30].map((n) => (
+ <option key={n}>{n}</option>
+ ))}
+ </select>
+ <select
+ className={button}
+ aria-label={t("society.city.demo_target")}
+ value={demoStop}
+ onChange={(e) => setDemoStop(e.target.value as Stop)}
+ >
+ {DISTRICTS.map((d) => (
+ <option key={d.stop} value={d.stop}>
+ {t(d.labelKey)}
+ </option>
+ ))}
+ </select>
+ </>
+ )}
+ <span data-testid="city-metrics">
+ {metrics.current.fps} FPS · {metrics.current.calls} draws ·{" "}
+ {metrics.current.triangles.toLocaleString()} triangles
+ </span>
+ </div>
+ )}
<div ref={host} className="relative isolate min-h-0 flex-1">
{webgl ? (
<Canvas
key={generation}
camera={{
- position: [200, 140, 240],
+ position: [700, 550, 850],
fov: 45,
near: 0.2,
- far: 4000,
+ far: 9000,
}}
dpr={1}
- shadows
gl={{ antialias: true, alpha: false }}
frameloop={!awake ? "never" : reduced ? "demand" : "always"}
>
<Suspense fallback={null}>
- <Runtime
+ <CityRuntime
sim={sim}
- hour={hour}
+ clock={clock}
paused={reduced}
- awake={awake}
+ focus={focus}
follow={follow}
- overview={overview}
- onMetrics={setMetrics}
+ metrics={metrics}
+ requestFrame={requestFrame}
/>
- <District
- placements={placements}
- onPlace={(s) => {
- setActivePlot(s);
- setPlacementError(false);
- }}
+ <CityEnvironment
+ graph={sim.graph}
+ placements={sim.placements}
+ activeStops={activeStops}
+ onSelect={selectStop}
+ interiorStop={interiorStop ?? (follow && sim.citizens.get(follow)?.atWork ? sim.citizens.get(follow)!.target : null)}
/>
- {actors.map((actor) => (
- <MovingActor
- key={actor.id}
- actor={actor}
- sim={sim}
- paused={reduced}
- selected={selected === actor.id}
- onClick={() => setSelected(actor.id)}
- />
- ))}
+ {actors
+ .filter((a) => sim.citizens.has(a.id))
+ .map((a) => (
+ <MovingActor
+ key={a.id}
+ actor={a}
+ sim={sim}
+ paused={reduced || !awake}
+ selected={selected === a.id}
+ onSelect={selectActor}
+ />
+ ))}
</Suspense>
</Canvas>
) : (
@@ -787,64 +403,139 @@ export function CityStage({
</button>
</div>
)}
- <div className="absolute z-20 bottom-3 left-3 max-w-sm rounded border border-border bg-popover/95 p-3 text-xs shadow-lg">
- <p className="font-medium">{t("society.city.reference_notice")}</p>
- <p className="mt-1 text-muted-foreground">
- {t("society.city.controls")}
- </p>
- <p className="mt-2 font-mono" data-testid="city-metrics">
- {metrics.fps} FPS · {metrics.calls} draws ·{" "}
- {metrics.triangles.toLocaleString()} triangles
- </p>
- <p className="text-muted-foreground">
- 600 × 400 m · {actors.length} {t("society.city.agents")} ·{" "}
- {Math.floor(sim.time)} s
+ <div
+ className="absolute left-3 top-3 z-20 flex max-w-[55%] flex-wrap gap-1 rounded-lg border border-border bg-popover/95 p-1.5 shadow-sm"
+ aria-label={t("society.city.districts")}
+ >
+ {DISTRICTS.map((d) => (
+ <button
+ key={d.stop}
+ className="rounded px-2 py-1 text-xs hover:bg-muted"
+ onClick={() => selectStop(d.stop)}
+ >
+ {t(d.labelKey)}
+ </button>
+ ))}
+ </div>
+ <div className="absolute right-3 top-3 z-20 max-h-[40%] w-48 overflow-auto rounded-lg border border-border bg-popover/95 p-2 text-xs shadow-sm">
+ <p className="mb-2 font-medium">
+ {t(
+ demo
+ ? "society.city.demo"
+ : loading
+ ? "society.city.loading"
+ : sample
+ ? "society.city.sample"
+ : "society.city.live",
+ )}
</p>
- {reduced && <p>{t("society.city.reduced")}</p>}
+ {sample && (
+ <p className="mb-2 text-muted-foreground">
+ {t("society.city.sample_notice")}
+ </p>
+ )}
{roster.isError && !demo && (
<p role="alert">{t("society.city.feed_error")}</p>
)}
- </div>
- <div className="absolute z-20 right-3 top-3 max-h-[55%] w-52 overflow-auto rounded border border-border bg-popover/95 p-2 text-xs">
- <p className="mb-2 font-medium">
- {t(demo ? "society.city.demo" : "society.city.live")}
- </p>
{actors.map((a) => (
<button
key={a.id}
- className="mb-1 block w-full rounded px-2 py-1 text-left hover:bg-muted"
- onClick={() => setSelected(a.id)}
+ className="mb-1 block w-full rounded p-1.5 text-left hover:bg-muted"
+ onClick={() => selectActor(a.id)}
>
{a.label}
<span className="block text-muted-foreground">
- {t(
- `society.city.stage_${sim.citizens.get(a.id)?.stage ?? "arrived"}`,
+ {stageText(
+ sim.citizens.get(a.id)?.stage ?? "arrived",
+ sim.citizens.get(a.id)?.waitingForWorkspace,
)}
</span>
</button>
))}
</div>
- {selectedActor && citizen && (
+ <div className="absolute bottom-3 left-3 z-20 rounded-lg border border-border bg-popover/95 p-3 text-xs shadow-sm">
+ <svg
+ viewBox="-950 -650 1900 1300"
+ width="190"
+ height="120"
+ role="img"
+ aria-label={t("society.city.city_map")}
+ >
+ <rect
+ x={CAMERA_BOUNDS.minX}
+ y={CAMERA_BOUNDS.minZ}
+ width={CAMERA_BOUNDS.maxX - CAMERA_BOUNDS.minX}
+ height={CAMERA_BOUNDS.maxZ - CAMERA_BOUNDS.minZ}
+ rx="40"
+ fill="none"
+ stroke="currentColor"
+ opacity="0.2"
+ strokeWidth="8"
+ />
+ <ellipse
+ cx="0"
+ cy="-110"
+ rx="500"
+ ry="280"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="10"
+ opacity="0.4"
+ />
+ {DISTRICTS.map((d) => (
+ <circle
+ key={d.stop}
+ cx={d.stationPosition[0]}
+ cy={d.stationPosition[2]}
+ r="26"
+ fill={d.color}
+ />
+ ))}
+ <circle
+ cx={train.position[0]}
+ cy={train.position[2]}
+ r="17"
+ fill="currentColor"
+ />
+ </svg>
+ <p>
+ {t("society.city.metro_line")} · {actors.length}{" "}
+ {t("society.city.agents")}
+ </p>
+ <p className="mt-1 text-muted-foreground">
+ {CITY.width / 1000} × {CITY.depth / 1000} km ·{" "}
+ {t("society.city.city_limits")}
+ </p>
+ {reduced && (
+ <p className="mt-2 max-w-52">{t("society.city.reduced")}</p>
+ )}
+ {snapshot.debt > 1 && <p>{t("society.city.catching_up")}</p>}
+ </div>
+ {citizen && actor && (
<div
- className="absolute z-20 bottom-3 right-3 w-64 rounded border border-border bg-popover p-3 text-xs shadow-lg"
+ className="absolute bottom-3 right-3 z-20 w-64 rounded-lg border border-border bg-popover p-3 text-xs shadow-lg"
data-testid="city-journey"
data-stage={citizen.stage}
data-position={citizen.position.join(",")}
- data-tick={tick}
+ data-simulation-time={snapshot.time}
>
- <strong>{selectedActor.label}</strong>
- <p>
- {t("society.city.task")}: {selectedActor.checkpoint} ·{" "}
- {selectedActor.state}
+ <strong>{actor.label}</strong>
+ <p className="mt-1">
+ {t(
+ demo || sample
+ ? "society.city.example_state"
+ : "society.city.task",
+ )}
+ : {actor.checkpoint} · {actor.state}
</p>
<p>
{t("society.city.travel")}:{" "}
- {t(`society.city.stage_${citizen.stage}`)}
+ {stageText(citizen.stage, citizen.waitingForWorkspace)}
</p>
<p>
- {t("society.city.target")}: {t(`society.city.${citizen.target}`)}
+ {t("society.city.target")}: {t(district(citizen.target).labelKey)}
</p>
- <div className="mt-2 flex gap-2">
+ <div className="mt-2 flex flex-wrap gap-2">
<button
className={button}
onClick={() =>
@@ -857,7 +548,7 @@ export function CityStage({
: "society.city.follow",
)}
</button>
- {!demo && (
+ {!demo && !sample && (
<button
className={button}
onClick={() => onSelectAgent?.(citizen.id)}
@@ -868,34 +559,76 @@ export function CityStage({
</div>
</div>
)}
- {activePlot && (
- <div className="absolute z-20 left-3 top-3 rounded border border-border bg-popover p-3 text-xs shadow-lg">
- <strong>{t(`society.city.${activePlot}`)}</strong>
- <p className="my-2">{t("society.city.plot")}</p>
- <div className="flex gap-2">
- <button className={button} onClick={() => movePlot(-4)}>
- −4 m
- </button>
- <button className={button} onClick={() => movePlot(4)}>
- +4 m
- </button>
- <button
- className={button}
- onClick={() =>
- onSelectPlace?.(activePlot === "west" ? "civic" : "cli")
- }
- >
- {t("society.city.open_building")}
- </button>
- <button className={button} onClick={() => setActivePlot(null)}>
- {t("society.city.close")}
- </button>
- </div>
- {placementError && (
- <p role="alert" className="mt-2">
- {t("society.city.invalid_plot")}
+ {activeDistrict && (
+ <div
+ className="absolute left-3 top-16 z-20 max-w-72 rounded-lg border border-border bg-popover p-3 text-xs shadow-lg"
+ data-testid="city-building-panel"
+ >
+ <strong>{t(activeDistrict.labelKey)}</strong>
+ <p className="my-2 text-muted-foreground">
+ {t(`society.city.description_${activeDistrict.id}`)}
+ </p>
+ <button
+ className={button}
+ onClick={() =>
+ activeDistrict.stop === "east"
+ ? setActiveSection("agentic-ide")
+ : onSelectPlace?.(activeDistrict.placeId)
+ }
+ >
+ {t(
+ activeDistrict.stop === "east"
+ ? "society.city.open_terminal"
+ : "society.city.open_building",
+ )}
+ </button>
+ <button
+ className={`${button} ml-1`}
+ onClick={() => {
+ setInteriorStop(
+ interiorStop === activeDistrict.stop
+ ? null
+ : activeDistrict.stop,
+ );
+ requestFrame.current();
+ }}
+ >
+ {t(
+ interiorStop === activeDistrict.stop
+ ? "society.city.exterior"
+ : "society.city.work_floor",
+ )}
+ </button>
+ <details className="mt-3">
+ <summary className="cursor-pointer">
+ {t("society.city.adjust_plot")}
+ </summary>
+ <div className="my-2 flex flex-wrap gap-1">
+ <button className={button} onClick={() => movePlot(-4, 0)}>
+ ← 4 m
+ </button>
+ <button className={button} onClick={() => movePlot(4, 0)}>
+ 4 m →
+ </button>
+ <button className={button} onClick={() => movePlot(0, -4)}>
+ ↑ 4 m
+ </button>
+ <button className={button} onClick={() => movePlot(0, 4)}>
+ 4 m ↓
+ </button>
+ </div>
+ </details>
+ {message && (
+ <p role="status" className="my-2">
+ {t(`society.city.${message}`)}
</p>
)}
+ <button
+ className="mt-2 text-muted-foreground underline"
+ onClick={() => setSelectedStop(null)}
+ >
+ {t("society.city.close")}
+ </button>
</div>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityClock.test.ts b/jarvis/ui/web/frontend/src/components/society/city/cityClock.test.ts
new file mode 100644
index 0000000000..dbd1fc8b30
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/cityClock.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { addCitizen, createSimulation, setTarget } from "./citySimulation";
+import { createCityClock, tickCityClock } from "./cityClock";
+
+describe("shared city clock", () => {
+ it("does not double-count a frame and timer at the same time", () => {
+ const sim = createSimulation(),
+ clock = createCityClock(0);
+ tickCityClock(clock, sim, 1000, false);
+ tickCityClock(clock, sim, 1000, false);
+ expect(sim.time).toBeCloseTo(1);
+ tickCityClock(clock, sim, 1500, false);
+ expect(sim.time).toBeCloseTo(1.5);
+ });
+ it("freezes journeys and daylight and does not replay the paused interval", () => {
+ const sim = createSimulation(),
+ clock = createCityClock(0);
+ tickCityClock(clock, sim, 30000, true);
+ expect(sim.time).toBe(0);
+ expect(clock.hour).toBe(10);
+ tickCityClock(clock, sim, 31000, false);
+ expect(sim.time).toBeCloseTo(1);
+ });
+ it("budgets active catch-up and retains remaining physical time", () => {
+ const sim = createSimulation(),
+ clock = createCityClock(0);
+ addCitizen(sim, "commuter", "west");
+ setTarget(sim, "commuter", "east", 1);
+ tickCityClock(clock, sim, 120000, false);
+ expect(sim.time).toBeLessThan(10);
+ expect(sim.debt).toBeGreaterThan(110);
+ for (let i = 0; i < 100; i++) tickCityClock(clock, sim, 120000, false);
+ expect(sim.time).toBeCloseTo(120);
+ expect(sim.debt).toBeLessThan(0.0001);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityClock.ts b/jarvis/ui/web/frontend/src/components/society/city/cityClock.ts
new file mode 100644
index 0000000000..daa63f0e3a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/cityClock.ts
@@ -0,0 +1,32 @@
+import {
+ advanceHour,
+ stepWithBudget,
+ type CitySimulation,
+} from "./citySimulation";
+
+export interface CityClock {
+ lastMs: number;
+ hour: number;
+ dayPaused: boolean;
+}
+export const createCityClock = (now: number): CityClock => ({
+ lastMs: now,
+ hour: 10,
+ dayPaused: false,
+});
+/** Both foreground frames and background ticks consume the SAME monotonic clock. */
+export function tickCityClock(
+ clock: CityClock,
+ sim: CitySimulation,
+ now: number,
+ paused: boolean,
+): void {
+ const elapsed = Math.max(0, (now - clock.lastMs) / 1000);
+ clock.lastMs = Math.max(clock.lastMs, now);
+ if (paused) {
+ sim.debt = 0;
+ return;
+ }
+ stepWithBudget(sim, elapsed, 20);
+ clock.hour = advanceHour(clock.hour, elapsed, clock.dayPaused);
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityInstances.test.ts b/jarvis/ui/web/frontend/src/components/society/city/cityInstances.test.ts
new file mode 100644
index 0000000000..f26ff591fa
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/cityInstances.test.ts
@@ -0,0 +1,13 @@
+import { applyProps } from "@react-three/fiber";
+import { BoxGeometry, InstancedMesh, MeshBasicMaterial } from "three";
+import { expect, it } from "vitest";
+import { releaseCityInstances } from "./cityInstances";
+
+it("releases instance buffers even when R3F shadows the native disposer", () => {
+ const geometry = new BoxGeometry(), material = new MeshBasicMaterial();
+ const mesh = new InstancedMesh(geometry, material, 1);
+ let releases = 0; mesh.addEventListener("dispose", () => releases++);
+ applyProps(mesh, { dispose: null });
+ expect(() => releaseCityInstances(mesh)).not.toThrow();
+ expect(releases).toBe(1); geometry.dispose(); material.dispose();
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityInstances.ts b/jarvis/ui/web/frontend/src/components/society/city/cityInstances.ts
new file mode 100644
index 0000000000..7df591f819
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/cityInstances.ts
@@ -0,0 +1,6 @@
+import { InstancedMesh } from "three";
+
+/** R3F's dispose={null} prop can shadow the instance's native dispose method. */
+export function releaseCityInstances(mesh: InstancedMesh): void {
+ InstancedMesh.prototype.dispose.call(mesh);
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts b/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts
index 7c43c15100..fdfd2ba7ad 100644
--- a/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts
+++ b/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts
@@ -1,216 +1,206 @@
-/** Metre-based reference district. Layer identity is part of every route node. */
+/** Metre-based city: rendering and routing share the same authored anchors. */
export type Vec3 = [number, number, number];
-export type Stop = "west" | "east";
-export interface RouteNode {
- id: string;
- position: Vec3;
- layer: "ground" | "platform" | "bridge";
+export type Stop = "west" | "east" | "knowledge" | "workshop" | "communications";
+export type DistrictId = "central" | "terminal" | "knowledge" | "workshop" | "communications";
+export interface RouteNode { id: string; position: Vec3; layer: "ground" | "platform" | "bridge" | "interior"; }
+export interface RouteEdge { from: string; to: string; speed: number; kind: "walk" | "lift" | "interior"; }
+export const CITY = { width: 1800, depth: 1200, referenceWidth: 600, referenceDepth: 400, grid: 4 };
+export const CAMERA_BOUNDS = { minX: -850, maxX: 850, minZ: -550, maxZ: 550, minDistance: 5, maxDistance: 1500 };
+export const MATERIALS = { concrete: "#b8b5ac", graphite: "#252c32", metal: "#aab4bc", glass: "#708b95", green: "#60714d", light: "#ffe1ad" };
+/** Clockwise order, matching the train tangent and platform side. */
+export const STOPS: Stop[] = ["west", "east", "knowledge", "communications", "workshop"];
+export const TRAIN_FLOOR = 12.08;
+export const distance = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
+export const mix = (a: Vec3, b: Vec3, t: number): Vec3 => a.map((v, i) => v + (b[i] - v) * t) as Vec3;
+/** Three.js Y rotation; train/station local +X points along the track. */
+export function transformPoint(origin: Vec3, yaw: number, p: Vec3): Vec3 {
+ const c = Math.cos(yaw), s = Math.sin(yaw);
+ return [origin[0] + c * p[0] + s * p[2], origin[1] + p[1], origin[2] - s * p[0] + c * p[2]];
}
-export interface RouteEdge {
- from: string;
- to: string;
- speed: number;
+export const RAIL_SEGMENTS = 320;
+export function railPoint(progress: number): Vec3 {
+ const angle = Math.PI * 0.7 - progress * Math.PI * 2;
+ return [500 * Math.cos(angle), 12, -110 + 280 * Math.sin(angle)];
}
-export const CITY = {
- width: 1800,
- depth: 1200,
- referenceWidth: 600,
- referenceDepth: 400,
- grid: 4,
-};
-export const MATERIALS = {
- concrete: "#b8b5ac",
- graphite: "#252c32",
- metal: "#aab4bc",
- glass: "#708b95",
- green: "#60714d",
- light: "#ffe1ad",
+export function railHeading(progress: number): number {
+ const angle = Math.PI * 0.7 - progress * Math.PI * 2;
+ return Math.atan2(280 * Math.cos(angle), 500 * Math.sin(angle));
+}
+export const RAIL_POINTS: Vec3[] = Array.from({ length: RAIL_SEGMENTS + 1 }, (_, i) => railPoint(i / RAIL_SEGMENTS));
+export interface District {
+ id: DistrictId; stop: Stop; labelKey: string;
+ placeId: "civic" | "cli" | "archive" | "skills" | "comms";
+ color: string; x: number; z: number;
+ stationPosition: Vec3; stationYaw: number;
+ buildingPosition: Vec3; buildingRotation: number; workplaces: Vec3[];
+}
+const districtInfo: Record<Stop, { id: DistrictId; color: string; placeId: District["placeId"] }> = {
+ west: { id: "central", color: "#d6b76a", placeId: "civic" },
+ east: { id: "terminal", color: "#54c9e0", placeId: "cli" },
+ knowledge: { id: "knowledge", color: "#799cde", placeId: "archive" },
+ workshop: { id: "workshop", color: "#e7a365", placeId: "skills" },
+ communications: { id: "communications", color: "#65c7b4", placeId: "comms" },
};
-export const DISTRICTS = [
- { id: "central", color: "#d6b76a", x: -120, z: 80 },
- { id: "terminal", color: "#54c9e0", x: 120, z: 80 },
- { id: "knowledge", color: "#799cde", x: -520, z: -260 },
- { id: "workshop", color: "#e7a365", x: 520, z: -260 },
- { id: "communications", color: "#65c7b4", x: 0, z: -440 },
-] as const;
-export const STOPS: Stop[] = ["west", "east"];
-export const stopX = (stop: Stop) => (stop === "west" ? -120 : 120);
-export const otherStop = (stop: Stop): Stop =>
- stop === "west" ? "east" : "west";
-export const NODES: RouteNode[] = STOPS.flatMap((s) => [
- {
- id: `${s}:work`,
- position: [stopX(s), 0, 84] as Vec3,
- layer: "ground" as const,
- },
- {
- id: `${s}:plaza`,
- position: [stopX(s), 0, 40] as Vec3,
- layer: "ground" as const,
- },
- {
- id: `${s}:lift`,
- position: [stopX(s), 0, 16] as Vec3,
- layer: "ground" as const,
- },
- {
- id: `${s}:upper`,
- position: [stopX(s), 12, 16] as Vec3,
- layer: "platform" as const,
- },
- {
- id: `${s}:platform`,
- position: [stopX(s), 12, 8] as Vec3,
- layer: "platform" as const,
- },
-]);
-NODES.push(
- { id: "cross:ground", position: [0, 0, 40], layer: "ground" },
- { id: "cross:bridge", position: [0, 20, 40], layer: "bridge" },
- { id: "bridge:north", position: [0, 20, -40], layer: "bridge" },
- { id: "bridge:south", position: [0, 20, 80], layer: "bridge" },
- { id: "bridge:base", position: [0, 0, 80], layer: "ground" },
-);
-const links: [string, string, number][] = STOPS.flatMap(
- (s) =>
- [
- [`${s}:work`, `${s}:plaza`, 1.28],
- [`${s}:plaza`, `${s}:lift`, 1.28],
- [`${s}:lift`, `${s}:upper`, 2],
- [`${s}:upper`, `${s}:platform`, 1.28],
- ] as [string, string, number][],
-);
-links.push(
- ["west:plaza", "cross:ground", 1.28],
- ["cross:ground", "east:plaza", 1.28],
- ["cross:ground", "bridge:base", 1.28],
- ["bridge:base", "bridge:south", 2],
- ["bridge:south", "cross:bridge", 1.28],
- ["cross:bridge", "bridge:north", 1.28],
-);
-export const EDGES: RouteEdge[] = links.flatMap(([from, to, speed]) => [
- { from, to, speed },
- { from: to, to: from, speed },
-]);
-export const node = (id: string) => NODES.find((n) => n.id === id);
-export const distance = (a: Vec3, b: Vec3) =>
- Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
-export const mix = (a: Vec3, b: Vec3, t: number): Vec3 =>
- a.map((v, i) => v + (b[i] - v) * t) as Vec3;
-
-/** Dijkstra over explicit edges: coincident X/Z never implies a floor change. */
-export function route(
- from: string,
- to: string,
- blocked = new Set<string>(),
-): string[] | null {
- if (!node(from) || !node(to) || blocked.has(to)) return null;
- const costs = new Map([[from, 0]]);
- const previous = new Map<string, string>();
- const visited = new Set<string>();
+export function localWorkplaces(stop: Stop): Vec3[] {
+ const rows = stop === "east" ? [-9, -5, -1, 3, 7, 11] : [-8, -3, 2, 7, 12, 16];
+ return rows.flatMap((z) => [-12, -6, 0, 6, 12].map((x): Vec3 => [x, 0, z]));
+}
+export const DISTRICTS: District[] = STOPS.map((stop, index) => {
+ const info = districtInfo[stop];
+ const stationPosition = railPoint(index / STOPS.length);
+ const stationYaw = railHeading(index / STOPS.length);
+ const p = transformPoint([stationPosition[0], 0, stationPosition[2]], stationYaw, [0, 0, 88]);
+ const buildingPosition: Vec3 = [Math.round(p[0] / 4) * 4, 0, Math.round(p[2] / 4) * 4];
+ return { ...info, stop, labelKey: `society.city.${info.id}`, x: buildingPosition[0], z: buildingPosition[2], stationPosition, stationYaw, buildingPosition, buildingRotation: stationYaw, workplaces: localWorkplaces(stop).map((p) => transformPoint(buildingPosition, stationYaw, p)) };
+});
+export const STATIONS = DISTRICTS;
+export const district = (stop: Stop): District => DISTRICTS.find((d) => d.stop === stop)!;
+export const stopX = (stop: Stop): number => district(stop).stationPosition[0];
+export const otherStop = (stop: Stop): Stop => STOPS[(STOPS.indexOf(stop) + 1) % STOPS.length];
+export type Placements = Record<Stop, Vec3>;
+export const defaultPlacements = (): Placements => Object.fromEntries(DISTRICTS.map((d) => [d.stop, [...d.buildingPosition]])) as Placements;
+export interface Plot { id: string; x: number; z: number; width: number; depth: number; }
+export const PLOTS: Plot[] = DISTRICTS.map((d) => ({ id: d.stop, x: d.x, z: d.z, width: 96, depth: 96 }));
+export function validPlacement(plot: Plot, x: number, z: number, width: number, depth: number, occupied: Plot[]): boolean {
+ if (![x, z, width, depth].every(Number.isFinite) || width <= 0 || depth <= 0 || x % CITY.grid !== 0 || z % CITY.grid !== 0) return false;
+ if (Math.abs(x - plot.x) + width / 2 > plot.width / 2 || Math.abs(z - plot.z) + depth / 2 > plot.depth / 2) return false;
+ if (Math.abs(x) + width / 2 > CITY.width / 2 || Math.abs(z) + depth / 2 > CITY.depth / 2) return false;
+ const d = DISTRICTS.find((candidate) => candidate.stop === plot.id);
+ if (!d) return false;
+ const entrance = transformPoint([x, 0, z], d.buildingRotation, [0, 0, -19]);
+ const plaza = transformPoint([d.stationPosition[0], 0, d.stationPosition[2]], d.stationYaw, [0, 0, 42]);
+ const outward = transformPoint([0, 0, 0], d.stationYaw, [0, 0, 1]);
+ // The building must remain outside its plaza, with a clear four-metre entrance strip.
+ if ((entrance[0] - plaza[0]) * outward[0] + (entrance[2] - plaza[2]) * outward[2] < 8) return false;
+ const minX = Math.min(entrance[0], plaza[0]) - 2, maxX = Math.max(entrance[0], plaza[0]) + 2;
+ const minZ = Math.min(entrance[2], plaza[2]) - 2, maxZ = Math.max(entrance[2], plaza[2]) + 2;
+ return !occupied.some((p) =>
+ (Math.abs(x - p.x) < (width + p.width) / 2 && Math.abs(z - p.z) < (depth + p.depth) / 2) ||
+ (p.x + p.width / 2 > minX && p.x - p.width / 2 < maxX && p.z + p.depth / 2 > minZ && p.z - p.depth / 2 < maxZ));
+}
+export interface SavedCityLayout { version: 2; placements: Placements; }
+/** Earlier preview/island coordinates are explicitly migrated to default city plots. */
+export function restoreLayout(value: unknown): SavedCityLayout {
+ const placements = defaultPlacements();
+ if (!value || typeof value !== "object" || !("version" in value) || value.version !== 2 || !("placements" in value) || !value.placements || typeof value.placements !== "object") return { version: 2, placements };
+ for (const d of DISTRICTS) {
+ const p = (value.placements as Record<string, unknown>)[d.stop];
+ if (Array.isArray(p) && p.length === 3 && p.every((n) => typeof n === "number" && Number.isFinite(n)) && p[1] === 0 && validPlacement(PLOTS.find((plot) => plot.id === d.stop)!, p[0], p[2], 58, 58, [])) placements[d.stop] = [p[0], 0, p[2]];
+ }
+ return { version: 2, placements };
+}
+export interface RouteGraph {
+ nodes: Map<string, RouteNode>; edges: RouteEdge[];
+ outgoing: Map<string, RouteEdge[]>; cache: Map<string, string[] | null>;
+}
+export function createRouteGraph(placements: Placements = defaultPlacements()): RouteGraph {
+ const nodes = new Map<string, RouteNode>();
+ const edges: RouteEdge[] = [];
+ const addNode = (id: string, position: Vec3, layer: RouteNode["layer"]) => nodes.set(id, { id, position, layer });
+ const link = (from: string, to: string, speed: number, kind: RouteEdge["kind"] = "walk") => { edges.push({ from, to, speed, kind }, { from: to, to: from, speed, kind }); };
+ for (const d of DISTRICTS) {
+ const base: Vec3 = [d.stationPosition[0], 0, d.stationPosition[2]];
+ const local = (p: Vec3) => transformPoint(base, d.stationYaw, p);
+ const buildingLocal = (p: Vec3) => transformPoint(placements[d.stop], d.buildingRotation, p);
+ const s = d.stop;
+ addNode(`${s}:platform`, local([0, TRAIN_FLOOR, 4.2]), "platform");
+ addNode(`${s}:upper`, local([0, TRAIN_FLOOR, 15]), "platform");
+ addNode(`${s}:lift`, local([0, 0, 15]), "ground");
+ addNode(`${s}:plaza`, local([0, 0, 42]), "ground");
+ addNode(`${s}:entry`, buildingLocal([0, 0, -19]), "ground");
+ addNode(`${s}:foyer`, buildingLocal([-3, 0, -15]), "interior");
+ link(`${s}:platform`, `${s}:upper`, 1.8);
+ link(`${s}:upper`, `${s}:lift`, 3, "lift");
+ link(`${s}:lift`, `${s}:plaza`, 2.4);
+ link(`${s}:plaza`, `${s}:entry`, 2.4);
+ link(`${s}:entry`, `${s}:foyer`, 1.5, "interior");
+ localWorkplaces(s).forEach((p, index) => {
+ const row = Math.floor(index / 5), aisle = `${s}:aisle:${row}`;
+ if (!nodes.has(aisle)) {
+ addNode(aisle, buildingLocal([-3, 0, p[2] - 1.5]), "interior");
+ link(row === 0 ? `${s}:foyer` : `${s}:aisle:${row - 1}`, aisle, 1.5, "interior");
+ }
+ addNode(`${s}:approach:${index}`, buildingLocal([p[0], 0, p[2] - 1.5]), "interior");
+ addNode(`${s}:work:${index}`, buildingLocal(p), "interior");
+ link(aisle, `${s}:approach:${index}`, 1.5, "interior");
+ link(`${s}:approach:${index}`, `${s}:work:${index}`, 1.5, "interior");
+ });
+ addNode(`${s}:work`, buildingLocal([0, 0, -9]), "interior");
+ link(`${s}:aisle:0`, `${s}:work`, 1.5, "interior");
+ }
+ // The public promenade follows the viaduct outside, without cutting across halls.
+ for (let index = 0; index < STOPS.length; index++) {
+ let previous = `${STOPS[index]}:plaza`;
+ for (let step = 1; step < 16; step++) {
+ const progress = (index + step / 16) / STOPS.length;
+ const p = railPoint(progress), id = `promenade:${index}:${step}`;
+ addNode(id, transformPoint([p[0], 0, p[2]], railHeading(progress), [0, 0, 42]), "ground");
+ link(previous, id, 2.4);
+ previous = id;
+ }
+ link(previous, `${otherStop(STOPS[index])}:plaza`, 2.4);
+ }
+ addNode("cross:ground", [0, 0, 200], "ground");
+ addNode("cross:bridge", [0, 20, 200], "bridge");
+ addNode("bridge:north", [0, 20, 80], "bridge");
+ addNode("bridge:south", [0, 20, 260], "bridge");
+ addNode("bridge:base", [0, 0, 260], "ground");
+ link("promenade:0:8", "cross:ground", 2.4);
+ link("cross:ground", "bridge:base", 2.4);
+ link("bridge:base", "bridge:south", 3, "lift");
+ link("bridge:south", "cross:bridge", 2.4);
+ link("cross:bridge", "bridge:north", 2.4);
+ const outgoing = new Map<string, RouteEdge[]>();
+ for (const e of edges) outgoing.set(e.from, [...(outgoing.get(e.from) ?? []), e]);
+ return { nodes, edges, outgoing, cache: new Map() };
+}
+export const DEFAULT_GRAPH = createRouteGraph();
+export const NODES = [...DEFAULT_GRAPH.nodes.values()];
+export const EDGES = DEFAULT_GRAPH.edges;
+export const node = (id: string, graph: RouteGraph = DEFAULT_GRAPH): RouteNode | undefined => graph.nodes.get(id);
+export interface Walkway { id: string; a: Vec3; b: Vec3; width: number; layer: RouteNode["layer"]; }
+export function graphWalkways(graph: RouteGraph): Walkway[] {
+ return graph.edges.filter((e) => e.from < e.to && e.kind === "walk").map((e) => ({ id: `${e.from}/${e.to}`, a: node(e.from, graph)!.position, b: node(e.to, graph)!.position, width: e.from.includes("platform") || e.to.includes("platform") ? 5 : 6, layer: node(e.from, graph)!.layer }));
+}
+export const WALKWAYS = graphWalkways(DEFAULT_GRAPH);
+export const LIFTS = EDGES.filter((e) => e.kind === "lift" && node(e.from)!.position[1] < node(e.to)!.position[1]).map((e) => ({ id: e.from, a: node(e.from)!.position, b: node(e.to)!.position }));
+/** Indexed adjacency and reusable paths avoid searching the graph on every frame. */
+export function route(from: string, to: string, blocked = new Set<string>(), graph: RouteGraph = DEFAULT_GRAPH): string[] | null {
+ if (!node(from, graph) || !node(to, graph) || blocked.has(to) || blocked.has(from)) return null;
+ const key = `${from}|${to}`;
+ if (blocked.size === 0 && graph.cache.has(key)) { const cached = graph.cache.get(key); return cached ? [...cached] : null; }
+ const costs = new Map([[from, 0]]), previous = new Map<string, string>(), visited = new Set<string>();
while (true) {
- const current = [...costs]
- .filter(([id]) => !visited.has(id))
- .sort((a, b) => a[1] - b[1])[0];
- if (!current) return null;
- const [id, cost] = current;
+ let id: string | undefined, cost = Infinity;
+ for (const [candidate, value] of costs) if (!visited.has(candidate) && value < cost) { id = candidate; cost = value; }
+ if (id === undefined) { if (blocked.size === 0) graph.cache.set(key, null); return null; }
if (id === to) {
const path = [to];
while (previous.has(path[0])) path.unshift(previous.get(path[0])!);
- return path;
+ if (blocked.size === 0) graph.cache.set(key, path);
+ return [...path];
}
visited.add(id);
- for (const edge of EDGES.filter(
- (e) => e.from === id && !blocked.has(e.to),
- )) {
- const next =
- cost +
- distance(node(id)!.position, node(edge.to)!.position) / edge.speed;
- if (next < (costs.get(edge.to) ?? Infinity)) {
- costs.set(edge.to, next);
- previous.set(edge.to, id);
- }
+ for (const edge of graph.outgoing.get(id) ?? []) {
+ if (blocked.has(edge.to)) continue;
+ const next = cost + distance(node(id, graph)!.position, node(edge.to, graph)!.position) / edge.speed;
+ if (next < (costs.get(edge.to) ?? Infinity)) { costs.set(edge.to, next); previous.set(edge.to, id); }
}
}
}
-export function routeSeconds(path: string[] | null): number {
+export function routeSeconds(path: string[] | null, graph: RouteGraph = DEFAULT_GRAPH): number {
if (!path) return Infinity;
- return path
- .slice(1)
- .reduce(
- (sum, id, i) =>
- sum +
- distance(node(path[i])!.position, node(id)!.position) /
- EDGES.find((e) => e.from === path[i] && e.to === id)!.speed,
- 0,
- );
+ return path.slice(1).reduce((sum, id, i) => {
+ const edge = graph.outgoing.get(path[i])?.find((e) => e.to === id);
+ return edge ? sum + distance(node(path[i], graph)!.position, node(id, graph)!.position) / edge.speed : Infinity;
+ }, 0);
}
+/** This maps presentation checkpoints; dispatch never depends on travel. */
export function checkpointStop(checkpoint: string): Stop | null {
- if (
- [
- "desk",
- "hub:cli",
- "hub:models",
- "hub:skills",
- "hub:plugins",
- "hub:desktop",
- ].includes(checkpoint)
- )
- return "east";
- if (
- [
- "meeting",
- "archive",
- "gate",
- "gallery",
- "hub:mcp",
- "hub:web",
- "hub:comms",
- ].includes(checkpoint)
- )
- return "west";
+ if (["desk", "hub:cli", "hub:desktop", "hub:models"].includes(checkpoint)) return "east";
+ if (["archive", "gallery"].includes(checkpoint)) return "knowledge";
+ if (["hub:skills", "hub:plugins"].includes(checkpoint)) return "workshop";
+ if (["hub:mcp", "hub:web", "hub:comms", "gate"].includes(checkpoint)) return "communications";
+ if (["meeting", "civic"].includes(checkpoint)) return "west";
return null;
}
-export interface Plot {
- id: string;
- x: number;
- z: number;
- width: number;
- depth: number;
-}
-export const PLOTS: Plot[] = STOPS.map((s) => ({
- id: s,
- x: stopX(s),
- z: 104,
- width: 64,
- depth: 64,
-}));
-export function validPlacement(
- plot: Plot,
- x: number,
- z: number,
- width: number,
- depth: number,
- occupied: Plot[],
-): boolean {
- if (
- ![x, z, width, depth].every(Number.isFinite) ||
- width <= 0 ||
- depth <= 0 ||
- x % CITY.grid ||
- z % CITY.grid
- )
- return false;
- if (
- Math.abs(x - plot.x) + width / 2 > plot.width / 2 ||
- Math.abs(z - plot.z) + depth / 2 > plot.depth / 2
- )
- return false;
- // The south-facing entrance must retain a clear access strip to the fixed plot entrance.
- if (z - depth / 2 < 72 || Math.abs(x - plot.x) > 16) return false;
- return !occupied.some(
- (p) =>
- Math.abs(x - p.x) < (width + p.width) / 2 &&
- Math.abs(z - p.z) < (depth + p.depth) / 2,
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySession.test.ts b/jarvis/ui/web/frontend/src/components/society/city/citySession.test.ts
new file mode 100644
index 0000000000..81c467ffd3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/citySession.test.ts
@@ -0,0 +1,18 @@
+import { expect, it } from "vitest";
+import { defaultPlacements } from "./cityModel";
+import { addCitizen, setTarget, stepSimulation } from "./citySimulation";
+import { createCitySessions } from "./citySession";
+
+it("retains a physical journey when leaving and reopening the city section", () => {
+ const sessions = createCitySessions();
+ const first = sessions.get("live", defaultPlacements, 0);
+ const person = addCitizen(first.sim, "agent", "west"); setTarget(first.sim, person.id, "east", 1); stepSimulation(first.sim, 10);
+ const position = [...person.position];
+ const reopened = sessions.get("live", defaultPlacements, 50000);
+ expect(reopened).toBe(first); expect(reopened.sim.citizens.get(person.id)!.position).toEqual(position);
+});
+it("keeps demo journeys separate from real agent positions", () => {
+ const sessions = createCitySessions(); const live = sessions.get("live", defaultPlacements, 0), demo = sessions.get("demo", defaultPlacements, 0);
+ addCitizen(demo.sim, "example", "west"); stepSimulation(demo.sim, 50);
+ expect(live.sim.citizens.size).toBe(0); expect(live.sim.time).toBe(0); expect(demo.sim.time).toBeCloseTo(50);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySession.ts b/jarvis/ui/web/frontend/src/components/society/city/citySession.ts
new file mode 100644
index 0000000000..f070aac4eb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/city/citySession.ts
@@ -0,0 +1,17 @@
+import { createCityClock, type CityClock } from "./cityClock";
+import { createSimulation, type CitySimulation } from "./citySimulation";
+import type { Placements } from "./cityModel";
+
+interface Session { sim: CitySimulation; clock: CityClock }
+/** Lazy, browser-local state survives section switches without keeping a canvas alive. */
+export function createCitySessions() {
+ const sessions = new Map<"live" | "demo" | "sample", Session>();
+ return {
+ get(kind: "live" | "demo" | "sample", placements: () => Placements, now: number): Session {
+ let session = sessions.get(kind);
+ if (!session) { session = { sim: createSimulation(placements()), clock: createCityClock(now) }; sessions.set(kind, session); }
+ return session;
+ },
+ };
+}
+export const citySessions = createCitySessions();
diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts
index 6f1b0508f4..6ae4521eab 100644
--- a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts
@@ -1,153 +1,353 @@
import { describe, expect, it } from "vitest";
-import { node, PLOTS, route, validPlacement } from "./cityModel";
import {
- addCitizen,
- advanceHour,
- CAPACITY,
- createSimulation,
- previewCrossing,
- safeDestination,
- setTarget,
- stepSimulation,
- trainAt,
+ CAMERA_BOUNDS, checkpointStop, createRouteGraph, defaultPlacements, DISTRICTS,
+ district, distance, graphWalkways, localWorkplaces, node, PLOTS, RAIL_POINTS,
+ restoreLayout, route, STOPS, transformPoint, validPlacement,
+} from "./cityModel";
+import {
+ addCitizen, advanceHour, cancelJourney, CAPACITY, createSimulation, CYCLE,
+ DWELL, LEG_RIDES, moveBuilding, nextDeparture, previewCrossing, safeDestination,
+ setTarget, setTaskActive, STARTUP_HOLD, stepSimulation, stepWithBudget, trainAt,
+ type CitySimulation, type Citizen,
} from "./citySimulation";
-describe("city reference journeys", () => {
- it("never connects overlapping ground and bridge nodes without the lift", () => {
- expect(node("cross:ground")!.position[0]).toBe(
- node("cross:bridge")!.position[0],
- );
- expect(route("cross:ground", "cross:bridge")).toEqual([
- "cross:ground",
- "bridge:base",
- "bridge:south",
- "cross:bridge",
- ]);
- expect(
- route("cross:ground", "cross:bridge", new Set(["bridge:base"])),
- ).toBeNull();
- });
- it("completes a physical rail journey including boarding and exiting", () => {
- const sim = createSimulation();
- const c = addCitizen(sim, "one", "west");
- setTarget(sim, c.id, "east", 1);
+function task(sim: CitySimulation, id: string, target: Citizen["target"], revision = 1): Citizen {
+ const c = addCitizen(sim, id);
+ setTarget(sim, id, target, revision);
+ setTaskActive(sim, id, true);
+ return c;
+}
+function until(sim: CitySimulation, predicate: () => boolean, timeout = 1200): void {
+ const deadline = sim.time + timeout;
+ while (!predicate() && sim.time < deadline) stepSimulation(sim, 0.1);
+ expect(predicate(), `Condition not reached by ${sim.time.toFixed(1)} seconds`).toBe(true);
+}
+
+describe("city graph and authored layout", () => {
+ it("contains all five functional destinations with the matching scene anchors", () => {
+ expect(DISTRICTS).toHaveLength(5);
+ expect(new Set(DISTRICTS.map((d) => d.stop)).size).toBe(5);
+ for (const d of DISTRICTS) {
+ expect(node(`${d.stop}:entry`)!.position).toEqual(transformPoint(d.buildingPosition, d.buildingRotation, [0, 0, -19]));
+ d.workplaces.forEach((p, i) => expect(node(`${d.stop}:work:${i}`)!.position).toEqual(p));
+ expect(route(`${d.stop}:platform`, `${d.stop}:work:29`)).not.toBeNull();
+ }
+ });
+ it("renders precisely the external graph links and closes its rail ring", () => {
+ const graph = createRouteGraph();
+ for (const path of graphWalkways(graph)) {
+ const [from, to] = path.id.split("/");
+ expect(path.a).toEqual(node(from, graph)!.position);
+ expect(path.b).toEqual(node(to, graph)!.position);
+ }
+ expect(distance(RAIL_POINTS[0], RAIL_POINTS.at(-1)!)).toBeLessThan(1e-8);
+ expect(CAMERA_BOUNDS.minX).toBeGreaterThan(-900);
+ expect(CAMERA_BOUNDS.maxZ).toBeLessThan(600);
+ });
+ it("never changes floors where bridge and ground overlap", () => {
+ expect(node("cross:ground")!.position[0]).toBe(node("cross:bridge")!.position[0]);
+ expect(route("cross:ground", "cross:bridge")).toEqual(["cross:ground", "bridge:base", "bridge:south", "cross:bridge"]);
+ expect(route("cross:ground", "cross:bridge", new Set(["bridge:base"]))).toBeNull();
+ });
+ it("approaches workstations in front of chairs rather than walking through them", () => {
+ const path = route("east:entry", "east:work:4")!;
+ expect(path.at(-2)).toBe("east:approach:4");
+ const p = localWorkplaces("east")[4], d = district("east");
+ expect(node("east:approach:4")!.position).toEqual(transformPoint(d.buildingPosition, d.buildingRotation, [p[0], 0, p[2] - 1.5]));
+ });
+ it("routes semantic checkpoints to the corresponding five districts", () => {
+ expect(checkpointStop("desk")).toBe("east");
+ expect(checkpointStop("hub:cli")).toBe("east");
+ expect(checkpointStop("meeting")).toBe("west");
+ expect(checkpointStop("archive")).toBe("knowledge");
+ expect(checkpointStop("hub:plugins")).toBe("workshop");
+ expect(checkpointStop("hub:web")).toBe("communications");
+ expect(checkpointStop("unknown")).toBeNull();
+ });
+ it("rejects overlap, malformed coordinates and off-grid placements", () => {
+ const p = PLOTS[0];
+ expect(validPlacement(p, p.x, p.z, 58, 58, [])).toBe(true);
+ expect(validPlacement(p, p.x + 1, p.z, 58, 58, [])).toBe(false);
+ expect(validPlacement(p, p.x, p.z, 58, 58, [p])).toBe(false);
+ expect(validPlacement(p, NaN, p.z, 58, 58, [])).toBe(false);
+ expect(validPlacement(p, p.x, p.z, 0, 58, [])).toBe(false);
+ expect(validPlacement(p, p.x + 100, p.z, 58, 58, [])).toBe(false);
+ });
+ it("migrates legacy coordinates and validates each saved plot independently", () => {
+ const defaults = defaultPlacements();
+ expect(restoreLayout({ version: 1, placements: { west: [-120, 0, 104] } }).placements).toEqual(defaults);
+ const changed = { ...defaults, west: [defaults.west[0] + 4, 0, defaults.west[2]], east: [Infinity, 0, 0] };
+ const restored = restoreLayout({ version: 2, placements: changed });
+ expect(restored.placements.west).toEqual(changed.west);
+ expect(restored.placements.east).toEqual(defaults.east);
+ expect(restoreLayout(null).placements).toEqual(defaults);
+ });
+ it("updates the actual entrance route when an empty building is moved", () => {
+ const sim = createSimulation(), d = district("east");
+ const before = node("east:entry", sim.graph)!.position;
+ expect(moveBuilding(sim, "east", [d.x + 4, 0, d.z])).toBe(true);
+ expect(node("east:entry", sim.graph)!.position[0]).toBeCloseTo(before[0] + 4);
+ const c = addCitizen(sim, "inside");
+ c.at = "east:work:0";
+ expect(moveBuilding(sim, "east", [d.x, 0, d.z])).toBe(false);
+ });
+});
+
+describe("physical city journeys", () => {
+ it("boards, rides, alights and operates a real terminal workstation without snapping", () => {
+ const sim = createSimulation(), c = task(sim, "one", "east");
const stages = new Set<string>();
- let last = c.position;
- for (let i = 0; i < 2500; i++) {
- stepSimulation(sim, 0.1);
+ let last = [...c.position] as Citizen["position"];
+ until(sim, () => {
stages.add(c.stage);
- expect(Math.hypot(...c.position.map((v, j) => v - last[j]))).toBeLessThan(
- 1.6,
- );
+ expect(distance(c.position, last)).toBeLessThan(2.8);
last = [...c.position];
- }
- for (const stage of [
- "walking",
- "waiting",
- "boarding",
- "riding",
- "exiting",
- "arrived",
- ])
- expect(stages.has(stage)).toBe(true);
- expect(c.at).toBe("east:work");
+ return c.stage === "working";
+ });
+ for (const stage of ["walking", "waiting", "boarding", "riding", "exiting", "working"]) expect(stages.has(stage), stage).toBe(true);
+ expect(c.atWork).toBe(true);
+ expect(c.at).toBe(`east:work:${c.workIndex}`);
+ expect(c.position).toEqual(node(c.at, sim.graph)!.position);
+ expect(c.heading).toBe(district("east").buildingRotation);
expect(c.seat).toBeNull();
});
- it("reserves capacity and leaves excess passengers for the next departure", () => {
+ it("keeps working intent separate from the physical location", () => {
+ const sim = createSimulation(), c = task(sim, "one", "east");
+ expect(c.taskActive).toBe(true);
+ expect(c.atWork).toBe(false);
+ expect(c.at).toBe("west:plaza");
+ until(sim, () => c.stage === "working");
+ setTaskActive(sim, c.id, false);
+ expect(c.stage).toBe("arrived");
+ expect(c.atWork).toBe(true);
+ });
+ it("crosses the actual platform door only while the metro is stopped", () => {
+ const sim = createSimulation(), c = task(sim, "one", "east");
+ until(sim, () => c.stage === "boarding");
+ let closest = Infinity;
+ until(sim, () => {
+ if (c.stage !== "boarding") return true;
+ const train = trainAt(sim.time);
+ expect(train.stop).toBe("west");
+ expect(train.doorsOpen).toBe(true);
+ closest = Math.min(closest, distance(c.position, transformPoint(train.position, train.heading, [0, 0.08, 2.55])));
+ return false;
+ });
+ expect(closest).toBeLessThan(0.2);
+ expect(c.stage).toBe("riding");
+ });
+ it("reaches every district around the connected city", () => {
+ for (const stop of STOPS) {
+ const sim = createSimulation(), c = task(sim, "one", stop);
+ until(sim, () => c.stage === "working");
+ expect(c.at).toBe(`${stop}:work:0`);
+ }
+ });
+ it("retains passengers through intermediate ring stops", () => {
+ const sim = createSimulation(), c = task(sim, "one", "knowledge");
+ until(sim, () => c.stage === "riding");
+ until(sim, () => trainAt(sim.time).stop === "east");
+ expect(c.stage).toBe("riding");
+ expect(c.alightAt).toBe("knowledge");
+ until(sim, () => c.stage === "working");
+ expect(c.at).toBe("knowledge:work:0");
+ });
+ it("reserves seats and retains a queue when a train fills", () => {
const sim = createSimulation();
- for (let i = 0; i < 12; i++) {
- const c = addCitizen(sim, String(i), "west");
- c.at = "west:platform";
- c.position = [...node(c.at)!.position];
- setTarget(sim, c.id, "east", 1);
+ for (let i = 0; i < CAPACITY + 3; i++) {
+ const c = addCitizen(sim, String(i));
+ c.at = "west:platform"; c.position = [...node(c.at, sim.graph)!.position];
+ setTarget(sim, c.id, "east", 1); setTaskActive(sim, c.id, true);
}
- stepSimulation(sim, 9);
- expect(
- [...sim.citizens.values()].filter((c) => c.seat !== null),
- ).toHaveLength(CAPACITY);
- expect(
- [...sim.citizens.values()].filter((c) => c.stage === "waiting"),
- ).toHaveLength(4);
- stepSimulation(sim, 240);
- expect([...sim.citizens.values()].every((c) => c.at === "east:work")).toBe(
- true,
- );
- });
- it("retargets on a train without snapping and ignores older activity", () => {
+ stepSimulation(sim, 15);
+ const passengers = [...sim.citizens.values()].filter((c) => c.seat !== null);
+ expect(passengers).toHaveLength(CAPACITY);
+ expect(new Set(passengers.map((c) => c.seat)).size).toBe(CAPACITY);
+ expect([...sim.citizens.values()].filter((c) => c.stage === "waiting")).toHaveLength(3);
+ until(sim, () => [...sim.citizens.values()].every((c) => c.stage === "working"));
+ expect(new Set([...sim.citizens.values()].map((c) => c.workIndex)).size).toBe(CAPACITY + 3);
+ });
+ it("misses a departure when there is insufficient time to board", () => {
+ const sim = createSimulation();
+ sim.time = STARTUP_HOLD + DWELL - 1;
+ const c = addCitizen(sim, "one"); c.at = "west:platform"; c.position = [...node(c.at, sim.graph)!.position];
+ c.target = "east"; c.taskActive = true; c.stage = "waiting"; c.alightAt = "east";
+ stepSimulation(sim, 0.2);
+ expect(c.stage).toBe("waiting"); expect(c.seat).toBeNull();
+ until(sim, () => c.stage === "working");
+ });
+ it("leaves a workspace queue for a preview walk without stale queue replanning", () => {
+ const sim = createSimulation();
+ for (let i = 0; i < 31; i++) task(sim, String(i), "west");
+ const c = sim.citizens.get("30")!;
+ until(sim, () => c.waitingForWorkspace);
+ expect(previewCrossing(sim, c.id)).toBe(true);
+ expect(c.waitingForWorkspace).toBe(false);
+ stepSimulation(sim, 1);
+ const before = [...c.position] as Citizen["position"];
+ setTaskActive(sim, c.id, false);
+ stepSimulation(sim, 0.1);
+ expect(distance(c.position, before)).toBeLessThan(0.3);
+ until(sim, () => c.at === "bridge:north");
+ });
+ it("queues a full workplace and reaches a newly vacated desk physically", () => {
const sim = createSimulation();
- const c = addCitizen(sim, "one", "west");
- setTarget(sim, c.id, "east", 1);
- while (c.stage !== "riding" && sim.time < 150) stepSimulation(sim, 0.1);
+ for (let i = 0; i < 31; i++) task(sim, String(i), "west");
+ const waiting = sim.citizens.get("30")!;
+ until(sim, () => waiting.waitingForWorkspace);
+ expect(waiting.stage).toBe("waiting");
+ expect(waiting.atWork).toBe(false);
+ until(sim, () => sim.citizens.get("0")!.stage === "working");
+ cancelJourney(sim, "0", 2);
+ const before = [...waiting.position];
+ stepSimulation(sim, 0.1);
+ expect(distance(waiting.position, before as Citizen["position"])).toBeLessThan(0.3);
+ until(sim, () => waiting.stage === "working");
+ expect(waiting.workIndex).toBe(0);
+ expect(waiting.waitingForWorkspace).toBe(false);
+ expect(waiting.position).toEqual(node("west:work:0", sim.graph)!.position);
+ });
+ it("retargets on board at the next station and ignores older activity", () => {
+ const sim = createSimulation(), c = task(sim, "one", "knowledge");
+ until(sim, () => c.stage === "riding");
+ const p = [...c.position];
+ setTarget(sim, c.id, "west", 3); setTarget(sim, c.id, "knowledge", 2);
+ expect(c.position).toEqual(p); expect(c.target).toBe("west");
+ expect(c.alightAt).toBe("east");
+ until(sim, () => c.stage === "exiting");
+ expect(c.alightAt).toBe("east");
+ until(sim, () => c.stage === "working");
+ expect(c.at).toBe("west:work:0");
+ });
+ it("does not force a passenger off at an intermediate stop for a same-target update", () => {
+ const sim = createSimulation(), c = task(sim, "one", "knowledge");
+ until(sim, () => c.stage === "riding");
+ setTarget(sim, c.id, "knowledge", 2);
+ expect(c.alightAt).toBe("knowledge");
+ });
+ it("defers a late-dwell retarget until a stop with enough time to exit", () => {
+ const sim = createSimulation(), c = task(sim, "one", "knowledge");
+ until(sim, () => trainAt(sim.time).stop === "east" && trainAt(sim.time).remaining < 1);
+ expect(c.stage).toBe("riding");
+ expect(safeDestination(sim, c)).toBe("knowledge");
+ setTarget(sim, c.id, "west", 2);
+ expect(c.alightAt).toBe("knowledge");
+ stepSimulation(sim, 2);
expect(c.stage).toBe("riding");
+ expect(trainAt(sim.time).doorsOpen).toBe(false);
+ until(sim, () => c.stage === "exiting");
+ expect(trainAt(sim.time).stop).toBe("knowledge");
+ until(sim, () => c.stage === "working");
+ expect(c.at).toBe("west:work:0");
+ });
+ it("cancels to a safe station without teleporting or operating an old terminal", () => {
+ const sim = createSimulation(), c = task(sim, "one", "knowledge");
+ until(sim, () => c.stage === "riding");
const before = [...c.position];
- setTarget(sim, c.id, "west", 3);
- setTarget(sim, c.id, "east", 2);
- expect(c.position).toEqual(before);
- expect(c.target).toBe("west");
- stepSimulation(sim, 250);
- expect(c.at).toBe("west:work");
- });
- it("reports a blocked destination and resumes after an updated intent", () => {
- const sim = createSimulation();
- const c = addCitizen(sim, "one", "west");
- sim.blocked.add("east:work");
- setTarget(sim, c.id, "east", 1);
- expect(c.stage).toBe("unreachable");
- sim.blocked.clear();
- setTarget(sim, c.id, "east", 2);
+ cancelJourney(sim, c.id, 2);
+ expect(c.position).toEqual(before); expect(c.taskActive).toBe(false);
+ until(sim, () => c.stage === "arrived");
+ expect(c.at).toBe("east:plaza"); expect(c.atWork).toBe(false);
+ });
+ it("settles at the physical arrival station when work ends while exiting", () => {
+ const sim = createSimulation(), c = task(sim, "one", "east");
+ until(sim, () => c.stage === "exiting");
+ expect(safeDestination(sim, c)).toBe("east");
+ cancelJourney(sim, c.id, 2);
+ until(sim, () => c.stage === "arrived");
+ expect(c.at).toBe("east:plaza");
+ });
+ it("cancels a local approach after its current physical edge", () => {
+ const sim = createSimulation(), c = task(sim, "one", "west");
+ stepSimulation(sim, 1);
+ const p = [...c.position];
+ cancelJourney(sim, c.id, 2);
+ expect(c.position).toEqual(p);
+ expect(c.path.length).toBeLessThanOrEqual(2);
+ until(sim, () => c.stage === "arrived");
+ expect(c.at).toBe("west:plaza");
+ expect(c.workIndex).toBeNull();
+ });
+ it("physically returns to a workstation after cancelling and reactivating", () => {
+ const sim = createSimulation(), c = task(sim, "one", "west");
+ until(sim, () => c.stage === "working");
+ cancelJourney(sim, c.id, 2);
+ stepSimulation(sim, 1);
expect(c.stage).toBe("walking");
+ expect(c.atWork).toBe(false);
+ const p = [...c.position];
+ setTaskActive(sim, c.id, true);
+ expect(c.position).toEqual(p);
+ expect(c.stage).toBe("walking");
+ until(sim, () => c.stage === "working");
+ expect(c.at).toBe("west:work:0");
+ expect(c.position).toEqual(node(c.at, sim.graph)!.position);
+ });
+ it("reports unreachable targets and resumes on a newer intent", () => {
+ const sim = createSimulation();
+ sim.blocked.add("east:entry");
+ const c = task(sim, "one", "east");
+ // The preexisting access leg is completed before the blocked interior is reconsidered.
+ until(sim, () => c.stage === "unreachable");
+ sim.blocked.clear(); setTarget(sim, c.id, "east", 2);
+ until(sim, () => c.stage === "working");
+ });
+ it("walks the preview bridge at its exact deck height", () => {
+ const sim = createSimulation(), c = addCitizen(sim, "one");
+ expect(previewCrossing(sim, c.id)).toBe(true);
+ until(sim, () => c.at === "cross:bridge");
+ expect(c.position[1]).toBe(20);
+ until(sim, () => c.at === "bridge:north");
+ expect(c.stage).toBe("arrived");
});
- it("matches continuous travel when catching up an offscreen interval", () => {
- const a = createSimulation(),
- b = createSimulation();
- for (const sim of [a, b]) {
- addCitizen(sim, "one", "west");
- setTarget(sim, "one", "east", 1);
+ it("does not reset a journey when the same roster citizen is observed again", () => {
+ const sim = createSimulation(), c = task(sim, "one", "east");
+ stepSimulation(sim, 20);
+ const p = [...c.position];
+ expect(addCitizen(sim, c.id)).toBe(c); expect(c.position).toEqual(p);
+ });
+});
+
+describe("train clock and bounded catch-up", () => {
+ it("keeps every train arrival and departure position continuous", () => {
+ let phase = STARTUP_HOLD;
+ for (const duration of LEG_RIDES) {
+ for (const time of [phase, phase + DWELL, phase + DWELL + duration]) expect(distance(trainAt(time - 0.001).position, trainAt(time).position)).toBeLessThan(0.03);
+ phase += DWELL + duration;
}
+ expect(trainAt(STARTUP_HOLD + CYCLE + 1).stop).toBe("west");
+ });
+ it("reserves the occupied block and closes its doors while moving", () => {
+ expect(trainAt(0).reservedBlock).toBe("platform:west");
+ const moving = trainAt(STARTUP_HOLD + DWELL + 10);
+ expect(moving.doorsOpen).toBe(false); expect(moving.reservedBlock).toBe("track:west:east");
+ expect(nextDeparture("west", 0)).toBe(STARTUP_HOLD + DWELL);
+ });
+ it("matches continuous travel when processing a hidden interval", () => {
+ const a = createSimulation(), b = createSimulation();
+ task(a, "one", "knowledge"); task(b, "one", "knowledge");
stepSimulation(a, 90);
for (let i = 0; i < 900; i++) stepSimulation(b, 0.1);
expect(a.citizens.get("one")!.stage).toBe(b.citizens.get("one")!.stage);
- a.citizens
- .get("one")!
- .position.forEach((v, i) =>
- expect(v).toBeCloseTo(b.citizens.get("one")!.position[i], 5),
- );
- });
- it("keeps the train continuous at departure and arrival", () => {
- for (const time of [12, 28, 40, 56])
- expect(
- Math.abs(trainAt(time - 0.001).position[0] - trainAt(time).position[0]),
- ).toBeLessThan(0.02);
- });
- it("walks the preview crossing at its actual deck height", () => {
- const sim = createSimulation();
- const c = addCitizen(sim, "one", "west");
- expect(previewCrossing(sim, c.id)).toBe(true);
- let reachedDeck = false;
- for (let i = 0; i < 3500; i++) {
- stepSimulation(sim, 0.1);
- if (c.at === "cross:bridge") {
- expect(c.position[1]).toBe(20);
- reachedDeck = true;
- }
- }
- expect(reachedDeck).toBe(true);
+ expect(distance(a.citizens.get("one")!.position, b.citizens.get("one")!.position)).toBeLessThan(1e-6);
+ });
+ it("limits catch-up work while retaining every elapsed second", () => {
+ const sim = createSimulation(), reference = createSimulation();
+ task(sim, "one", "knowledge"); task(reference, "one", "knowledge");
+ stepWithBudget(sim, 90, 20);
+ expect(sim.time).toBeCloseTo(2); expect(sim.debt).toBeCloseTo(88);
+ while (sim.debt > 0.00001) stepWithBudget(sim, 0, 20);
+ stepSimulation(reference, 90);
+ expect(distance(sim.citizens.get("one")!.position, reference.citizens.get("one")!.position)).toBeLessThan(1e-6);
});
- it("pauses the day cycle and wraps a full 30 minute day", () => {
+ it("skips empty idle intervals without moving any citizen", () => {
+ const sim = createSimulation(), c = addCitizen(sim, "one");
+ const p = [...c.position];
+ stepWithBudget(sim, 3600, 5);
+ expect(sim.time).toBe(3600); expect(sim.debt).toBe(0); expect(c.position).toEqual(p);
+ });
+ it("pauses and wraps the independent 30-minute daylight cycle", () => {
expect(advanceHour(10, 1800, false)).toBe(10);
expect(advanceHour(10, 300, true)).toBe(10);
});
- it("rejects overlapping, off-grid or unreachable building placement", () => {
- expect(validPlacement(PLOTS[0], -120, 104, 40, 36, [])).toBe(true);
- expect(validPlacement(PLOTS[0], -119, 104, 40, 36, [])).toBe(false);
- expect(validPlacement(PLOTS[0], -120, 84, 40, 36, [])).toBe(false);
- expect(validPlacement(PLOTS[0], -120, 104, 40, 36, [PLOTS[0]])).toBe(false);
- });
-});
-
-
-it("settles at the arrival station when work ends during alighting", () => {
- const sim = createSimulation(); const c = addCitizen(sim, "one", "west");
- sim.time = 30; c.boardingAt = "west"; c.seat = 0; c.stage = "exiting";
- expect(safeDestination(sim, c)).toBe("east");
});
diff --git a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts
index 37991aa2e2..a2527950ba 100644
--- a/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts
+++ b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts
@@ -1,319 +1,311 @@
import {
- distance,
- EDGES,
- mix,
- node,
- otherStop,
- route,
- routeSeconds,
- type Stop,
- type Vec3,
+ createRouteGraph, defaultPlacements, distance, district, mix, node,
+ railHeading, railPoint, RAIL_POINTS, RAIL_SEGMENTS, route, routeSeconds,
+ STOPS, transformPoint, PLOTS, validPlacement,
+ type Placements, type RouteGraph, type Stop, type Vec3,
} from "./cityModel";
-export const DWELL = 12;
-export const RIDE = 16;
-export const CAPACITY = 8;
-export const CYCLE = 2 * (DWELL + RIDE);
-export type JourneyStage =
- | "arrived"
- | "walking"
- | "waiting"
- | "boarding"
- | "riding"
- | "exiting"
- | "unreachable";
+export const DWELL = 18;
+export const CAPACITY = 24;
+export const STARTUP_HOLD = 42;
+const MAX_SPEED = 26;
+const ACCELERATION = 3;
+const STEP = 0.1;
+const BOARD_SPEED = 1.8;
+const CUMULATIVE = RAIL_POINTS.reduce<number[]>((lengths, p, i) => {
+ lengths.push(i ? lengths[i - 1] + distance(RAIL_POINTS[i - 1], p) : 0);
+ return lengths;
+}, []);
+export const LEG_LENGTHS = STOPS.map((_, i) => CUMULATIVE[(i + 1) * RAIL_SEGMENTS / STOPS.length] - CUMULATIVE[i * RAIL_SEGMENTS / STOPS.length]);
+export const LEG_RIDES = LEG_LENGTHS.map((length) => length / MAX_SPEED + MAX_SPEED / ACCELERATION);
+export const RIDE = LEG_RIDES[0];
+export const CYCLE = LEG_RIDES.reduce((sum, duration) => sum + DWELL + duration, 0);
+const PHASES = STOPS.map((_, i) => LEG_RIDES.slice(0, i).reduce((sum, duration) => sum + duration + DWELL, 0));
+export type JourneyStage = "arrived" | "working" | "walking" | "waiting" | "boarding" | "riding" | "exiting" | "unreachable";
export interface TrainState {
- position: Vec3;
- stop: Stop | null;
- next: Stop;
- remaining: number;
- heading: number;
+ position: Vec3; stop: Stop | null; next: Stop; remaining: number; heading: number;
+ doorsOpen: boolean; reservedBlock: string; speed: number;
}
+function sampledProgress(length: number): number {
+ let low = 0, high = CUMULATIVE.length - 1;
+ while (low + 1 < high) {
+ const mid = (low + high) >> 1;
+ if (CUMULATIVE[mid] <= length) low = mid; else high = mid;
+ }
+ return (low + (length - CUMULATIVE[low]) / (CUMULATIVE[high] - CUMULATIVE[low])) / RAIL_SEGMENTS;
+}
+/** A single train holds one ring block at a time; smooth acceleration preserves passengers. */
export function trainAt(time: number): TrainState {
- const t = ((time % CYCLE) + CYCLE) % CYCLE;
- if (t < DWELL)
- return {
- position: [-120, 12, 0],
- stop: "west",
- next: "east",
- remaining: DWELL - t,
- heading: Math.PI / 2,
- };
- if (t < DWELL + RIDE)
- return {
- position: [-120 + (240 * (t - DWELL)) / RIDE, 12, 0],
- stop: null,
- next: "east",
- remaining: DWELL + RIDE - t,
- heading: Math.PI / 2,
- };
- if (t < 2 * DWELL + RIDE)
- return {
- position: [120, 12, 0],
- stop: "east",
- next: "west",
- remaining: 2 * DWELL + RIDE - t,
- heading: Math.PI / 2,
- };
- return {
- position: [120 - (240 * (t - 2 * DWELL - RIDE)) / RIDE, 12, 0],
- stop: null,
- next: "west",
- remaining: CYCLE - t,
- heading: Math.PI / 2,
- };
+ const raw = Math.max(0, time) - STARTUP_HOLD;
+ const t = raw < 0 ? 0 : raw % CYCLE;
+ let leg = STOPS.length - 1;
+ for (let i = 0; i < STOPS.length; i++) if (t < PHASES[i] + DWELL + LEG_RIDES[i] - 1e-9) { leg = i; break; }
+ const stop = STOPS[leg], next = STOPS[(leg + 1) % STOPS.length];
+ const phase = t - PHASES[leg];
+ if (phase < DWELL) {
+ const progress = leg / STOPS.length;
+ const remaining = DWELL - phase + (raw < 0 ? -raw : 0);
+ return { position: railPoint(progress), stop, next, remaining, heading: railHeading(progress), doorsOpen: remaining > 0.4, reservedBlock: `platform:${stop}`, speed: 0 };
+ }
+ const elapsed = phase - DWELL, duration = LEG_RIDES[leg], ramp = MAX_SPEED / ACCELERATION;
+ let travelled: number, speed: number;
+ if (elapsed < ramp) { travelled = ACCELERATION * elapsed * elapsed / 2; speed = ACCELERATION * elapsed; }
+ else if (elapsed > duration - ramp) {
+ const left = duration - elapsed;
+ travelled = LEG_LENGTHS[leg] - ACCELERATION * left * left / 2; speed = ACCELERATION * left;
+ } else { travelled = MAX_SPEED * (elapsed - ramp / 2); speed = MAX_SPEED; }
+ const progress = sampledProgress(CUMULATIVE[leg * RAIL_SEGMENTS / STOPS.length] + Math.max(0, Math.min(LEG_LENGTHS[leg], travelled)));
+ return { position: railPoint(progress), stop: null, next, remaining: duration - elapsed, heading: railHeading(progress), doorsOpen: false, reservedBlock: `track:${stop}:${next}`, speed };
}
-export function nextDeparture(stop: Stop, time: number): number {
- const phase = stop === "west" ? DWELL : 2 * DWELL + RIDE;
- return Math.ceil((time + 8 - phase) / CYCLE) * CYCLE + phase;
+export function nextDeparture(stop: Stop, time: number, boardingSeconds = 12): number {
+ const first = STARTUP_HOLD + PHASES[STOPS.indexOf(stop)] + DWELL;
+ return first + Math.max(0, Math.ceil((time + boardingSeconds + 0.5 - first) / CYCLE)) * CYCLE;
+}
+export function rideSeconds(from: Stop, to: Stop): number {
+ let i = STOPS.indexOf(from), total = 0;
+ while (STOPS[i] !== to) { total += LEG_RIDES[i]; i = (i + 1) % STOPS.length; if (STOPS[i] !== to) total += DWELL; }
+ return total;
}
export interface Citizen {
- id: string;
- position: Vec3;
- at: string;
- target: Stop;
- stage: JourneyStage;
- path: string[];
- edgeTime: number;
- speed: number;
- heading: number;
- seat: number | null;
- boardingAt: Stop | null;
- transition: number;
- transitionFrom: Vec3;
- queued: number;
- revision: number;
- lane: number;
+ id: string; position: Vec3; at: string; target: Stop; stage: JourneyStage;
+ path: string[]; edgeTime: number; speed: number; heading: number;
+ seat: number | null; boardingAt: Stop | null; alightAt: Stop | null;
+ transition: number; transitionFrom: Vec3; transitionPath: Vec3[];
+ queued: number; revision: number; lane: number;
+ taskActive: boolean; atWork: boolean; workIndex: number | null;
+ waitingForWorkspace: boolean;
+ previewTarget: string | null;
}
export interface CitySimulation {
- time: number;
- citizens: Map<string, Citizen>;
- blocked: Set<string>;
+ time: number; citizens: Map<string, Citizen>; blocked: Set<string>;
+ graph: RouteGraph; placements: Placements; debt: number;
+ reservedBlock: string;
+ nextBoardAt: number;
+ nextWorkCheck: number;
}
-export function createSimulation(): CitySimulation {
- return { time: 0, citizens: new Map(), blocked: new Set() };
+export function createSimulation(placements: Placements = defaultPlacements()): CitySimulation {
+ return { time: 0, citizens: new Map(), blocked: new Set(), graph: createRouteGraph(placements), placements, debt: 0, reservedBlock: "platform:west", nextBoardAt: 0, nextWorkCheck: 0 };
}
export function safeDestination(sim: CitySimulation, citizen: Citizen): Stop {
- if (citizen.seat === null) return citizen.position[0] < 0 ? "west" : "east";
- const train = trainAt(sim.time);
- return train.stop && train.stop !== citizen.boardingAt ? train.stop : train.next;
+ if (citizen.seat !== null) {
+ const train = trainAt(sim.time);
+ return citizen.stage === "exiting" && citizen.alightAt ? citizen.alightAt : canAlight(sim, citizen, train) ? train.stop! : train.next;
+ }
+ return STOPS.reduce((best, stop) => distance(citizen.position, node(`${stop}:plaza`, sim.graph)!.position) < distance(citizen.position, node(`${best}:plaza`, sim.graph)!.position) ? stop : best);
}
-export function addCitizen(
- sim: CitySimulation,
- id: string,
- stop: Stop,
-): Citizen {
+export function addCitizen(sim: CitySimulation, id: string, stop: Stop = "west"): Citizen {
+ const existing = sim.citizens.get(id);
+ if (existing) return existing;
const used = new Set([...sim.citizens.values()].map((c) => c.lane));
- let lane = 0;
- while (used.has(lane)) lane++;
- const position = [...node(`${stop}:work`)!.position] as Vec3;
- const c: Citizen = {
- id,
- position,
- at: `${stop}:work`,
- target: stop,
- stage: "arrived",
- path: [],
- edgeTime: 0,
- speed: 0,
- heading: 0,
- seat: null,
- boardingAt: null,
- transition: 0,
- transitionFrom: position,
- queued: sim.time,
- revision: -1,
- lane,
- };
- c.position = routePoint(c, c.at);
- sim.citizens.set(id, c);
- return c;
+ let lane = 0; while (used.has(lane)) lane++;
+ const p = [...node(`${stop}:plaza`, sim.graph)!.position] as Vec3;
+ const c: Citizen = { id, position: p, at: `${stop}:plaza`, target: stop, stage: "arrived", path: [], edgeTime: 0, speed: 0, heading: district(stop).buildingRotation, seat: null, boardingAt: null, alightAt: null, transition: 0, transitionFrom: p, transitionPath: [], queued: sim.time, revision: -1, lane, taskActive: false, atWork: false, workIndex: null, waitingForWorkspace: false, previewTarget: null };
+ c.position = routePoint(sim, c, c.at); sim.citizens.set(id, c); return c;
+}
+function routePoint(sim: CitySimulation, c: Citizen, id: string): Vec3 {
+ const n = node(id, sim.graph)!;
+ if (id.endsWith(":foyer")) {
+ const stop = id.split(":")[0] as Stop;
+ return transformPoint(n.position, district(stop).buildingRotation, [((c.lane % 7) - 3) * 0.45, 0, Math.floor(c.lane / 7) % 5 * 0.45]);
+ }
+ if (n.layer === "interior" || id.endsWith(":entry") || id.includes("bridge") || id.startsWith("cross:")) return [...n.position];
+ const stop = STOPS.find((s) => id.startsWith(`${s}:`));
+ const offset: Vec3 = [((c.lane % 7) - 3) * 0.3, 0, Math.floor(c.lane / 7) % 5 * 0.3];
+ return transformPoint(n.position, stop ? district(stop).stationYaw : 0, offset);
}
-function routePoint(c: Citizen, id: string): Vec3 {
- const p = node(id)!.position;
- return [
- p[0] + ((c.lane % 5) - 2) * 0.7,
- p[1],
- p[2] + ((Math.floor(c.lane / 5) % 6) - 2.5) * 0.7,
- ];
+function assignWorkspace(sim: CitySimulation, c: Citizen): void {
+ const reserved = new Set([...sim.citizens.values()].filter((other) => other.id !== c.id && other.target === c.target && other.workIndex !== null).map((other) => other.workIndex));
+ if (c.workIndex !== null && !reserved.has(c.workIndex)) return;
+ c.workIndex = Array.from({ length: 30 }, (_, i) => i).find((i) => !reserved.has(i)) ?? null;
}
-export function setTarget(
- sim: CitySimulation,
- id: string,
- target: Stop,
- revision: number,
-): void {
+export function setTaskActive(sim: CitySimulation, id: string, active: boolean): void {
const c = sim.citizens.get(id);
- if (!c || revision <= c.revision) return;
+ if (!c || c.taskActive === active) return;
+ c.taskActive = active;
+ if (c.atWork && ["arrived", "working"].includes(c.stage) && c.at.startsWith(`${c.target}:work:`)) { c.stage = active ? "working" : "arrived"; return; }
+ if (!active && c.waitingForWorkspace && c.stage === "waiting") { plan(sim, c); return; }
+ if (active && c.stage === "walking") c.path = c.path.slice(0, 2);
+ if (active && c.stage === "arrived") plan(sim, c);
+}
+export function setTarget(sim: CitySimulation, id: string, target: Stop, revision: number): void {
+ const c = sim.citizens.get(id);
+ if (!c || !STOPS.includes(target) || revision <= c.revision) return;
c.revision = revision;
- c.target = target;
- if (["boarding", "riding", "exiting"].includes(c.stage)) return;
- // Finish the current physical edge before changing direction.
- if (c.stage === "walking" && c.path.length > 1) {
- c.path = c.path.slice(0, 2);
+ if (c.target === target && !c.previewTarget && !["arrived", "unreachable"].includes(c.stage)) return;
+ if (c.target !== target) c.workIndex = null;
+ c.target = target; c.previewTarget = null; c.atWork = false;
+ if (c.stage === "boarding" || c.stage === "riding") {
+ const train = trainAt(sim.time);
+ // Retargeting is an intent change; disembark at the next physical opportunity.
+ c.alightAt = canAlight(sim, c, train) ? train.stop! : train.next;
return;
}
+ if (c.stage === "exiting") return;
+ if (c.stage === "walking" && c.path.length > 1) { c.path = c.path.slice(0, 2); return; }
plan(sim, c);
}
-/** Explicit preview walk, never used to override a live agent's activity. */
+export function cancelJourney(sim: CitySimulation, id: string, revision: number): void {
+ const c = sim.citizens.get(id);
+ if (!c || revision <= c.revision) return;
+ c.taskActive = false;
+ c.workIndex = null;
+ setTarget(sim, id, safeDestination(sim, c), revision);
+ // Cancelling within the current district must also trim a same-target access route.
+ if (c.stage === "walking" && c.path.length > 1) c.path = c.path.slice(0, 2);
+ else if (c.waitingForWorkspace || ["arrived", "working", "unreachable"].includes(c.stage)) plan(sim, c);
+}
export function previewCrossing(sim: CitySimulation, id: string): boolean {
- const citizen = sim.citizens.get(id);
- if (
- !citizen ||
- !["arrived", "waiting", "unreachable"].includes(citizen.stage)
- )
- return false;
- const path = route(citizen.at, "bridge:north", sim.blocked);
+ const c = sim.citizens.get(id);
+ if (!c || !["arrived", "working", "waiting", "unreachable"].includes(c.stage)) return false;
+ const path = route(c.at, "bridge:north", sim.blocked, sim.graph);
if (!path) return false;
- citizen.path = path;
- citizen.edgeTime = 0;
- citizen.stage = "walking";
- return true;
+ c.previewTarget = "bridge:north"; c.atWork = false; c.waitingForWorkspace = false; c.path = path; c.edgeTime = 0; c.stage = "walking"; return true;
+}
+function destination(sim: CitySimulation, c: Citizen): string {
+ if (c.previewTarget) return c.previewTarget;
+ if (!c.taskActive) return `${c.target}:plaza`;
+ assignWorkspace(sim, c);
+ return c.workIndex === null ? `${c.target}:foyer` : `${c.target}:work:${c.workIndex}`;
}
function plan(sim: CitySimulation, c: Citizen): void {
- c.edgeTime = 0;
- c.speed = 0;
- const direct = route(c.at, `${c.target}:work`, sim.blocked);
- const stops: Stop[] = ["west", "east"];
- let selected = direct;
- let best = routeSeconds(direct);
- for (const stop of stops.filter((s) => s !== c.target)) {
- const access = route(c.at, `${stop}:platform`, sim.blocked);
- const exit = route(`${c.target}:platform`, `${c.target}:work`, sim.blocked);
- const reach = sim.time + routeSeconds(access);
- const total =
- nextDeparture(stop, reach) - sim.time + RIDE + 8 + routeSeconds(exit);
- if (total < best) {
- best = total;
- selected = access;
- }
+ c.edgeTime = 0; c.speed = 0; c.atWork = false; c.waitingForWorkspace = false;
+ const targetNode = destination(sim, c);
+ if (c.at === targetNode) {
+ c.path = []; c.atWork = targetNode.includes(":work:");
+ c.waitingForWorkspace = c.taskActive && c.workIndex === null && targetNode === `${c.target}:foyer`;
+ c.stage = c.waitingForWorkspace ? "waiting" : c.atWork && c.taskActive ? "working" : "arrived";
+ c.heading = district(c.target).buildingRotation; return;
}
- if (!selected) {
- c.stage = "unreachable";
- c.path = [];
- return;
+ const direct = route(c.at, targetNode, sim.blocked, sim.graph);
+ let selected = direct, best = routeSeconds(direct, sim.graph), alight: Stop | null = null;
+ if (!c.previewTarget && !sim.blocked.has(targetNode)) {
+ const exit = route(`${c.target}:platform`, targetNode, sim.blocked, sim.graph);
+ for (const stop of STOPS) {
+ if (stop === c.target || !exit) continue;
+ const access = route(c.at, `${stop}:platform`, sim.blocked, sim.graph);
+ if (!access) continue;
+ const reach = sim.time + routeSeconds(access, sim.graph);
+ const total = nextDeparture(stop, reach) - sim.time + rideSeconds(stop, c.target) + 12 + routeSeconds(exit, sim.graph);
+ if (total < best) { best = total; selected = access; alight = c.target; }
+ }
}
+ c.alightAt = alight;
+ if (!selected) { c.stage = "unreachable"; c.path = []; return; }
c.path = selected;
- if (selected.length > 1) {
- c.stage = "walking";
- return;
- }
- if (c.at === `${c.target}:work`) c.stage = "arrived";
- else {
- c.stage = "waiting";
- c.queued = sim.time;
+ if (selected.length > 1) c.stage = "walking";
+ else { c.stage = "waiting"; c.queued = sim.time; }
+}
+function seatLocal(seat: number): Vec3 {
+ return [(seat % 12 - 5.5) * 1.5, 0.08, seat < 12 ? -0.8 : 0.8];
+}
+export function seatPosition(train: TrainState, seat: number): Vec3 { return transformPoint(train.position, train.heading, seatLocal(seat)); }
+function doorPath(train: TrainState, seat: number): Vec3[] {
+ const local = seatLocal(seat);
+ return [[0, 0.08, 4.2], [0, 0.08, 2.55], [0, 0.08, 0], [local[0], 0.08, 0], local].map((p) => transformPoint(train.position, train.heading, p as Vec3));
+}
+function pathLength(points: Vec3[]): number { return points.slice(1).reduce((sum, p, i) => sum + distance(points[i], p), 0); }
+function alightingPath(sim: CitySimulation, c: Citizen, train: TrainState): Vec3[] {
+ return [...doorPath(train, c.seat!).reverse(), routePoint(sim, c, `${train.stop}:platform`)];
+}
+function canAlight(sim: CitySimulation, c: Citizen, train: TrainState): boolean {
+ return train.stop !== null && train.stop !== c.boardingAt && train.remaining >= pathLength(alightingPath(sim, c, train)) / BOARD_SPEED + 0.5;
+}
+function advanceTransition(c: Citizen, dt: number): boolean {
+ c.transition += dt;
+ let travelled = c.transition * BOARD_SPEED;
+ const points = c.transitionPath;
+ for (let i = 1; i < points.length; i++) {
+ const a = points[i - 1], b = points[i], length = distance(a, b);
+ if (travelled < length && length > 1e-8) {
+ c.position = mix(a, b, travelled / length); c.speed = BOARD_SPEED;
+ c.heading = Math.atan2(b[0] - a[0], b[2] - a[2]); return false;
+ }
+ travelled -= length;
}
+ c.position = [...points[points.length - 1]]; c.speed = 0; return true;
}
-function seatPosition(train: TrainState, seat: number): Vec3 {
- return [
- train.position[0] + ((seat % 4) - 1.5) * 1.6,
- 12.3,
- 0.5 + Math.floor(seat / 4) * 1.3,
- ];
+function advanceWalk(sim: CitySimulation, c: Citizen, dt: number): void {
+ let left = dt;
+ while (left > 1e-8 && c.stage === "walking") {
+ const [from, to] = c.path;
+ if (!to) { plan(sim, c); break; }
+ const edge = sim.graph.outgoing.get(from)?.find((e) => e.to === to);
+ if (!edge || (sim.blocked.has(to) && c.edgeTime === 0)) { plan(sim, c); break; }
+ const a = routePoint(sim, c, from), b = routePoint(sim, c, to);
+ const duration = distance(a, b) / edge.speed;
+ const consumed = Math.min(left, Math.max(0, duration - c.edgeTime));
+ c.edgeTime += consumed; left -= consumed;
+ c.position = mix(a, b, duration ? Math.min(1, c.edgeTime / duration) : 1);
+ c.speed = edge.kind === "lift" ? 0 : edge.speed;
+ if (a[0] !== b[0] || a[2] !== b[2]) c.heading = Math.atan2(b[0] - a[0], b[2] - a[2]);
+ if (c.edgeTime + 1e-8 < duration) break;
+ c.at = to; c.path.shift(); c.edgeTime = 0;
+ if (c.path.length < 2) plan(sim, c);
+ }
}
function advance(sim: CitySimulation, dt: number): void {
sim.time += dt;
const train = trainAt(sim.time);
+ sim.reservedBlock = train.reservedBlock;
+ if (sim.time >= sim.nextWorkCheck) {
+ sim.nextWorkCheck = sim.time + 1;
+ for (const c of sim.citizens.values()) if (c.waitingForWorkspace && c.stage === "waiting") plan(sim, c);
+ }
for (const c of sim.citizens.values()) {
- if (c.stage === "walking") {
- const [from, to] = c.path;
- if (!to) {
- plan(sim, c);
- continue;
- }
- const edge = EDGES.find((e) => e.from === from && e.to === to)!;
- const a = routePoint(c, from),
- b = routePoint(c, to);
- c.edgeTime += dt;
- const duration = distance(a, b) / edge.speed;
- c.position = mix(a, b, Math.min(1, c.edgeTime / duration));
- c.speed = a[1] === b[1] ? edge.speed : 0;
- if (a[0] !== b[0] || a[2] !== b[2])
- c.heading = Math.atan2(b[0] - a[0], b[2] - a[2]);
- if (c.edgeTime >= duration) {
- c.at = to;
- c.path.shift();
- c.edgeTime = 0;
- if (c.path.length < 2) plan(sim, c);
- }
- } else if (c.stage === "boarding") {
- c.transition += dt;
- const seat = seatPosition(train, c.seat!);
- c.speed = distance(c.transitionFrom, seat) / 6;
- c.position = mix(c.transitionFrom, seat, Math.min(1, c.transition / 6));
- c.heading = Math.atan2(
- seat[0] - c.transitionFrom[0],
- seat[2] - c.transitionFrom[2],
- );
- if (c.transition >= 6) {
- c.stage = "riding";
- c.speed = 0;
- }
+ if (c.stage === "walking") advanceWalk(sim, c, dt);
+ else if (c.stage === "boarding") {
+ if (advanceTransition(c, dt)) { c.stage = "riding"; c.position = seatPosition(train, c.seat!); }
} else if (c.stage === "riding") {
- c.position = seatPosition(train, c.seat!);
- c.speed = 0;
- if (train.stop && train.stop !== c.boardingAt) {
- c.stage = "exiting";
- c.transition = 0;
- c.transitionFrom = [...c.position];
- }
- } else if (c.stage === "exiting") {
- c.transition += dt;
- const stop = otherStop(c.boardingAt!);
- const platform = routePoint(c, `${stop}:platform`);
- c.speed = distance(c.transitionFrom, platform) / 6;
- c.position = mix(
- c.transitionFrom,
- platform,
- Math.min(1, c.transition / 6),
- );
- c.heading = Math.atan2(
- platform[0] - c.transitionFrom[0],
- platform[2] - c.transitionFrom[2],
- );
- if (c.transition >= 6) {
- c.at = `${stop}:platform`;
- c.seat = null;
- c.boardingAt = null;
- plan(sim, c);
+ c.position = seatPosition(train, c.seat!); c.speed = 0; c.heading = train.heading + Math.PI / 2;
+ if (train.stop && train.stop === c.alightAt && canAlight(sim, c, train)) {
+ const path = alightingPath(sim, c, train);
+ c.stage = "exiting"; c.transition = 0; c.transitionFrom = [...c.position]; c.transitionPath = path;
}
+ } else if (c.stage === "exiting" && advanceTransition(c, dt)) {
+ c.at = `${c.alightAt}:platform`; c.seat = null; c.boardingAt = null;
+ plan(sim, c);
}
}
- const occupied = new Set(
- [...sim.citizens.values()]
- .filter((c) => c.seat !== null)
- .map((c) => c.seat),
- );
- if (train.stop && train.remaining >= 7) {
- for (const c of [...sim.citizens.values()]
- .filter((c) => c.stage === "waiting" && c.at === `${train.stop}:platform`)
- .sort((a, b) => a.queued - b.queued || a.id.localeCompare(b.id))) {
- const seat = Array.from({ length: CAPACITY }, (_, i) => i).find(
- (i) => !occupied.has(i),
- );
- if (seat === undefined) break;
- occupied.add(seat);
- c.seat = seat;
- c.stage = "boarding";
- c.boardingAt = train.stop;
- c.transition = 0;
- c.transitionFrom = [...c.position];
- }
+ if (!train.stop || !train.doorsOpen || sim.time < sim.nextBoardAt) return;
+ if ([...sim.citizens.values()].some((c) => c.stage === "exiting")) return;
+ const occupied = new Set([...sim.citizens.values()].filter((c) => c.seat !== null).map((c) => c.seat));
+ for (const c of [...sim.citizens.values()].filter((c) => c.stage === "waiting" && c.at === `${train.stop}:platform` && sim.time - c.queued >= 0.4).sort((a, b) => a.queued - b.queued || a.id.localeCompare(b.id))) {
+ const seat = Array.from({ length: CAPACITY }, (_, i) => i).find((i) => !occupied.has(i));
+ if (seat === undefined) break;
+ const path = [[...c.position] as Vec3, ...doorPath(train, seat)];
+ if (pathLength(path) / BOARD_SPEED + 0.5 > train.remaining) continue;
+ occupied.add(seat); c.seat = seat; c.stage = "boarding"; c.boardingAt = train.stop;
+ c.transition = 0; c.transitionFrom = [...c.position]; c.transitionPath = path;
+ sim.nextBoardAt = sim.time + 0.35;
+ break;
}
}
-/** Fixed small steps retain physical boarding and route transitions during catch-up. */
+/** Test/offline advance with physical substeps; runtime should use the budgeted driver. */
export function stepSimulation(sim: CitySimulation, seconds: number): void {
if (!Number.isFinite(seconds) || seconds <= 0) return;
let left = seconds;
- while (left > 0.000001) {
- const dt = Math.min(0.1, left);
- advance(sim, dt);
- left -= dt;
- }
+ while (left > 1e-8) { const dt = Math.min(STEP, left); advance(sim, dt); left -= dt; }
}
-export function daylight(hour: number): number {
- return Math.max(0, Math.sin(((hour - 6) / 24) * Math.PI * 2));
+/** Retains elapsed time as debt while bounding catch-up work for one event-loop turn. */
+export function stepWithBudget(sim: CitySimulation, seconds: number, maxSteps = 40): void {
+ if (!Number.isFinite(seconds) || seconds < 0 || !Number.isFinite(maxSteps) || maxSteps < 1) return;
+ sim.debt += seconds;
+ if ([...sim.citizens.values()].every((c) => ["arrived", "working", "unreachable"].includes(c.stage))) {
+ sim.time += sim.debt; sim.debt = 0; sim.reservedBlock = trainAt(sim.time).reservedBlock; return;
+ }
+ for (let i = 0; i < Math.floor(maxSteps) && sim.debt >= STEP - 1e-8; i++) {
+ advance(sim, STEP); sim.debt = Math.max(0, sim.debt - STEP);
+ }
}
-export function advanceHour(hour: number, dt: number, paused: boolean): number {
- return paused ? hour : (hour + (dt * 24) / 1800) % 24;
+/** Occupied interiors cannot be moved under a physical journey. */
+export function moveBuilding(sim: CitySimulation, stop: Stop, position: Vec3): boolean {
+ const plot = PLOTS.find((p) => p.id === stop)!;
+ if (position[1] !== 0 || !validPlacement(plot, position[0], position[2], 58, 58, [])) return false;
+ const interior = (id: string) => id.startsWith(`${stop}:`) && ["entry", "foyer", "aisle", "approach", "work"].includes(id.split(":")[1]);
+ if ([...sim.citizens.values()].some((c) => interior(c.at) || c.path.some(interior))) return false;
+ sim.placements = { ...sim.placements, [stop]: [...position] };
+ sim.graph = createRouteGraph(sim.placements);
+ return true;
}
+export function daylight(hour: number): number { return Math.max(0, Math.sin(((hour - 6) / 24) * Math.PI * 2)); }
+export function advanceHour(hour: number, dt: number, paused: boolean): number { return paused ? hour : ((hour + dt * 24 / 1800) % 24 + 24) % 24; }
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx
index 534ba75cc6..21929e74fc 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx
+++ b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx
@@ -10,7 +10,7 @@
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render, waitFor } from "@testing-library/react";
-import { useRef } from "react";
+import { StrictMode, useRef } from "react";
import { MAX_CONTEXT_RECOVERIES, useWebglSurface } from "@/hooks/useWebglSurface";
import { isWebglLost, reportWebglLost } from "@/lib/graphDimension";
@@ -46,6 +46,22 @@ function Surface({ canvas }: { canvas: HTMLCanvasElement }) {
);
}
+/** Mirrors a renderer that replaces its canvas when the recovery key changes. */
+function ReplacingSurface({ canvases }: { canvases: HTMLCanvasElement[] }) {
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const { generation } = useWebglSurface(hostRef);
+ return (
+ <div
+ ref={(node) => {
+ hostRef.current = node;
+ if (node) node.replaceChildren(canvases[generation]);
+ }}
+ data-testid="host"
+ data-generation={generation}
+ />
+ );
+}
+
/** Fire the event the browser fires when it takes a context away. */
function dropContext(canvas: HTMLCanvasElement): Event {
const event = new Event("webglcontextlost", { cancelable: true });
@@ -69,7 +85,48 @@ describe("useWebglSurface", () => {
view.unmount();
- expect(loseContext).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(loseContext).toHaveBeenCalledTimes(1));
+ });
+
+ it("keeps the live context during StrictMode effect replay and releases it on unmount", async () => {
+ const { canvas, loseContext } = fakeCanvas();
+ const view = render(
+ <StrictMode>
+ <Surface canvas={canvas} />
+ </StrictMode>,
+ );
+
+ // Let any deferred destruction run: replay must have reclaimed this canvas.
+ await act(async () => {
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+ expect(loseContext).not.toHaveBeenCalled();
+ expect(dropContext(canvas).defaultPrevented).toBe(true);
+ await waitFor(() => {
+ expect(view.getByTestId("host").dataset.generation).toBe("1");
+ });
+ expect(loseContext).not.toHaveBeenCalled();
+
+ view.unmount();
+ await waitFor(() => expect(loseContext).toHaveBeenCalledTimes(1));
+ });
+
+ it("releases only the retired canvas when context recovery mounts its replacement", async () => {
+ const retired = fakeCanvas();
+ const replacement = fakeCanvas();
+ const view = render(
+ <StrictMode>
+ <ReplacingSurface canvases={[retired.canvas, replacement.canvas]} />
+ </StrictMode>,
+ );
+
+ dropContext(retired.canvas);
+ await waitFor(() => expect(retired.loseContext).toHaveBeenCalledTimes(1));
+ expect(view.getByTestId("host").firstChild).toBe(replacement.canvas);
+ expect(replacement.loseContext).not.toHaveBeenCalled();
+
+ view.unmount();
+ await waitFor(() => expect(replacement.loseContext).toHaveBeenCalledTimes(1));
});
it("survives a lost context: prevents the default and rebuilds the scene", async () => {
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts
index f37b532631..b11b5accce 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts
@@ -78,6 +78,7 @@ export function useWebglSurface(
): WebglSurface {
const [generation, setGeneration] = useState(0);
const recoveriesRef = useRef(0);
+ const pendingReleasesRef = useRef(new Map<HTMLCanvasElement, number>());
useEffect(() => {
const host = hostRef.current;
@@ -126,6 +127,13 @@ export function useWebglSurface(
if (attempts++ < MAX_ATTACH_FRAMES) frame = requestAnimationFrame(attach);
return;
}
+ // StrictMode replays effects on the same live canvas. Reclaim it before
+ // deferred cleanup can lose the context the renderer is still using.
+ const pendingRelease = pendingReleasesRef.current.get(canvas);
+ if (pendingRelease !== undefined) {
+ window.clearTimeout(pendingRelease);
+ pendingReleasesRef.current.delete(canvas);
+ }
canvas.addEventListener("webglcontextlost", onLost);
canvas.addEventListener("webglcontextrestored", onRestored);
};
@@ -147,7 +155,15 @@ export function useWebglSurface(
// graph ref here would reach the NEXT scene, because React commits a
// rebuilt child BEFORE it runs this cleanup — that mistake left the
// rebuilt map paused and black (2026-08-21).
- releaseWebglContext(canvas);
+ // React's development effect replay is not a real unmount. Give the next
+ // setup one task to reclaim this exact canvas, while retired canvases and
+ // actual unmounts still hand their contexts back to the browser.
+ const retiredCanvas = canvas;
+ const pendingReleases = pendingReleasesRef.current;
+ pendingReleases.set(retiredCanvas, window.setTimeout(() => {
+ pendingReleases.delete(retiredCanvas);
+ releaseWebglContext(retiredCanvas);
+ }, 0));
};
}, [generation, hostRef]);
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index 862190a257..042f57a3d1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -270,8 +270,8 @@
"filter_hint": "Beispiel: {\"data.status\": \"ready\"}. Mit {} wird jede Payload angenommen."
},
"city": {
- "mode": "Stadtvorschau",
- "title": "Zukunftsstadt / Referenz 01",
+ "mode": "Stadt",
+ "title": "Agentenstadt",
"demo": "Demo-Agenten",
"agent_count": "Anzahl Demo-Agenten",
"reference_agent": "Referenzagent",
@@ -287,7 +287,7 @@
"reduced": "Reduzierte Bewegung: Reisen und Tageslauf sind angehalten.",
"feed_error": "Live-Agenten nicht verfügbar. Demo-Agenten bleiben verfügbar.",
"live": "Live-Arbeitsorte",
- "task": "Tatsächliche Aufgabe",
+ "task": "Tatsächlicher Arbeitsstatus",
"travel": "Physische Reise",
"target": "Ziel",
"follow": "Verfolgen",
@@ -296,19 +296,48 @@
"plot": "Referenzplatzierung · 4-m-Raster · nur diese Sitzung",
"open_building": "Arbeitsbereich öffnen",
"close": "Schließen",
- "invalid_plot": "Das Gebäude muss aufs Grundstück passen und der Eingang erreichbar bleiben.",
+ "invalid_plot": "Das Gebäude muss auf das Grundstück passen, einen freien Eingang haben und vor dem Verschieben leer sein.",
"knowledge": "Wissensviertel",
"workshop": "Werkstattviertel",
"communications": "Kommunikationsviertel",
"blockout": "Rohentwurf",
"stage_arrived": "Am Ziel",
"stage_walking": "Unterwegs / Aufzug",
- "stage_waiting": "Wartet am Bahnsteig",
+ "stage_waiting": "Wartet",
"stage_boarding": "Steigt ein",
"stage_riding": "Im Zug",
"stage_exiting": "Steigt aus",
"stage_unreachable": "Ziel nicht erreichbar",
- "bridge_walk": "Brücke begehen"
+ "bridge_walk": "Brücke begehen",
+ "legacy_mode": "Alte Map",
+ "central": "Zentrale",
+ "terminal": "Terminal",
+ "options": "Stadtoptionen",
+ "districts": "Stadtviertel",
+ "city_map": "Verkehrsplan der Stadt",
+ "metro_line": "Metro-Ring",
+ "city_limits": "Erkundung innerhalb der Stadtgrenzen",
+ "catching_up": "Physische Reisen werden synchronisiert…",
+ "demo_target": "Demo-Ziel",
+ "adjust_plot": "Gebäude verschieben",
+ "saved_plot": "Position gespeichert. Wege aktualisiert.",
+ "session_plot": "Position für diese Sitzung geändert; Speicherung ist nicht verfügbar.",
+ "open_terminal": "Terminal-Arbeitsbereich öffnen",
+ "stage_working": "Bedient Arbeitsplatz",
+ "waiting_workspace": "Wartet auf einen Arbeitsplatz",
+ "description_central": "Koordination, Besprechungen und gemeinsame Agentenaufgaben.",
+ "description_terminal": "Computerarbeitsplätze für Kommandozeilen- und Coding-Aufgaben. Öffne den Terminal-Arbeitsbereich, um deine Terminals zu bedienen.",
+ "description_knowledge": "Recherche, Archive und gemeinsames Gedächtnis.",
+ "description_workshop": "Skills, Fertigung und Plugin-Integration.",
+ "description_communications": "Externe Dienste, Browser-Arbeit und Kommunikation.",
+ "exterior": "Außenansicht",
+ "work_floor": "Arbeitsplätze",
+ "sample": "Beispielagenten",
+ "sample_notice": "Keine Live-Agentenliste verfügbar. Hier werden Beispiele gezeigt.",
+ "example_state": "Beispiel-Arbeitsstatus",
+ "subtitle": "Eine vernetzte Stadt für deine Agenten.",
+ "demo_plot": "Beispielposition geändert; dein Stadtlayout bleibt erhalten.",
+ "loading": "Agenten werden geladen…"
},
"triggers": {
"group": "Trigger-Gruppe",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index c5013f9c46..5ad77a769f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -270,8 +270,8 @@
"filter_hint": "Example: {\"data.status\": \"ready\"}. Leave {} to accept every payload."
},
"city": {
- "mode": "City preview",
- "title": "Future city / Reference 01",
+ "mode": "City",
+ "title": "Agent City",
"demo": "Demo agents",
"agent_count": "Demo agent count",
"reference_agent": "Reference agent",
@@ -287,7 +287,7 @@
"reduced": "Reduced motion: journeys and daylight are paused.",
"feed_error": "Live roster unavailable. Demo agents remain available.",
"live": "Live checkpoint feed",
- "task": "Actual task",
+ "task": "Actual work state",
"travel": "Physical journey",
"target": "Destination",
"follow": "Follow",
@@ -296,19 +296,48 @@
"plot": "Reference placement · 4 m grid · session only",
"open_building": "Open workspace",
"close": "Close",
- "invalid_plot": "The building must fit the plot and keep its entrance accessible.",
+ "invalid_plot": "The building must fit its plot, keep a clear entrance, and be empty before moving.",
"knowledge": "Knowledge district",
"workshop": "Workshop district",
"communications": "Communications district",
"blockout": "Blockout",
"stage_arrived": "At destination",
"stage_walking": "Walking / lift",
- "stage_waiting": "Waiting at platform",
+ "stage_waiting": "Waiting",
"stage_boarding": "Boarding",
"stage_riding": "On the train",
"stage_exiting": "Leaving the train",
"stage_unreachable": "Destination unreachable",
- "bridge_walk": "Walk the bridge"
+ "bridge_walk": "Walk the bridge",
+ "legacy_mode": "Legacy map",
+ "central": "Central",
+ "terminal": "Terminal",
+ "options": "City options",
+ "districts": "City districts",
+ "city_map": "City transit map",
+ "metro_line": "Metro ring",
+ "city_limits": "Explore within city limits",
+ "catching_up": "Synchronizing physical journeys…",
+ "demo_target": "Demo destination",
+ "adjust_plot": "Adjust building position",
+ "saved_plot": "Position saved. Routes updated.",
+ "session_plot": "Position updated for this session; storage is unavailable.",
+ "open_terminal": "Open terminal workspace",
+ "stage_working": "Using workstation",
+ "waiting_workspace": "Waiting for a workstation",
+ "description_central": "Coordination, meetings and shared agent operations.",
+ "description_terminal": "Computer workstations for command-line and coding activity. Open the terminal workspace to interact with your terminals.",
+ "description_knowledge": "Research, archives and shared memory.",
+ "description_workshop": "Skills, fabrication and plugin integration.",
+ "description_communications": "External services, browser activity and communications.",
+ "exterior": "Exterior",
+ "work_floor": "Work floor",
+ "sample": "Sample agents",
+ "sample_notice": "No live agent roster is available. These are examples.",
+ "example_state": "Example work state",
+ "subtitle": "A connected city for your agents.",
+ "demo_plot": "Example position changed; your city layout is unchanged.",
+ "loading": "Loading agents…"
},
"triggers": {
"group": "Trigger group",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index 2a40fff8f5..6a2bb1413d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -270,8 +270,8 @@
"filter_hint": "Ejemplo: {\"data.status\": \"ready\"}. Usa {} para aceptar cualquier contenido."
},
"city": {
- "mode": "Vista previa de ciudad",
- "title": "Ciudad del futuro / Referencia 01",
+ "mode": "Ciudad",
+ "title": "Ciudad de agentes",
"demo": "Agentes de prueba",
"agent_count": "Cantidad de agentes de prueba",
"reference_agent": "Agente de referencia",
@@ -287,7 +287,7 @@
"reduced": "Movimiento reducido: viajes y ciclo del día en pausa.",
"feed_error": "La lista en vivo no está disponible. Puedes usar agentes de prueba.",
"live": "Destinos de trabajo en vivo",
- "task": "Tarea real",
+ "task": "Estado real del trabajo",
"travel": "Viaje físico",
"target": "Destino",
"follow": "Seguir",
@@ -296,19 +296,48 @@
"plot": "Ubicación de referencia · Cuadrícula de 4 m · Solo esta sesión",
"open_building": "Abrir espacio de trabajo",
"close": "Cerrar",
- "invalid_plot": "El edificio debe caber en la parcela y mantener accesible su entrada.",
+ "invalid_plot": "El edificio debe caber en su parcela, tener entrada despejada y estar vacío antes de moverlo.",
"knowledge": "Distrito del conocimiento",
"workshop": "Distrito de talleres",
"communications": "Distrito de comunicaciones",
"blockout": "Boceto",
"stage_arrived": "En el destino",
"stage_walking": "Caminando / ascensor",
- "stage_waiting": "Esperando en el andén",
+ "stage_waiting": "Esperando",
"stage_boarding": "Subiendo",
"stage_riding": "En el tren",
"stage_exiting": "Bajando del tren",
"stage_unreachable": "Destino inaccesible",
- "bridge_walk": "Cruzar el puente"
+ "bridge_walk": "Cruzar el puente",
+ "legacy_mode": "Mapa anterior",
+ "central": "Central",
+ "terminal": "Terminal",
+ "options": "Opciones de ciudad",
+ "districts": "Distritos de ciudad",
+ "city_map": "Mapa de transporte urbano",
+ "metro_line": "Anillo de metro",
+ "city_limits": "Explora dentro de los límites urbanos",
+ "catching_up": "Sincronizando viajes físicos…",
+ "demo_target": "Destino de prueba",
+ "adjust_plot": "Mover edificio",
+ "saved_plot": "Posición guardada. Rutas actualizadas.",
+ "session_plot": "Posición actualizada para esta sesión; almacenamiento no disponible.",
+ "open_terminal": "Abrir espacio de terminales",
+ "stage_working": "Usando puesto de trabajo",
+ "waiting_workspace": "Esperando un puesto de trabajo",
+ "description_central": "Coordinación, reuniones y operaciones compartidas.",
+ "description_terminal": "Puestos informáticos para consola y programación. Abre el espacio de terminales para trabajar con ellas.",
+ "description_knowledge": "Investigación, archivos y memoria compartida.",
+ "description_workshop": "Habilidades, fabricación e integración de plugins.",
+ "description_communications": "Servicios externos, navegador y comunicaciones.",
+ "exterior": "Exterior",
+ "work_floor": "Planta de trabajo",
+ "sample": "Agentes de ejemplo",
+ "sample_notice": "No hay lista de agentes en vivo disponible. Se muestran ejemplos.",
+ "example_state": "Estado de ejemplo",
+ "subtitle": "Una ciudad conectada para tus agentes.",
+ "demo_plot": "Posición de ejemplo cambiada; tu ciudad no se modifica.",
+ "loading": "Cargando agentes…"
},
"triggers": {
"group": "Grupo de activación",
diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
index aa2250f09e..8284a31558 100644
--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
@@ -55,7 +55,7 @@ const RUN_PARAM = "run";
* load for someone who only ever reads the ledger.
*/
type AgentsMode = "world" | "ledger" | "city";
-const MODE_KEY = "jarvis.agents.mode";
+const MODE_KEY = "jarvis.agents.mode.v2";
const WorldStage = lazy(() =>
import("@/components/society/world/WorldStage").then((m) => ({ default: m.WorldStage })),
@@ -65,17 +65,18 @@ const CityStage = lazy(() =>
);
function readMode(): AgentsMode {
+ if (!detectWebgl()) return "ledger";
try {
const raw = localStorage.getItem(MODE_KEY);
- if (raw === "world" || raw === "ledger") return raw;
+ if (raw === "city" || raw === "world" || raw === "ledger") return raw;
+ if (localStorage.getItem("jarvis.agents.mode") === "ledger") return "ledger";
} catch {
/* private mode: fall through to the default */
}
- return detectWebgl() ? "world" : "ledger";
+ return "city";
}
function writeMode(mode: AgentsMode): void {
- if (mode === "city") return; // Reference preview never replaces a saved production preference.
try {
localStorage.setItem(MODE_KEY, mode);
} catch {
@@ -94,9 +95,9 @@ function ModeSwitch({ mode, onChange }: { mode: AgentsMode; onChange: (m: Agents
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") },
{ id: "city", label: t("society.city.mode") },
+ { id: "ledger", label: t("society.world.mode_ledger") },
+ { id: "world", label: t("society.city.legacy_mode") },
]}
/>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
index 7f262cd7c1..032afeb1e3 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
@@ -12,7 +12,7 @@
*/
import { lazy, Suspense, useCallback, useMemo, useState } from "react";
-import { useT } from "@/i18n";
+import { useLocaleChunk, useT } from "@/i18n";
import { AgentCardOverlay } from "@/components/society/card/AgentCardOverlay";
import { BuildingCardOverlay } from "@/components/society/card/BuildingCardOverlay";
import { isBuildingPlace, type BuildingPlace } from "@/components/society/card/buildingCards";
@@ -30,6 +30,7 @@ const JarvisAgentsBoard = lazy(() =>
export function SocietyView() {
useModelMenuData();
const t = useT();
+ const cityTextReady = useLocaleChunk("society");
const roster = useSocietyRoster();
const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);
const sample = roster.data?.sample ?? true;
@@ -72,7 +73,7 @@ export function SocietyView() {
<span aria-live="polite">
{t("society.strip.active").replace("{0}", String(activeCount))}
</span>
- <span className="ml-auto">{t("society.strip.world_pending")}</span>
+ <span className="ml-auto">{cityTextReady ? t("society.city.subtitle") : null}</span>
</div>
<div className="relative min-h-0 flex-1">
<CanvasActivity.Provider value={!openAgent && !openPlace && !creating}>
diff --git a/scripts/art/build_city_reference.py b/scripts/art/build_city_reference.py
index e60d6389ff..676c18bf46 100644
--- a/scripts/art/build_city_reference.py
+++ b/scripts/art/build_city_reference.py
@@ -3,8 +3,10 @@
Run with Blender --background --factory-startup --disable-autoexec --python this_file.
The manifest exporter remains the only path from these sources to study GLBs.
"""
-from pathlib import Path
+
import math
+import sys
+from pathlib import Path
import bpy
from mathutils import Vector
@@ -76,60 +78,6 @@ def beam(name, a, b, width, mat):
return obj
-collection("Station")
-box("platform", (0, -8, -0.3), (38, 10, 0.6), CONCRETE)
-box("canopy", (0, -8, 7.6), (44, 15, 0.65), STEEL)
-box("roof_cap", (0, -8, 8), (44.5, 15.5, 0.18), METAL)
-for x in (-15, 15):
- beam("diagonal_column", (x - 4, -10, 0), (x + 2, -8, 7.3), 0.65, STEEL)
- beam("branch_column", (x - 4, -10, 0), (x - 7, -8, 7.3), 0.45, STEEL)
-for y in (-14.8, -1.2):
- box("canopy_light", (0, y, 7.25), (43, 0.1, 0.12), LIGHT)
-for x in range(-18, 19, 6):
- box("rear_glass", (x, -12.5, 2), (5.8, 0.12, 4), GLASS)
-box("boarding_edge", (0, -3.2, 0.03), (36, 0.25, 0.06), LIGHT)
-for x in (-10, 10):
- box("bench", (x, -10, 0.55), (4, 0.7, 0.18), METAL)
- box("bench_back", (x, -10.3, 1), (4, 0.12, 0.8), METAL)
-
-collection("Building")
-box("base", (0, 0, 0.3), (40, 36, 0.6), CONCRETE)
-box("core", (0, 4, 12), (24, 19, 24), STEEL)
-for level in (0, 8, 16):
- box("floor_slab", (0, 0, level + 0.8), (42, 36, 0.6), CONCRETE)
- for x in range(-18, 19, 6):
- box("facade_glass", (x, -15, level + 4.3), (5.8, 0.2, 6.5), GLASS)
- box("mullion", (x - 3, -15.2, level + 4.3), (0.15, 0.4, 7), METAL)
- box("floor_light", (0, -18, level + 0.4), (41, 0.1, 0.12), LIGHT)
-for x in (-18, 18):
- beam("facade_brace", (x, -16, 0), (-x, -16, 24), 0.7, STEEL)
-box("roof", (0, 0, 25), (48, 42, 1.2), STEEL)
-box("roof_edge", (0, -21, 24.8), (47, 0.16, 0.18), LIGHT)
-box("entrance_frame", (0, -17, 2.6), (27, 3, 5.2), METAL)
-box("entrance_glass", (0, -18.6, 2.4), (25, 0.2, 4.8), GLASS)
-for x in (-15, 15):
- box("roof_planter", (x, 0, 26), (5, 25, 0.8), CONCRETE)
- box("roof_planting", (x, 0, 26.6), (4.5, 24.5, 0.5), GREEN)
-
-collection("Train")
-# Open doors on the platform side allow visible physical boarding.
-box("train_floor", (0, 0, 0.15), (19, 5, 0.3), METAL)
-box("train_roof", (0, 0, 3.8), (20, 5.4, 0.3), STEEL)
-box("rear_windows", (0, 2.4, 2.1), (18, 0.1, 2.7), GLASS)
-for x in (-8, 8):
- box("car_end", (x, 0, 1.1), (2, 4.8, 2), METAL)
- box("cab_window", (x, -2.42, 2.5), (2.8, 0.1, 1.7), GLASS)
- box("front_light", (x, -2.52, 0.7), (2.4, 0.08, 0.15), LIGHT)
-box("train_light", (0, -2.7, 3.7), (19, 0.08, 0.1), LIGHT)
-for x in (-6, 6):
- box("door_post", (x, -2.4, 2), (0.15, 0.2, 3.5), METAL)
-
-collection("Tree")
-beam("trunk", (0, 0, 0), (0.3, 0, 5), 0.28, BARK)
-for x, y, z, radius in ((0, 0, 6, 2.5), (-1.2, 0, 5, 1.8), (1.3, 0.4, 5.5, 2), (0, 1, 7, 1.7)):
- bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=2, radius=radius, location=(x, y, z))
- finish(bpy.context.object, "leaf_cluster", GREEN)
-
collection("Citizen")
box("torso", (0, 0, 1.13), (0.42, 0.24, 0.5), CLOTH, 0.08)
box("head", (0, -0.01, 1.59), (0.23, 0.22, 0.29), SKIN, 0.07)
@@ -138,7 +86,19 @@ for x, side in ((-0.12, "l"), (0.12, "r")):
upper = box("leg_" + side, (x, 0, 0.7), (0.16, 0.18, 0.47), CLOTH, 0.05)
lower = box("shin_" + side, (x, 0, 0.26), (0.14, 0.16, 0.47), CLOTH, 0.04)
shoe = box("shoe_" + side, (x, -0.04, 0.08), (0.18, 0.3, 0.16), STEEL, 0.03)
- box("arm_" + side, (x * 2.3, 0, 1.06), (0.13, 0.16, 0.57), CLOTH, 0.04)
+ shoulder = bpy.data.objects.new("Arm_" + side.upper(), None)
+ shoulder.location = (x * 2.3, 0, 1.32)
+ current.objects.link(shoulder)
+ upper_arm = box("upper_arm_" + side, (0, 0, -0.15), (0.13, 0.16, 0.3), CLOTH, 0.04)
+ upper_arm.parent = shoulder
+ elbow = bpy.data.objects.new("Forearm_" + side.upper(), None)
+ elbow.location = (0, 0, -0.3)
+ elbow.parent = shoulder
+ current.objects.link(elbow)
+ forearm = box("forearm_" + side, (0, 0, -0.13), (0.115, 0.14, 0.26), CLOTH, 0.035)
+ forearm.parent = elbow
+ hand = box("hand_" + side, (0, 0, -0.29), (0.1, 0.12, 0.1), SKIN, 0.025)
+ hand.parent = elbow
for frame in range(25):
phase = (frame / 24 + (0.5 if side == "r" else 0)) % 1
# The stance foot moves backward at 1.28 m/s relative to the body.
@@ -147,7 +107,7 @@ for x, side in ((-0.12, "l"), (0.12, "r")):
hip = Vector((x, 0, 0.92))
ankle = Vector((x, foot_y, 0.12 + lift))
axis = ankle - hip
- bend = math.sqrt(max(0, 0.47**2 - (axis.length / 2)**2))
+ bend = math.sqrt(max(0, 0.47**2 - (axis.length / 2) ** 2))
perpendicular = Vector((0, axis.z, -axis.y)).normalized()
knee = (hip + ankle) / 2 + perpendicular * bend
for obj, a, b in ((upper, hip, knee), (lower, knee, ankle)):
@@ -166,6 +126,10 @@ for x, side in ((-0.12, "l"), (0.12, "r")):
obj.animation_data.action = None
box("badge", (0.09, -0.125, 1.26), (0.045, 0.015, 0.07), LIGHT, 0)
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from city_architecture import author_city_architecture # noqa: E402
+
+author_city_architecture()
bpy.context.scene.unit_settings.system = "METRIC"
bpy.context.scene.unit_settings.scale_length = 1
bpy.context.scene.render.fps = 24
diff --git a/scripts/art/city_architecture.py b/scripts/art/city_architecture.py
new file mode 100644
index 0000000000..7fb00aa42d
--- /dev/null
+++ b/scripts/art/city_architecture.py
@@ -0,0 +1,454 @@
+"""Authored metric city kit; helpers accept the runtime's X/right, Y/up, Z/depth."""
+
+import math
+
+import bpy
+from mathutils import Vector
+
+ACTIVE = None
+MATS = {}
+
+
+def xyz(point):
+ return Vector((point[0], -point[2], point[1]))
+
+
+def surface(name, rgb, roughness=0.6, metallic=0, emission=0):
+ mat = bpy.data.materials.new(name)
+ mat.diffuse_color = (*rgb, 1)
+ mat.use_nodes = True
+ shader = mat.node_tree.nodes.get("Principled BSDF")
+ shader.inputs["Base Color"].default_value = (*rgb, 1)
+ shader.inputs["Roughness"].default_value = roughness
+ shader.inputs["Metallic"].default_value = metallic
+ shader.inputs["Emission Color"].default_value = (*rgb, 1)
+ shader.inputs["Emission Strength"].default_value = emission
+ MATS[name] = mat
+ return mat
+
+
+def begin(name):
+ global ACTIVE
+ old = bpy.data.collections.get(name)
+ if old:
+ for obj in list(old.all_objects):
+ bpy.data.objects.remove(obj, do_unlink=True)
+ bpy.data.collections.remove(old)
+ ACTIVE = bpy.data.collections.new(name)
+ bpy.context.scene.collection.children.link(ACTIVE)
+
+
+def assign(obj, name, mat):
+ obj.name = name
+ for group in list(obj.users_collection):
+ group.objects.unlink(obj)
+ ACTIVE.objects.link(obj)
+ if mat:
+ obj.data.materials.append(MATS[mat])
+ return obj
+
+
+def box(name, at, size, mat="Concrete", bevel=0.08):
+ bpy.ops.mesh.primitive_cube_add(size=1, location=xyz(at))
+ obj = bpy.context.object
+ obj.scale = (size[0], size[2], size[1])
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ if bevel:
+ mod = obj.modifiers.new("Authored edge radius", "BEVEL")
+ mod.width = min(bevel, min(size) / 3)
+ mod.segments = 3
+ bpy.ops.object.modifier_apply(modifier=mod.name)
+ return assign(obj, name, mat)
+
+
+def beam(name, a, b, width, mat="Graphite"):
+ delta = xyz(b) - xyz(a)
+ center = (Vector(a) + Vector(b)) / 2
+ obj = box(name, center, (width, delta.length, width), mat)
+ obj.rotation_euler = delta.to_track_quat("Z", "Y").to_euler()
+ return obj
+
+
+def cylinder(name, at, radius, depth, mat="Metal", vertices=24):
+ bpy.ops.mesh.primitive_cylinder_add(
+ vertices=vertices, radius=radius, depth=depth, location=xyz(at)
+ )
+ return assign(bpy.context.object, name, mat)
+
+
+def text_mesh(name, text, at, size, mat="Light"):
+ bpy.ops.object.text_add(location=xyz(at), rotation=(math.pi / 2, 0, 0))
+ obj = bpy.context.object
+ obj.data.body = text
+ obj.data.size = size
+ obj.data.align_x = "CENTER"
+ obj.data.extrude = 0.008
+ obj.data.bevel_depth = 0.002
+ # Text faces runtime -Z, the common building frontage.
+ obj.rotation_euler = (math.pi / 2, 0, math.pi)
+ bpy.ops.object.convert(target="MESH")
+ return assign(bpy.context.object, name, mat)
+
+
+def anchor(name, at):
+ obj = bpy.data.objects.new(name, None)
+ obj.location = xyz(at)
+ ACTIVE.objects.link(obj)
+ obj["city_anchor"] = True
+ return obj
+
+
+def tree(at=(0, 0, 0), scale=1):
+ x, y, z = at
+
+ def p(dx, dy, dz):
+ return (x + dx * scale, y + dy * scale, z + dz * scale)
+
+ beam("Trunk", p(0, 0, 0), p(0.1, 4.2, 0), 0.22 * scale, "Bark")
+ for i, (dx, dy, dz, radius) in enumerate(
+ ((-1, 4.3, 0, 1.7), (1, 5, 0.6, 1.9), (0, 6, 0, 1.7), (0, 4.8, -1.1, 1.4))
+ ):
+ beam("Branch", p(0, 2.8, 0), p(dx, dy, dz), 0.1 * scale, "Bark")
+ bpy.ops.mesh.primitive_ico_sphere_add(
+ subdivisions=2, radius=radius * scale, location=xyz(p(dx, dy, dz))
+ )
+ assign(bpy.context.object, "Foliage", "LeafLight" if i % 2 else "Leaf")
+
+
+def planter(at, width, depth, trees=True):
+ x, y, z = at
+ box("Planter", (x, y + 0.42, z), (width, 0.84, depth), "Concrete", 0.15)
+ box("Soil", (x, y + 0.87, z), (width - 0.4, 0.06, depth - 0.4), "Soil", 0)
+ if trees:
+ tree((x, y + 0.9, z), 0.7)
+
+
+def optimize_static():
+ """Keep dynamic doors and named anchors; batch static surfaces by material."""
+ groups = {}
+ for obj in list(ACTIVE.objects):
+ if obj.type == "MESH" and obj.parent is None:
+ key = tuple(mat.name for mat in obj.data.materials)
+ groups.setdefault(key, []).append(obj)
+ for mats, objects in groups.items():
+ if len(objects) < 2:
+ continue
+ bpy.ops.object.select_all(action="DESELECT")
+ for obj in objects:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = objects[0]
+ bpy.ops.object.join()
+ bpy.context.object.name = f"{ACTIVE.name}_{'_'.join(mats)}"
+
+
+def station():
+ begin("Station")
+ box("Platform", (0, -0.3, 8), (38, 0.6, 10))
+ box("Floating canopy", (0, 7.1, 8), (44, 0.7, 15), "Graphite", 0.25)
+ box("Aluminium roof", (0, 7.55, 8), (44.5, 0.2, 15.6), "Pearl", 0.08)
+ for x in (-15, 15):
+ beam("V column", (x, 0, 10), (x - 3.5, 6.8, 8), 0.42)
+ beam("V column", (x, 0, 10), (x + 3.5, 6.8, 8), 0.42)
+ for z in (0.5, 15.5):
+ box("Linear lighting", (0, 6.69, z), (43, 0.1, 0.1), "Light", 0)
+ for x in range(-18, 19, 6):
+ box("Windbreak", (x, 2, 12.6), (5.7, 4, 0.12), "Glazing")
+ box("Windbreak frame", (x - 2.9, 2, 12.6), (0.12, 4, 0.2), "Metal")
+ for x in range(-17, 18, 2):
+ box("Tactile boarding studs", (x, 0.025, 3.7), (1.7, 0.05, 0.3), "Amber", 0)
+ box("Boarding safety strip", (0, 0.04, 3.2), (37, 0.08, 0.17), "Cyan", 0)
+ for x in (-10, 10):
+ box("Bench seat", (x, 0.48, 10), (4, 0.14, 0.75), "Metal")
+ box("Bench back", (x, 0.9, 10.35), (4, 0.85, 0.1), "Metal")
+ for offset in (-1.4, 1.4):
+ box("Bench base", (x + offset, 0.21, 10), (0.18, 0.42, 0.5), "Graphite")
+ for x in (-10, 10):
+ box("Metro display housing", (x, 4.8, 5.5), (9, 1.5, 0.32), "Graphite")
+ box("Metro display", (x, 4.8, 5.3), (8.6, 1.1, 0.03), "Screen")
+ text_mesh("Destination display", "M1 CITY LINE", (x, 4.5, 5.25), 0.65, "Cyan")
+ anchor("Station_Boarding", (0, 0, 3.2))
+ anchor("Station_Lift", (0, 0, 16))
+ optimize_static()
+
+
+def loft(name, sections, mat):
+ """Eight-sided rounded coach cross section, lofted along the rail axis."""
+ perimeter = [
+ (0.25, -2.0),
+ (0.6, -2.45),
+ (3.2, -2.45),
+ (3.7, -1.9),
+ (3.7, 1.9),
+ (3.2, 2.45),
+ (0.6, 2.45),
+ (0.25, 2.0),
+ ]
+ verts = [xyz((x, y * sy, z * sz)) for x, sy, sz in sections for y, z in perimeter]
+ faces = [tuple(reversed(range(8))), tuple(range(len(verts) - 8, len(verts)))]
+ for ring in range(len(sections) - 1):
+ for i in range(8):
+ j = (i + 1) % 8
+ faces.append((ring * 8 + i, ring * 8 + j, (ring + 1) * 8 + j, (ring + 1) * 8 + i))
+ if sections[-1][0] < sections[0][0]:
+ faces = [tuple(reversed(face)) for face in faces]
+ mesh = bpy.data.meshes.new(name)
+ mesh.from_pydata(verts, [], faces)
+ mesh.update()
+ obj = bpy.data.objects.new(name, mesh)
+ ACTIVE.objects.link(obj)
+ obj.data.materials.append(MATS[mat])
+ bevel = obj.modifiers.new("Coach corner radius", "BEVEL")
+ bevel.width = 0.14
+ bevel.segments = 3
+ bpy.context.view_layer.objects.active = obj
+ bpy.ops.object.modifier_apply(modifier=bevel.name)
+ return obj
+
+
+def train():
+ begin("Train")
+ box("Cabin floor", (0, 0, 0), (18.5, 0.16, 4.65), "Metal", 0.08)
+ box("Coach lower sill", (0, 0.36, -2.35), (17, 0.65, 0.22), "Pearl", 0.12)
+ box("Coach roof", (0, 3.65, 0), (18.3, 0.4, 4.95), "Pearl", 0.18)
+ box("Roof equipment", (0, 3.96, 0), (9, 0.3, 2.7), "Graphite", 0.1)
+ for side in (-1, 1):
+ z = side * 2.4
+ for x in (-5.1, 5.1):
+ box("Coach body side", (x, 0.65, z), (6.5, 1.2, 0.18), "Pearl", 0.08)
+ box("Panoramic window strip", (x, 2.25, z), (6.25, 1.8, 0.09), "Glazing", 0.05)
+ for offset in (-2, 0, 2):
+ box(
+ "Window mullion",
+ (x + offset, 2.24, z + side * 0.06),
+ (0.1, 1.84, 0.06),
+ "Graphite",
+ 0.01,
+ )
+ box("Turquoise identity line", (x, 1.17, z + side * 0.1), (6.6, 0.15, 0.035), "Cyan", 0)
+ box("Upper side belt", (0, 3.3, z), (17, 0.36, 0.14), "Graphite", 0.04)
+ box("Door header", (0, 3.15, z), (3.3, 0.25, 0.25), "Metal", 0.03)
+ for x in (-1.62, 1.62):
+ box("Door gasket", (x, 1.55, z), (0.12, 3.1, 0.2), "Graphite", 0.02)
+ for direction in (-1, 1):
+ loft(
+ "Aerodynamic cab",
+ [
+ (direction * 8.4, 1, 1),
+ (direction * 9.2, 0.97, 0.93),
+ (direction * 10.2, 0.82, 0.66),
+ ],
+ "Pearl",
+ )
+ visor = box(
+ "Cab wraparound windscreen",
+ (direction * 10.24, 2.18, 0),
+ (0.1, 1.52, 3.28),
+ "Graphite",
+ 0.03,
+ )
+ visor.rotation_euler.y = direction * -0.18
+ for z in (-1.25, 1.25):
+ box("LED headlamp", (direction * 10.21, 0.89, z), (0.055, 0.22, 0.54), "Light", 0.04)
+ box("Nose trim", (direction * 10.23, 0.6, 0), (0.04, 0.09, 2.7), "Cyan", 0.01)
+ for x in (-5.8, 5.8):
+ box("Bogie", (x, -0.48, 0), (3.1, 0.8, 3.5), "Graphite", 0.18)
+ for dx in (-0.95, 0.95):
+ for z in (-1.7, 1.7):
+ wheel = cylinder("Wheel", (x + dx, -0.62, z), 0.5, 0.26, "Graphite")
+ wheel.rotation_euler.x = math.pi / 2
+ for side in (-1, 1):
+ for x in (-6, -4, 4, 6):
+ box("Passenger seat", (x, 0.51, side * 1.62), (1.55, 0.18, 0.66), "Upholstery", 0.09)
+ box("Passenger back", (x, 0.99, side * 1.96), (1.55, 0.83, 0.12), "Upholstery", 0.08)
+ beam("Handrail", (-7, 3.02, side * 1.25), (7, 3.02, side * 1.25), 0.07, "Amber")
+ for x in (-2, 2):
+ beam("Grab pole", (x, 0.1, 0), (x, 3.35, 0), 0.065, "Amber")
+ box("Cabin ceiling light", (0, 3.41, 0), (15, 0.07, 0.22), "Light", 0.02)
+ optimize_static()
+ for sign, suffix in ((-1, "Left"), (1, "Right")):
+ parent = anchor(f"Door_Platform_{suffix}", (sign * 0.7, 0, 0))
+ parent["open_offset_x"] = sign * 1.25
+ for name, at, size, mat in (
+ ("Door leaf", (sign * 0.7, 1.5, 2.47), (1.36, 3, 0.12), "Metal"),
+ ("Door glass", (sign * 0.7, 2, 2.55), (1.05, 1.62, 0.025), "Glazing"),
+ ("Door safety light", (sign * 0.7, 2.94, 2.56), (1.1, 0.07, 0.035), "Cyan"),
+ ):
+ obj = box(name, at, size, mat, 0.025)
+ world = obj.matrix_world.copy()
+ obj.parent = parent
+ obj.matrix_world = world
+ anchor("Train_Boarding", (0, 0, 2.55))
+ anchor("Train_Cabin", (0, 0.08, 0))
+
+
+def workstation(x, z, index):
+ box("Work desk", (x, 0.79, z + 0.8), (2.65, 0.12, 1.12), "Metal", 0.05)
+ for dx in (-1.1, 1.1):
+ box("Desk leg", (x + dx, 0.37, z + 0.8), (0.08, 0.74, 0.7), "Graphite", 0.02)
+ box("Monitor stand", (x, 1.07, z + 1.08), (0.12, 0.45, 0.12), "Graphite")
+ box("Ultrawide monitor", (x, 1.58, z + 1.1), (2.28, 0.97, 0.14), "Graphite", 0.05)
+ box(
+ f"Terminal_Screen_{index:02}", (x, 1.58, z + 1.012), (2.12, 0.82, 0.02), "TerminalScreen", 0
+ )
+ for row, width in enumerate((1.45, 0.9, 1.65, 1.1, 0.55)):
+ box(
+ "Code line",
+ (x - 0.87 + width / 2, 1.85 - row * 0.13, z + 0.995),
+ (width, 0.035, 0.015),
+ "Cyan" if row % 2 else "ScreenText",
+ 0,
+ )
+ box("Keyboard", (x - 0.2, 0.88, z + 0.45), (1.02, 0.06, 0.33), "Graphite", 0.02)
+ box("Mouse", (x + 0.65, 0.89, z + 0.45), (0.13, 0.07, 0.2), "Graphite", 0.03)
+ # Park the chair beside the standing workstation, clear of its approach path.
+ box("Chair seat", (x + 1.8, 0.48, z + 0.6), (0.65, 0.15, 0.65), "Upholstery", 0.06)
+ box("Chair back", (x + 1.8, 0.94, z + 0.3), (0.64, 0.85, 0.1), "Upholstery", 0.05)
+ cylinder("Chair pedestal", (x + 1.8, 0.22, z + 0.6), 0.08, 0.44)
+ anchor(f"Workstation_{index:02}", (x, 0, z))
+
+
+def building(name, title, accent, terminal=False):
+ begin(name)
+ box("Ground slab", (0, -0.22, 0), (42, 0.44, 38), "Concrete")
+ box("Rear service core", (0, 15.3, 16), (30, 17.4, 5), "Graphite")
+ # Open ground floor faces the plaza, making desks and agent activity visible.
+ for level in (6.3, 13, 20):
+ box("Cantilever floor", (0, level, 0), (43, 0.55, 38), "Concrete", 0.1)
+ box("Floor edge reveal", (0, level - 0.23, -19.15), (42.6, 0.12, 0.13), accent, 0)
+ if level < 20:
+ for x in range(-18, 19, 6):
+ box("Recessed glazing", (x, level + 3.2, -14), (5.76, 5.7, 0.15), "Glazing")
+ box("Aluminium fin", (x - 3, level + 3.1, -14.25), (0.18, 6.1, 0.58), "Metal")
+ for x in (-20, 20):
+ box("Side glazing", (x, level + 3.2, 0), (0.16, 5.7, 31), "Glazing")
+ for x in (-19.5, 19.5):
+ for z in (-14, 10):
+ beam("Diagonal megaframe", (x, 0, z + 3), (x, 20, z - 5), 0.72)
+ box("Floating roof", (0, 20.8, 0), (48, 1.15, 42), "Graphite", 0.24)
+ box("Roof crown", (0, 21.48, 0), (48.2, 0.22, 42.2), "Pearl", 0.08)
+ box("Roof perimeter light", (0, 20.23, -21.04), (47, 0.1, 0.08), "Light", 0)
+ box("Arrival canopy", (0, 5.7, -19.5), (36, 0.45, 6.2), "Graphite", 0.1)
+ text_mesh("Building identity", title, (0, 6.9, -19.4), 1.65, accent)
+ for x in (-17, 17):
+ planter((x, 21.62, 1), 4, 26)
+ anchor("Building_Entrance", (0, 0, -19))
+ if terminal:
+ for row, z in enumerate((-9, -5, -1, 3, 7, 11)):
+ for col, x in enumerate((-12, -6, 0, 6, 12)):
+ workstation(x, z, row * 5 + col)
+ for x in (-16.5, 16.5):
+ for z in (-4, 2, 8):
+ box("Server cabinet", (x, 1.9, z), (1.8, 3.8, 1.8), "Graphite")
+ for level in range(10):
+ box(
+ "Server status",
+ (x, 0.4 + level * 0.3, z - 0.92),
+ (1.3, 0.045, 0.03),
+ "Cyan",
+ 0,
+ )
+ text_mesh("Terminal command sign", ">_", (0, 15, -14.35), 4.5, "Cyan")
+ else:
+ # Reception stays beside the entry-to-work aisle.
+ box("Reception desk", (-12, 1, -13), (10, 2, 2.4), "Pearl", 0.25)
+ box("Reception trim", (-12, 1.1, -14.23), (9.5, 0.2, 0.05), accent, 0)
+ for row, z in enumerate((-8, -3, 2, 7, 12, 16)):
+ for col, x in enumerate((-12, -6, 0, 6, 12)):
+ anchor(f"Interaction_{row * 5 + col:02}", (x, 0, z))
+ for x in (-17, 17):
+ planter((x, 0, 4), 4, 5)
+ box("Mission wall", (0, 3.1, 18.35), (25, 4.2, 0.1), "Screen")
+ for x in range(-10, 11, 5):
+ box("Mission column", (x, 3.1, 18.25), (3.6, 3.7, 0.04), accent)
+ optimize_static()
+
+
+def landmark(name, title, accent, height):
+ building(name, title, accent)
+ # Roof structures establish distinct silhouettes at city viewing distance.
+ if name == "Knowledge":
+ for i in range(3):
+ box(
+ "Archive terrace", (0, 26 + i * 6, i * 3), (30 - i * 7, 4, 23 - i * 4), "Pearl", 0.3
+ )
+ box(
+ "Archive glazing",
+ (0, 26 + i * 6, -11.6 + i * 5),
+ (29 - i * 7, 2.8, 0.12),
+ "Glazing",
+ )
+ elif name == "Fabrication":
+ for x in (-10, 10):
+ box("Fabrication gantry", (x, 28, 0), (3, 13, 21), "Graphite")
+ box("Gantry beam", (0, 34, 0), (30, 3, 5), accent)
+ beam("Fabrication tool", (0, 32, 0), (0, 24, 0), 1.2, "Metal")
+ else:
+ for x in (-8, 8):
+ box("Comms spire", (x, 21 + height / 2, 3), (7, height, 9), "Graphite")
+ box("Comms light", (x, 21 + height / 2, -1.6), (0.26, height - 2, 0.1), accent)
+ for level in (35, 45, 55):
+ box("Sky connection", (0, level, 3), (24, 1, 5), "Metal")
+ optimize_static()
+
+
+def author_city_architecture():
+ surface("Concrete", (0.48, 0.46, 0.42), 0.82)
+ surface("Graphite", (0.021, 0.029, 0.036), 0.4, 0.5)
+ surface("Metal", (0.4, 0.46, 0.5), 0.32, 0.7)
+ surface("Pearl", (0.76, 0.79, 0.77), 0.34, 0.35)
+ surface("Glazing", (0.052, 0.13, 0.17), 0.16, 0.35)
+ surface("Light", (1, 0.73, 0.4), 0.4, 0, 1.1)
+ surface("Cyan", (0.07, 0.68, 0.83), 0.4, 0.1, 0.7)
+ surface("Gold", (0.8, 0.54, 0.19), 0.36, 0.4, 0.25)
+ surface("Blue", (0.19, 0.34, 0.8), 0.4, 0.15, 0.4)
+ surface("Orange", (0.9, 0.3, 0.065), 0.4, 0.1, 0.35)
+ surface("Teal", (0.09, 0.64, 0.42), 0.4, 0.15, 0.35)
+ surface("Amber", (0.86, 0.56, 0.09), 0.55)
+ surface("Screen", (0.008, 0.023, 0.026), 0.27)
+ surface("TerminalScreen", (0.008, 0.045, 0.052), 0.27, 0, 0.1)
+ surface("ScreenText", (0.45, 0.92, 0.65), 0.5, 0, 0.65)
+ surface("Upholstery", (0.04, 0.2, 0.24), 0.85)
+ surface("Leaf", (0.095, 0.19, 0.055), 0.9)
+ surface("LeafLight", (0.19, 0.28, 0.09), 0.9)
+ surface("Bark", (0.11, 0.065, 0.03), 0.95)
+ surface("Soil", (0.055, 0.04, 0.027), 1)
+ station()
+ train()
+ building("Building", "TERMINAL / COMPUTE", "Cyan", terminal=True)
+ building("Central", "CENTRAL / CIVIC HALL", "Gold")
+ landmark("Knowledge", "KNOWLEDGE / ARCHIVE", "Blue", 18)
+ landmark("Fabrication", "FABRICATION / LAB", "Orange", 18)
+ landmark("Communications", "COMMUNICATIONS", "Teal", 44)
+ begin("Tree")
+ tree()
+ optimize_static()
+ for name, height, width in (
+ ("SkylineOffice", 36, 26),
+ ("SkylineTower", 76, 24),
+ ("SkylineResidence", 24, 34),
+ ):
+ begin(name)
+ box("Foundation", (0, 0.3, 0), (width + 2, 0.6, 26), "Concrete", 0)
+ box("Facade mass", (0, height / 2, 0), (width, height, 24), "Glazing", 0)
+ for y in range(3, height, 4):
+ box("Floor belt", (0, y, 0), (width + 0.5, 0.45, 24.5), "Concrete", 0)
+ for x in range(-width // 2, width // 2 + 1, 5):
+ for z in (-12.1, 12.1):
+ box("Facade fin", (x, height / 2, z), (0.26, height, 0.4), "Metal", 0)
+ box("Roof cap", (0, height + 0.4, 0), (width + 1.5, 0.8, 25.5), "Concrete", 0)
+ if name == "SkylineTower":
+ box("Penthouse", (0, height + 5, 0), (width - 8, 10, 18), "Glazing", 0)
+ box("Crown", (0, height + 10.4, 0), (width - 6, 0.8, 20), "Metal", 0)
+ if name == "SkylineResidence":
+ for y in range(4, height, 4):
+ for x in (-11, 0, 11):
+ box("Balcony", (x, y, -13.5), (8, 0.35, 3.5), "Concrete", 0)
+ box("Balcony balustrade", (x, y + 0.75, -15.1), (8, 1.1, 0.12), "Glazing", 0)
+ optimize_static()
+ begin("Streetlamp")
+ cylinder("Foot", (0, 0.06, 0), 0.32, 0.12, "Graphite", 16)
+ beam("Light mast", (0, 0, 0), (0, 7, 0), 0.14, "Graphite")
+ beam("Light arm", (0, 7, 0), (1.8, 7.3, 0), 0.13, "Graphite")
+ box("Luminaire", (1.55, 7.25, 0), (1.1, 0.12, 0.4), "Metal", 0.03)
+ box("Light panel", (1.55, 7.17, 0), (0.9, 0.03, 0.3), "Light", 0)
+ optimize_static()
diff --git a/scripts/art/compose_city_asset_gallery.py b/scripts/art/compose_city_asset_gallery.py
new file mode 100644
index 0000000000..2d8da4a15d
--- /dev/null
+++ b/scripts/art/compose_city_asset_gallery.py
@@ -0,0 +1,115 @@
+"""Assemble individually rendered Blender PNGs into a portable review index."""
+
+import csv
+import html
+import json
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+ROOT = Path(__file__).resolve().parents[2]
+STUDY = ROOT / "art/studies/city-realism-study"
+GALLERY = STUDY / "render-gallery"
+
+
+def main():
+ reports = json.loads((GALLERY / "coverage.json").read_text(encoding="utf-8"))
+ expected_legacy = list(csv.DictReader((STUDY / "asset-inventory.csv").open(encoding="utf-8")))
+ expected_study = json.loads((STUDY / "study.json").read_text(encoding="utf-8"))["assets"]
+ expected = {f"legacy/{Path(row['path']).stem}" for row in expected_legacy}
+ expected.update(f"study/{asset['id']}" for asset in expected_study)
+ missing = expected - reports.keys()
+ if missing:
+ raise SystemExit(f"Missing gallery entries: {sorted(missing)}")
+ font = ImageFont.load_default(size=17)
+ cards = []
+ for group in ("study", "legacy"):
+ entries = [(key, value) for key, value in reports.items() if key.startswith(group + "/")]
+ entries.sort()
+ for page in range(0, len(entries), 20):
+ subset = entries[page : page + 20]
+ sheet = Image.new("RGB", (1600, 360 * ((len(subset) + 4) // 5)), "#172129")
+ draw = ImageDraw.Draw(sheet)
+ for index, (key, value) in enumerate(subset):
+ if value["status"] == "failed":
+ raise SystemExit(f"Failed render: {key}")
+ image_path = STUDY / value["render"]
+ with Image.open(image_path) as original:
+ thumbnail = original.convert("RGB").resize((312, 312), Image.Resampling.LANCZOS)
+ x, y = (index % 5) * 320, (index // 5) * 360
+ sheet.paste(thumbnail, (x + 4, y + 4))
+ draw.text((x + 8, y + 321), key.split("/", 1)[1], fill="#eef4f7", font=font)
+ draw.text(
+ (x + 8, y + 341), f"{value['triangles']:,} tris", fill="#9bb2bf", font=font
+ )
+ sheet.save(GALLERY / f"contact-{group}-{page // 20 + 1:02}.jpg", quality=92)
+ for key, value in entries:
+ render = Path(value["render"]).relative_to("render-gallery").as_posix()
+ caption = html.escape(key.split("/", 1)[1])
+ cards.append(
+ f'<figure data-group="{group}"><a href="{render}">'
+ f'<img src="{render}" loading="lazy" alt="{caption}"></a>'
+ f"<figcaption>{caption}<small>{value['triangles']:,} triangles · "
+ f"{value['meshes']} meshes</small>"
+ f"<small>{html.escape(value['visualization'])}</small></figcaption></figure>"
+ )
+ page = """<!doctype html><html lang="en"><meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Future City · Individual Asset Review</title><style>
+body{margin:0;background:#121a20;color:#e8f0f4;font:16px/1.6 system-ui}
+header{padding:48px max(24px,5vw);max-width:1100px}
+h1{font-size:clamp(28px,4vw,52px);line-height:1.12;margin:0 0 20px}
+p{color:#b4c7d1}nav{display:flex;gap:8px}
+button{font:inherit;border:1px solid #56717d;background:#21343e;color:inherit;
+border-radius:8px;padding:8px 18px;cursor:pointer}
+main{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));
+gap:20px;padding:0 max(24px,5vw) 48px}
+figure{margin:0;background:#1e2a32;border-radius:10px;overflow:hidden}
+img{display:block;width:100%;aspect-ratio:1}figcaption{padding:14px}
+small{display:block;color:#aac0cd}a{color:#79d8e5}[hidden]{display:none!important}
+</style><header><h1>Future City<br>Individual Asset Review</h1>
+<p>Every catalog entry is rendered separately from its GLB in Blender EEVEE.
+New city models are authored study assets. Legacy images document the existing
+inventory; they are not redesigned replacements. Animation-only GLBs display
+their skeletons as review aids.</p><p>Coverage: COVERAGE. Technical rendering is
+not a visual approval or a runtime performance measurement.</p><nav>
+<button onclick="filter('study')">New city assets</button>
+<button onclick="filter('legacy')">Legacy inventory</button>
+<button onclick="filter('all')">All renders</button></nav></header><main>CARDS</main>
+<script>function filter(group){document.querySelectorAll('figure').forEach(
+el=>el.hidden=group!=='all'&&el.dataset.group!==group)}filter('study')</script></html>"""
+ page = page.replace(
+ "COVERAGE", f"{len(expected_study)} city assets and {len(expected_legacy)} legacy assets"
+ )
+ page = page.replace("CARDS", "\n".join(cards))
+ (GALLERY / "index.html").write_text(page, encoding="utf-8")
+ summary = {
+ "legacy_expected": len(expected_legacy),
+ "study_expected": len(expected_study),
+ "rendered": len(expected),
+ "missing": [],
+ "source": "coverage.json",
+ "art_approval": "pending visual runtime review",
+ }
+ (GALLERY / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
+ with (STUDY / "reference-inventory.csv").open("w", newline="", encoding="utf-8") as stream:
+ writer = csv.writer(stream)
+ writer.writerow(["asset", "source", "export", "bytes", "meshes", "triangles", "status"])
+ for asset in expected_study:
+ report = reports[f"study/{asset['id']}"]
+ writer.writerow(
+ [
+ asset["id"],
+ asset["source"],
+ asset["export"],
+ (STUDY / asset["export"]).stat().st_size,
+ report["meshes"],
+ report["triangles"],
+ "authored study; individual Blender render available",
+ ]
+ )
+ print(json.dumps(summary))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/art/render_city_asset_gallery.py b/scripts/art/render_city_asset_gallery.py
new file mode 100644
index 0000000000..f6e0c5032d
--- /dev/null
+++ b/scripts/art/render_city_asset_gallery.py
@@ -0,0 +1,242 @@
+"""Render every inventoried GLB individually in Blender, with source hashes.
+
+Run headlessly with --factory-startup --disable-autoexec --python this_file.
+Optional script arguments: --group study|legacy|all, --limit N, --force.
+The original assets are read only; animation-only assets get a labeled skeleton
+visualization because their GLB deliberately contains no renderable geometry.
+"""
+
+import argparse
+import csv
+import hashlib
+import json
+import struct
+import sys
+from pathlib import Path
+
+import bpy
+from mathutils import Vector
+
+ROOT = Path(__file__).resolve().parents[2]
+STUDY = ROOT / "art/studies/city-realism-study"
+GALLERY = STUDY / "render-gallery"
+
+
+def digest(path):
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def material(name, color):
+ mat = bpy.data.materials.new(name)
+ mat.diffuse_color = (*color, 1)
+ mat.use_nodes = True
+ mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (*color, 1)
+ return mat
+
+
+def light(name, location, power, size, color):
+ data = bpy.data.lights.new(name, "AREA")
+ data.energy = power
+ data.shape = "DISK"
+ data.size = size
+ data.color = color
+ obj = bpy.data.objects.new(name, data)
+ bpy.context.scene.collection.objects.link(obj)
+ obj.location = location
+ obj.rotation_euler = (-Vector(location)).to_track_quat("-Z", "Y").to_euler()
+
+
+def render_asset(source, target, detail=False):
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=str(source))
+ bpy.context.scene.frame_set(0)
+ if detail and source.stem == "train":
+ for name, offset in (("Door_Platform_Left", -1.25), ("Door_Platform_Right", 1.25)):
+ door = bpy.data.objects.get(name)
+ if door is not None:
+ door.location.x += offset
+ originals = [obj for obj in bpy.context.scene.objects if obj.visible_get()]
+ kind = "asset geometry"
+ if not any(obj.type == "MESH" for obj in originals):
+ kind = "animation library; skeleton visualization"
+ mat = material("Skeleton review aid", (0.08, 0.53, 0.67))
+ for armature in [obj for obj in originals if obj.type == "ARMATURE"]:
+ for bone in armature.data.bones:
+ a = armature.matrix_world @ bone.head_local
+ b = armature.matrix_world @ bone.tail_local
+ delta = b - a
+ if delta.length < 0.001:
+ continue
+ bpy.ops.mesh.primitive_cylinder_add(
+ vertices=8,
+ radius=max(delta.length * 0.08, 0.008),
+ depth=delta.length,
+ location=(a + b) / 2,
+ )
+ obj = bpy.context.object
+ obj.name = "Review skeleton bone"
+ obj.rotation_euler = delta.to_track_quat("Z", "Y").to_euler()
+ obj.data.materials.append(mat)
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ meshes = [obj for obj in bpy.context.scene.objects if obj.type == "MESH" and obj.visible_get()]
+ bounds = []
+ for obj in meshes:
+ evaluated = obj.evaluated_get(depsgraph)
+ mesh = evaluated.to_mesh()
+ try:
+ bounds.extend(evaluated.matrix_world @ vertex.co for vertex in mesh.vertices)
+ finally:
+ evaluated.to_mesh_clear()
+ if not bounds:
+ raise ValueError(f"No reviewable mesh or skeleton in {source.name}")
+ low = Vector(tuple(min(point[axis] for point in bounds) for axis in range(3)))
+ high = Vector(tuple(max(point[axis] for point in bounds) for axis in range(3)))
+ center = (low + high) / 2
+ dimensions = high - low
+ extent = max(dimensions)
+ ground = material("Gallery ground", (0.16, 0.18, 0.2))
+ bpy.ops.mesh.primitive_plane_add(
+ size=extent * 200, location=(center.x, center.y, low.z - extent * 0.005)
+ )
+ bpy.context.object.data.materials.append(ground)
+ camera_data = bpy.data.cameras.new("Asset review camera")
+ camera = bpy.data.objects.new("Asset review camera", camera_data)
+ bpy.context.scene.collection.objects.link(camera)
+ # City fronts are runtime -Z = Blender +Y. Legacy figures use the opposite.
+ front = 1 if source.parent == STUDY / "exports" else -1
+ direction = Vector((1.15, front * 1.65, 1.05)).normalized()
+ if source.stem == "building":
+ direction = Vector((0.65, 2.4, 0.62)).normalized()
+ if source.stem == "train":
+ direction = Vector((1.3, -2.4, 1.2)).normalized()
+ if source.stem == "station":
+ direction = Vector((1.1, 1.8, 0.45)).normalized()
+ camera.location = center + direction * extent * 3.2
+ camera.rotation_euler = (center - camera.location).to_track_quat("-Z", "Y").to_euler()
+ camera_data.type = "ORTHO"
+ view_rotation = camera.rotation_euler.to_matrix().transposed()
+ projected = [view_rotation @ (p - center) for p in bounds]
+ camera_data.ortho_scale = (
+ max(
+ max(p.x for p in projected) - min(p.x for p in projected),
+ max(p.y for p in projected) - min(p.y for p in projected),
+ )
+ * 1.3
+ )
+ if detail and source.stem == "building":
+ target_point = Vector((0, 0, 1.8))
+ camera.location = (9, 42, 6.2)
+ camera.rotation_euler = (target_point - camera.location).to_track_quat("-Z", "Y").to_euler()
+ camera_data.ortho_scale = 32
+ if detail and source.stem == "train":
+ target_point = Vector((0, -1, 1.6))
+ camera.location = (8, -28, 11)
+ camera.rotation_euler = (target_point - camera.location).to_track_quat("-Z", "Y").to_euler()
+ camera_data.ortho_scale = 12
+ camera_data.clip_start = max(0.001, extent / 10000)
+ camera_data.clip_end = extent * 1000
+ scene = bpy.context.scene
+ scene.camera = camera
+ scene.render.engine = "BLENDER_EEVEE"
+ scene.render.resolution_x = 768
+ scene.render.resolution_y = 768
+ scene.render.resolution_percentage = 100
+ scene.render.image_settings.file_format = "PNG"
+ scene.render.film_transparent = False
+ scene.world = bpy.data.worlds.new("Review studio")
+ scene.world.use_nodes = True
+ scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.24, 0.28, 0.34, 1)
+ scene.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.45
+ scene.view_settings.view_transform = "AgX"
+ scene.render.image_settings.color_mode = "RGB"
+ scene.render.filepath = str(target)
+ # Area-light power scales with object area so tiny accessories remain visible.
+ for name, position, energy, size, color in (
+ ("Key", (1, -1, 1.8), 180, 1.4, (1, 0.9, 0.77)),
+ ("Fill", (-1.4, 1, 1), 110, 1.3, (0.65, 0.8, 1)),
+ ("Rim", (0.8, 1.5, 1.6), 230, 1, (1, 0.94, 0.8)),
+ ):
+ pos = center + Vector(position) * extent
+ light(name, pos, energy * extent**2, size * extent, color)
+ bpy.ops.render.render(write_still=True)
+ raw = source.read_bytes()
+ length = struct.unpack_from("<I", raw, 12)[0]
+ gltf = json.loads(raw[20 : 20 + length])
+ triangles = sum(
+ gltf["accessors"][primitive["indices"]]["count"] // 3
+ for mesh in gltf.get("meshes", [])
+ for primitive in mesh["primitives"]
+ if "indices" in primitive
+ )
+ return {
+ "visualization": kind,
+ "meshes": len(gltf.get("meshes", [])),
+ "triangles": triangles,
+ "materials": len(gltf.get("materials", [])),
+ "dimensions_blender_xyz": list(dimensions),
+ "bounds_runtime": {
+ "min": [low.x, low.z, -high.y],
+ "max": [high.x, high.z, -low.y],
+ },
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--group", choices=["study", "legacy", "all"], default="all")
+ parser.add_argument("--limit", type=int)
+ parser.add_argument("--force", action="store_true")
+ args = parser.parse_args(sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [])
+ assets = []
+ if args.group in ("study", "all"):
+ for asset in json.loads((STUDY / "study.json").read_text(encoding="utf-8"))["assets"]:
+ assets.append(("study", asset["id"], STUDY / asset["export"]))
+ if args.group in ("legacy", "all"):
+ for row in csv.DictReader(
+ (STUDY / "asset-inventory.csv").read_text(encoding="utf-8").splitlines()
+ ):
+ source = ROOT / row["path"]
+ assets.append(("legacy", source.stem, source))
+ GALLERY.mkdir(exist_ok=True)
+ manifest = GALLERY / "coverage.json"
+ reports = json.loads(manifest.read_text(encoding="utf-8")) if manifest.exists() else {}
+ for group, asset_id, source in assets[: args.limit]:
+ key = f"{group}/{asset_id}"
+ target = GALLERY / group / f"{asset_id}.png"
+ target.parent.mkdir(exist_ok=True)
+ sha = digest(source)
+ if not args.force and target.exists() and reports.get(key, {}).get("source_sha256") == sha:
+ continue
+ try:
+ report = render_asset(source, target)
+ reports[key] = {
+ "source": source.relative_to(ROOT).as_posix(),
+ "source_sha256": sha,
+ "render": target.relative_to(STUDY).as_posix(),
+ "render_sha256": digest(target),
+ "renderer": bpy.app.version_string + " EEVEE",
+ "status": "rendered; human visual approval pending",
+ **report,
+ }
+ if group == "study" and asset_id in ("train", "building"):
+ detail_path = target.with_name(target.stem + "-detail.png")
+ render_asset(source, detail_path, detail=True)
+ reports[key]["detail_render"] = detail_path.relative_to(STUDY).as_posix()
+ reports[key]["detail_render_sha256"] = digest(detail_path)
+ except Exception as error:
+ reports[key] = {
+ "source": source.relative_to(ROOT).as_posix(),
+ "source_sha256": sha,
+ "status": "failed",
+ "error": str(error),
+ }
+ print(f"Render failed for {key}: {error}", flush=True)
+ manifest.write_text(json.dumps(reports, indent=2) + "\n", encoding="utf-8")
+ print(f"Gallery recorded {key}", flush=True)
+ failures = [key for key, value in reports.items() if value["status"] == "failed"]
+ if failures:
+ raise SystemExit(f"Render failures: {failures}")
+
+
+if __name__ == "__main__":
+ main()