Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): add isolated future city transit reference
rubenluetke10-beep78b6a421f51e
diff --git a/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx b/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsxnew file mode 100644index 0000000000..4e607dcc44--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/city/CityStage.tsx@@ -0,0 +1,904 @@+/** Isolated city reference. Existing catalogs and saved island positions remain intact. */+import {+ Suspense,+ 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 { useCanvasAwake } from "@/hooks/useCanvasAwake";+import { useWebglSurface } from "@/hooks/useWebglSurface";+import { useWebglSupported } from "@/lib/graphDimension";+import { useLocaleChunk, useT } from "@/i18n";+import { useSocietyRoster } from "../data";+import { FigureRig, type FigureDrive } from "../figures/FigureRig";+import type { FigureRecipe } from "../figures/figureRecipe";+import type { PlaceId } from "../world/islandLayout";+import {+ CITY,+ DISTRICTS,+ MATERIALS,+ PLOTS,+ checkpointStop,+ stopX,+ validPlacement,+ type Stop,+ type Vec3,+} from "./cityModel";+import {+ addCitizen,+ advanceHour,+ createSimulation,+ daylight,+ previewCrossing,+ safeDestination,+ setTarget,+ stepSimulation,+ trainAt,+ type CitySimulation,+ type Citizen,+} 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";++interface Props {+ topRight?: ReactNode;+ onOpenLedger: () => void;+ 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 INITIAL_METRICS: Metrics = {+ 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({+ topRight,+ onOpenLedger,+ onSelectAgent,+ onSelectPlace,+}: Props) {+ const t = useT();+ const ready = useLocaleChunk("society");+ const host = useRef<HTMLDivElement>(null);+ const { generation } = useWebglSurface(host);+ const awake = useCanvasAwake(host);+ const webgl = useWebglSupported();+ const 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[]>(+ () =>+ demo+ ? Array.from({ length: count }, (_, i) => ({+ id: `reference-${i}`,+ label: `${t("society.city.reference_agent")} ${i + 1}`,+ checkpoint: "idle",+ state: "demo",+ }))+ : (roster.data?.agents ?? []).map((a) => ({+ id: a.agentId,+ label: a.name,+ recipe: a.figure,+ checkpoint: a.checkpoint,+ state: a.state,+ })),+ [demo, count, roster.data, t],+ );+ // 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(() => {+ const ids = new Set(actors.map((a) => a.id));+ for (const id of sim.citizens.keys())+ if (!ids.has(id)) {+ sim.citizens.delete(id);+ signatures.current.delete(id);+ }+ for (const actor of actors) {+ const signature = `${actor.checkpoint}:${actor.state}`;+ if (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);+ }+ }+ }, [actors, sim, demo]);+ 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);+ }, 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);+ }+ 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]] });+ }+ const selectedActor = actors.find((a) => a.id === selected);+ const citizen = selected ? sim.citizens.get(selected) : null;+ 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;+ return (+ <div+ className="relative flex h-full min-h-0 flex-col bg-background text-foreground"+ data-testid="city-reference"+ >+ <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={() => {+ setFollow(null);+ setOverview((n) => n + 1);+ }}+ >+ {t("society.city.overview")}+ </button>+ <button className={button} onClick={() => setDayPaused(!dayPaused)}>+ {t(dayPaused ? "society.city.resume_day" : "society.city.pause_day")}+ </button>+ <label className="flex items-center gap-1 text-xs">+ {t("society.city.hour")}+ <input+ className="w-24"+ aria-label={t("society.city.hour")}+ type="range"+ min="0"+ max="23.9"+ step="0.1"+ value={hour}+ onChange={(e) => {+ setHour(Number(e.target.value));+ setDayPaused(true);+ }}+ />+ {String(Math.floor(hour)).padStart(2, "0")}:00+ </label>+ </div>+ <div ref={host} className="relative isolate min-h-0 flex-1">+ {webgl ? (+ <Canvas+ key={generation}+ camera={{+ position: [200, 140, 240],+ fov: 45,+ near: 0.2,+ far: 4000,+ }}+ dpr={1}+ shadows+ gl={{ antialias: true, alpha: false }}+ frameloop={!awake ? "never" : reduced ? "demand" : "always"}+ >+ <Suspense fallback={null}>+ <Runtime+ sim={sim}+ hour={hour}+ paused={reduced}+ awake={awake}+ follow={follow}+ overview={overview}+ onMetrics={setMetrics}+ />+ <District+ placements={placements}+ onPlace={(s) => {+ setActivePlot(s);+ setPlacementError(false);+ }}+ />+ {actors.map((actor) => (+ <MovingActor+ key={actor.id}+ actor={actor}+ sim={sim}+ paused={reduced}+ selected={selected === actor.id}+ onClick={() => setSelected(actor.id)}+ />+ ))}+ </Suspense>+ </Canvas>+ ) : (+ <div className="p-6">+ <p>{t("society.world.webgl_missing_body")}</p>+ <button className={button} onClick={onOpenLedger}>+ {t("society.world.open_ledger")}+ </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+ </p>+ {reduced && <p>{t("society.city.reduced")}</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)}+ >+ {a.label}+ <span className="block text-muted-foreground">+ {t(+ `society.city.stage_${sim.citizens.get(a.id)?.stage ?? "arrived"}`,+ )}+ </span>+ </button>+ ))}+ </div>+ {selectedActor && citizen && (+ <div+ className="absolute z-20 bottom-3 right-3 w-64 rounded 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}+ >+ <strong>{selectedActor.label}</strong>+ <p>+ {t("society.city.task")}: {selectedActor.checkpoint} ·{" "}+ {selectedActor.state}+ </p>+ <p>+ {t("society.city.travel")}:{" "}+ {t(`society.city.stage_${citizen.stage}`)}+ </p>+ <p>+ {t("society.city.target")}: {t(`society.city.${citizen.target}`)}+ </p>+ <div className="mt-2 flex gap-2">+ <button+ className={button}+ onClick={() =>+ setFollow(follow === citizen.id ? null : citizen.id)+ }+ >+ {t(+ follow === citizen.id+ ? "society.city.unfollow"+ : "society.city.follow",+ )}+ </button>+ {!demo && (+ <button+ className={button}+ onClick={() => onSelectAgent?.(citizen.id)}+ >+ {t("society.city.open_agent")}+ </button>+ )}+ </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")}+ </p>+ )}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts b/jarvis/ui/web/frontend/src/components/society/city/cityModel.tsnew file mode 100644index 0000000000..7c43c15100--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/city/cityModel.ts@@ -0,0 +1,216 @@+/** Metre-based reference district. Layer identity is part of every route node. */+export type Vec3 = [number, number, number];+export type Stop = "west" | "east";+export interface RouteNode {+ id: string;+ position: Vec3;+ layer: "ground" | "platform" | "bridge";+}+export interface RouteEdge {+ from: string;+ to: string;+ speed: number;+}+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 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>();+ 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;+ if (id === to) {+ const path = [to];+ while (previous.has(path[0])) path.unshift(previous.get(path[0])!);+ 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);+ }+ }+ }+}+export function routeSeconds(path: string[] | null): 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,+ );+}+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";+ 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/cityMotion.test.ts b/jarvis/ui/web/frontend/src/components/society/city/cityMotion.test.tsnew file mode 100644index 0000000000..666e84a34e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/city/cityMotion.test.ts@@ -0,0 +1,22 @@+import { act, renderHook } from "@testing-library/react";+import { expect, it } from "vitest";+import { useCityReducedMotion } from "./cityMotion";++it("reacts to an accessibility preference changed after the city mounts", () => {+ const original = Object.getOwnPropertyDescriptor(window, "matchMedia");+ class Media extends EventTarget { matches = false; }+ const media = new Media();+ Object.defineProperty(window, "matchMedia", { configurable: true, value: () => media });+ const hook = renderHook(useCityReducedMotion);+ try {+ expect(hook.result.current).toBe(false);+ act(() => { media.matches = true; media.dispatchEvent(new Event("change")); });+ expect(hook.result.current).toBe(true);+ act(() => { media.matches = false; media.dispatchEvent(new Event("change")); });+ expect(hook.result.current).toBe(false);+ } finally {+ hook.unmount();+ if (original) Object.defineProperty(window, "matchMedia", original);+ else Reflect.deleteProperty(window, "matchMedia");+ }+});diff --git a/jarvis/ui/web/frontend/src/components/society/city/cityMotion.ts b/jarvis/ui/web/frontend/src/components/society/city/cityMotion.tsnew file mode 100644index 0000000000..f67c224738--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/city/cityMotion.ts@@ -0,0 +1,16 @@+import { useSyncExternalStore } from "react";++const QUERY = "(prefers-reduced-motion: reduce)";+function snapshot(): boolean {+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(QUERY).matches;+}+function subscribe(listener: () => void): () => void {+ if (typeof window.matchMedia !== "function") return () => undefined;+ const media = window.matchMedia(QUERY);+ media.addEventListener("change", listener);+ return () => media.removeEventListener("change", listener);+}+/** The installed motion hook snapshots only at mount; city travel must react live. */+export function useCityReducedMotion(): boolean {+ return useSyncExternalStore(subscribe, snapshot, () => false);+}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.tsnew file mode 100644index 0000000000..6f1b0508f4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it } from "vitest";+import { node, PLOTS, route, validPlacement } from "./cityModel";+import {+ addCitizen,+ advanceHour,+ CAPACITY,+ createSimulation,+ previewCrossing,+ safeDestination,+ setTarget,+ stepSimulation,+ trainAt,+} 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);+ const stages = new Set<string>();+ let last = c.position;+ for (let i = 0; i < 2500; i++) {+ stepSimulation(sim, 0.1);+ stages.add(c.stage);+ expect(Math.hypot(...c.position.map((v, j) => v - last[j]))).toBeLessThan(+ 1.6,+ );+ 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");+ expect(c.seat).toBeNull();+ });+ it("reserves capacity and leaves excess passengers for the next departure", () => {+ 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);+ }+ 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", () => {+ 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);+ expect(c.stage).toBe("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);+ expect(c.stage).toBe("walking");+ });+ 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);+ }+ 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);+ });+ it("pauses the day cycle and wraps a full 30 minute day", () => {+ 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.tsnew file mode 100644index 0000000000..37991aa2e2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/city/citySimulation.ts@@ -0,0 +1,319 @@+import {+ distance,+ EDGES,+ mix,+ node,+ otherStop,+ route,+ routeSeconds,+ 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 interface TrainState {+ position: Vec3;+ stop: Stop | null;+ next: Stop;+ remaining: number;+ heading: number;+}+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,+ };+}+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 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;+}+export interface CitySimulation {+ time: number;+ citizens: Map<string, Citizen>;+ blocked: Set<string>;+}+export function createSimulation(): CitySimulation {+ return { time: 0, citizens: new Map(), blocked: new Set() };+}+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;+}+export function addCitizen(+ sim: CitySimulation,+ id: string,+ stop: Stop,+): Citizen {+ 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;+}+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,+ ];+}+export function setTarget(+ sim: CitySimulation,+ id: string,+ target: Stop,+ revision: number,+): void {+ const c = sim.citizens.get(id);+ if (!c || 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);+ return;+ }+ plan(sim, c);+}+/** Explicit preview walk, never used to override a live agent's activity. */+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);+ if (!path) return false;+ citizen.path = path;+ citizen.edgeTime = 0;+ citizen.stage = "walking";+ return true;+}+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;+ }+ }+ 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;+ }+}+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 advance(sim: CitySimulation, dt: number): void {+ sim.time += dt;+ const train = trainAt(sim.time);+ 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;+ }+ } 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);+ }+ }+ }+ 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];+ }+ }+}+/** Fixed small steps retain physical boarding and route transitions during catch-up. */+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;+ }+}+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;+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 83d15a67e2..757f593e7c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -262,6 +262,47 @@"configured": "Verbindung bereit","source": "Die Ereignisquelle muss aktiv sein.","filter_hint": "Beispiel: {\"data.status\": \"ready\"}. Mit {} wird jede Payload angenommen."+ },+ "city": {+ "mode": "Stadtvorschau",+ "title": "Zukunftsstadt / Referenz 01",+ "demo": "Demo-Agenten",+ "agent_count": "Anzahl Demo-Agenten",+ "reference_agent": "Referenzagent",+ "west": "Zentralbahnhof",+ "east": "Terminalbahnhof",+ "overview": "Übersicht",+ "resume_day": "Tageslauf fortsetzen",+ "pause_day": "Tageslauf anhalten",+ "hour": "Uhrzeit",+ "reference_notice": "Designreferenz — visuelle Prüfung steht aus",+ "controls": "Ziehen zum Drehen · Rechtsziehen zum Verschieben · Scrollen zum Zoomen",+ "agents": "Agenten",+ "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",+ "travel": "Physische Reise",+ "target": "Ziel",+ "follow": "Verfolgen",+ "unfollow": "Verfolgung beenden",+ "open_agent": "Agent öffnen",+ "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.",+ "knowledge": "Wissensviertel",+ "workshop": "Werkstattviertel",+ "communications": "Kommunikationsviertel",+ "blockout": "Rohentwurf",+ "stage_arrived": "Am Ziel",+ "stage_walking": "Unterwegs / Aufzug",+ "stage_waiting": "Wartet am Bahnsteig",+ "stage_boarding": "Steigt ein",+ "stage_riding": "Im Zug",+ "stage_exiting": "Steigt aus",+ "stage_unreachable": "Ziel nicht erreichbar",+ "bridge_walk": "Brücke begehen"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 569b8a775d..4696b1598e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -262,6 +262,47 @@"configured": "Connection ready","source": "Event source must be active.","filter_hint": "Example: {\"data.status\": \"ready\"}. Leave {} to accept every payload."+ },+ "city": {+ "mode": "City preview",+ "title": "Future city / Reference 01",+ "demo": "Demo agents",+ "agent_count": "Demo agent count",+ "reference_agent": "Reference agent",+ "west": "Central station",+ "east": "Terminal station",+ "overview": "Overview",+ "resume_day": "Resume daylight",+ "pause_day": "Pause daylight",+ "hour": "Time",+ "reference_notice": "Design reference — awaiting visual review",+ "controls": "Drag to orbit · Right-drag to pan · Scroll to zoom",+ "agents": "agents",+ "reduced": "Reduced motion: journeys and daylight are paused.",+ "feed_error": "Live roster unavailable. Demo agents remain available.",+ "live": "Live checkpoint feed",+ "task": "Actual task",+ "travel": "Physical journey",+ "target": "Destination",+ "follow": "Follow",+ "unfollow": "Stop following",+ "open_agent": "Open agent",+ "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.",+ "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_boarding": "Boarding",+ "stage_riding": "On the train",+ "stage_exiting": "Leaving the train",+ "stage_unreachable": "Destination unreachable",+ "bridge_walk": "Walk the bridge"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 1a13fff87c..43c187e1a5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -262,6 +262,47 @@"configured": "Conexión lista","source": "La fuente del evento debe estar activa.","filter_hint": "Ejemplo: {\"data.status\": \"ready\"}. Usa {} para aceptar cualquier contenido."+ },+ "city": {+ "mode": "Vista previa de ciudad",+ "title": "Ciudad del futuro / Referencia 01",+ "demo": "Agentes de prueba",+ "agent_count": "Cantidad de agentes de prueba",+ "reference_agent": "Agente de referencia",+ "west": "Estación central",+ "east": "Estación terminal",+ "overview": "Vista general",+ "resume_day": "Continuar ciclo del día",+ "pause_day": "Pausar ciclo del día",+ "hour": "Hora",+ "reference_notice": "Referencia de diseño — pendiente de revisión visual",+ "controls": "Arrastra para girar · Arrastra con botón derecho para desplazar · Rueda para ampliar",+ "agents": "agentes",+ "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",+ "travel": "Viaje físico",+ "target": "Destino",+ "follow": "Seguir",+ "unfollow": "Dejar de seguir",+ "open_agent": "Abrir agente",+ "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.",+ "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_boarding": "Subiendo",+ "stage_riding": "En el tren",+ "stage_exiting": "Bajando del tren",+ "stage_unreachable": "Destino inaccesible",+ "bridge_walk": "Cruzar el puente"}}}diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsxindex c5f5592298..aa2250f09e 100644--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx@@ -54,12 +54,15 @@ const RUN_PARAM = "run";* WebGL is absent. The world is a lazy chunk — three.js and the island never* load for someone who only ever reads the ledger.*/-type AgentsMode = "world" | "ledger";+type AgentsMode = "world" | "ledger" | "city";const MODE_KEY = "jarvis.agents.mode";const WorldStage = lazy(() =>import("@/components/society/world/WorldStage").then((m) => ({ default: m.WorldStage })),);+const CityStage = lazy(() =>+ import("@/components/society/city/CityStage").then((m) => ({ default: m.CityStage })),+);function readMode(): AgentsMode {try {@@ -72,6 +75,7 @@ function readMode(): AgentsMode {}function writeMode(mode: AgentsMode): void {+ if (mode === "city") return; // Reference preview never replaces a saved production preference.try {localStorage.setItem(MODE_KEY, mode);} catch {@@ -92,6 +96,7 @@ function ModeSwitch({ mode, onChange }: { mode: AgentsMode; onChange: (m: Agentsoptions={[{ id: "world", label: t("society.world.mode_world") },{ id: "ledger", label: t("society.world.mode_ledger") },+ { id: "city", label: t("society.city.mode") },]}/></div>@@ -254,6 +259,10 @@ export function JarvisAgentsView({ onSelectAgent, onSelectPlace }: JarvisAgentsVconst modeSwitch = <ModeSwitch mode={mode} onChange={switchMode} />;+ if (mode === "city") {+ return <Suspense fallback={<WorldLoading />}><CityStage topRight={modeSwitch} onOpenLedger={() => switchMode("ledger")} onSelectAgent={onSelectAgent} onSelectPlace={onSelectPlace} /></Suspense>;+ }+if (mode === "world") {return (<div className="h-full min-h-0">diff --git a/scripts/art/build_city_reference.py b/scripts/art/build_city_reference.pynew file mode 100644index 0000000000..e60d6389ff--- /dev/null+++ b/scripts/art/build_city_reference.py@@ -0,0 +1,177 @@+"""Author editable future-city reference collections; never replace production assets.++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 bpy+from mathutils import Vector++STUDY = Path(__file__).resolve().parents[2] / "art/studies/city-realism-study"+bpy.ops.object.select_all(action="SELECT")+bpy.ops.object.delete(use_global=False)+++def material(name, color, roughness=0.6, metal=0, glow=0):+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*color, 1)+ mat.use_nodes = True+ shader = mat.node_tree.nodes.get("Principled BSDF")+ shader.inputs["Base Color"].default_value = (*color, 1)+ shader.inputs["Roughness"].default_value = roughness+ shader.inputs["Metallic"].default_value = metal+ if glow:+ shader.inputs["Emission Color"].default_value = (*color, 1)+ shader.inputs["Emission Strength"].default_value = glow+ return mat+++CONCRETE = material("concrete", (0.48, 0.46, 0.42), 0.85)+STEEL = material("graphite_structure", (0.025, 0.035, 0.044), 0.35, 0.7)+METAL = material("brushed_aluminium", (0.4, 0.46, 0.5), 0.38, 0.75)+GLASS = material("blue_glazing", (0.09, 0.19, 0.23), 0.17, 0.35)+LIGHT = material("warm_light", (1, 0.72, 0.38), 0.4, 0, 2)+GREEN = material("foliage", (0.11, 0.2, 0.075), 0.9)+BARK = material("bark", (0.12, 0.07, 0.035), 0.95)+CLOTH = material("technical_uniform", (0.055, 0.19, 0.23), 0.85)+SKIN = material("skin", (0.46, 0.25, 0.15), 0.85)+current = None+++def collection(name):+ global current+ current = bpy.data.collections.new(name)+ bpy.context.scene.collection.children.link(current)+++def finish(obj, name, mat):+ obj.name = name+ for col in list(obj.users_collection):+ col.objects.unlink(obj)+ current.objects.link(obj)+ obj.data.materials.append(mat)+ return obj+++def box(name, at, size, mat, bevel=0.08):+ bpy.ops.mesh.primitive_cube_add(size=1, location=at)+ obj = bpy.context.object+ obj.scale = size+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ if bevel:+ mod = obj.modifiers.new("edge_detail", "BEVEL")+ mod.width = min(bevel, min(size) / 4)+ mod.segments = 2+ bpy.ops.object.modifier_apply(modifier=mod.name)+ obj.modifiers.new("weighted_normals", "WEIGHTED_NORMAL")+ return finish(obj, name, mat)+++def beam(name, a, b, width, mat):+ delta = Vector(b) - Vector(a)+ obj = box(name, (Vector(a) + Vector(b)) / 2, (width, width, delta.length), mat)+ obj.rotation_euler = delta.to_track_quat("Z", "Y").to_euler()+ 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)+box("hair", (0, 0.015, 1.73), (0.24, 0.23, 0.09), STEEL, 0.04)+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)+ 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.+ foot_y = -0.32 + 1.28 * phase if phase < 0.5 else 0.32 - 1.28 * (phase - 0.5)+ lift = 0 if phase < 0.5 else math.sin((phase - 0.5) * math.pi * 2) * 0.16+ 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))+ 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)):+ obj.location = (a + b) / 2+ obj.rotation_mode = "QUATERNION"+ obj.rotation_quaternion = (b - a).to_track_quat("Z", "Y")+ obj.keyframe_insert("location", frame=frame)+ obj.keyframe_insert("rotation_quaternion", frame=frame)+ shoe.location = (x, foot_y - 0.04, 0.08 + lift)+ shoe.keyframe_insert("location", frame=frame)+ for obj in (upper, lower, shoe):+ action = obj.animation_data.action+ track = obj.animation_data.nla_tracks.new()+ track.name = "walk"+ track.strips.new("walk", 0, action)+ obj.animation_data.action = None+box("badge", (0.09, -0.125, 1.26), (0.045, 0.015, 0.07), LIGHT, 0)++bpy.context.scene.unit_settings.system = "METRIC"+bpy.context.scene.unit_settings.scale_length = 1+bpy.context.scene.render.fps = 24+bpy.context.scene.frame_start = 0+bpy.context.scene.frame_end = 24+bpy.context.scene.frame_set(0)+STUDY.joinpath("source").mkdir(parents=True, exist_ok=True)+bpy.ops.wm.save_as_mainfile(filepath=str(STUDY / "source/city-reference.blend"))+print("Saved editable reference collections; export using the study manifest.")