From 97b44cecf584c9e81f3a2899fd86de8269102341 Mon Sep 17 00:00:00 2001 From: Christopher Toth Date: Sat, 28 Nov 2026 23:55:41 -0700 Subject: [PATCH] Keep room lighting across occupant-only snapshots --- agent-notes/perf-occupant-lighting.md | 19 +++ src/components/RoomLayout3D.test.tsx | 63 +++++++- src/components/RoomLayout3D.tsx | 66 +++++--- src/map/figureMesh.ts | 4 +- src/map/roomScene.test.ts | 22 +++ src/map/roomScene.ts | 219 +++++++++++++++----------- src/stores/roomStore.ts | 13 +- 7 files changed, 292 insertions(+), 114 deletions(-) create mode 100644 agent-notes/perf-occupant-lighting.md diff --git a/agent-notes/perf-occupant-lighting.md b/agent-notes/perf-occupant-lighting.md new file mode 100644 index 00000000..515422e0 --- /dev/null +++ b/agent-notes/perf-occupant-lighting.md @@ -0,0 +1,19 @@ +# Goal + +Keep the room's static scene and lighting bake across occupant-only changes, and suppress identical full snapshots. + +## State + +Implementation in the independent react-client-occupant-lighting worktree based on master. The room store compares decoded snapshots. The room view retains unchanged occupant meshes and labels, removes departed people and adds arrivals with the current environment. + +## Decisions and why + +The capture excludes people but includes real light sources. Check room identity, dimensions, finishes, exits, room light, placed sources, and static things before reusing that capture. Start from master so this work does not depend on the open first-paint PR. + +## Surprises + +Figure geometry belongs to a shared cache. Retain geometry still in use when a different figure leaves, and give each person's disposable materials an independent lifetime. + +## Next step + +The focused room scene and component tests passed. In a headless Edge replay an identical snapshot, departure and arrival during baking kept one lighting capture and the same wall and unchanged person's mesh. After the bake finished, a second departure and arrival retained its environment. Adding, moving, then removing a lamp took the capture count from one to four. Publish the PR, follow CI, and merge the checked head. diff --git a/src/components/RoomLayout3D.test.tsx b/src/components/RoomLayout3D.test.tsx index eac8df40..f4c81013 100644 --- a/src/components/RoomLayout3D.test.tsx +++ b/src/components/RoomLayout3D.test.tsx @@ -1,6 +1,10 @@ import { fireEvent, render } from "@testing-library/react"; import { afterEach, expect, it, vi } from "vitest"; -import { sampleLayout } from "../map/roomLayout.fixture"; +import { crowdLayout, sampleLayout } from "../map/roomLayout.fixture"; +import { placeThings } from "../map/roomLayout"; +import { type BufferGeometry, type Mesh, type MeshStandardMaterial, Texture } from "three"; +import { useRoomStore } from "../stores/roomStore"; +import { lightRoom } from "../map/roomBounce"; import * as roomScene from "../map/roomScene"; import RoomLayout3D from "./RoomLayout3D"; @@ -16,7 +20,7 @@ vi.mock("../map/roomPost", () => ({ roomPost: () => ({ setRoom: vi.fn(), setSize: vi.fn(), render: draw, dispose: vi.fn() }), })); vi.mock("../map/roomBounce", () => ({ - lightRoom: () => ({ baked: new Promise((resolve) => { finishBake = resolve; }), dispose: vi.fn() }), + lightRoom: vi.fn(() => ({ environment: new Texture(), baked: new Promise((resolve) => { finishBake = resolve; }), dispose: vi.fn() })), })); afterEach(() => { @@ -24,6 +28,61 @@ afterEach(() => { vi.unstubAllGlobals(); }); +it("keeps the room, environment and unchanged people through occupant snapshots; emitting lights invalidate the bake", () => { + vi.stubGlobal("requestAnimationFrame", () => 1); + vi.stubGlobal("cancelAnimationFrame", vi.fn()); + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({} as WebGL2RenderingContext); + vi.mocked(lightRoom).mockClear(); + const layout = crowdLayout(2); + const picture = (data: typeof layout, selectedId: string | null) => ; + const view = render(picture(layout, "#p1")); + const room = vi.mocked(lightRoom).mock.calls[0][2]; + const light = vi.mocked(lightRoom).mock.results[0].value; + const original = room.things.get("#p0"); + const marker = room.markers.get("#p0"); + const label = view.container.querySelector(".rl3d-label-person"); + const fewer = structuredClone(layout); + fewer.things.pop(); + view.rerender(picture(fewer, "#p1")); + expect(room.things.has("#p1")).toBe(false); + expect(room.heads.has("#p1")).toBe(false); + expect(room.markers.has("#p1")).toBe(false); + expect(room.things.get("#p0")).toBe(original); + expect(room.markers.get("#p0")).toBe(marker); + expect(label?.isConnected).toBe(true); + view.rerender(picture(structuredClone(layout), "#p1")); + expect(view.container.querySelector(".rl3d-label-selected")?.textContent).toBeTruthy(); + const added = room.things.get("#p1")!.children[0] as Mesh; + expect(added.material.envMap).toBe(light.environment); + expect(lightRoom).toHaveBeenCalledTimes(1); + expect(light.dispose).not.toHaveBeenCalled(); + const lit = structuredClone(layout); + lit.things[1].light = { on: true, lumens: 500, cct: 2700, shape: "point" }; + view.rerender(picture(lit, "#p1")); + expect(lightRoom).toHaveBeenCalledTimes(2); + expect(light.dispose).toHaveBeenCalledOnce(); + view.rerender(picture(fewer, null)); + expect(lightRoom).toHaveBeenCalledTimes(3); + view.unmount(); +}); + +it("retains the stored layout for an identical decoded snapshot", () => { + const layout = crowdLayout(2); + useRoomStore.getState().reset(); + useRoomStore.getState().setRoomLayout(layout); + const updated = vi.fn(); + const unsubscribe = useRoomStore.subscribe(updated); + try { + useRoomStore.getState().setRoomLayout(structuredClone(layout)); + expect(updated).not.toHaveBeenCalled(); + expect(useRoomStore.getState().roomLayout).toBe(layout); + } finally { + unsubscribe(); + useRoomStore.getState().reset(); + } +}); + it("combines wheel events into one room draw and cancels the last request on unmount", async () => { vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(480); vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(320); diff --git a/src/components/RoomLayout3D.tsx b/src/components/RoomLayout3D.tsx index a7815a0e..8b0a33ba 100644 --- a/src/components/RoomLayout3D.tsx +++ b/src/components/RoomLayout3D.tsx @@ -23,6 +23,7 @@ import { jointPositions, jointSwingMs, updateRoomBodies, + updateRoomOccupants, type CameraMode, type CameraPose, cutWalls, @@ -57,7 +58,8 @@ import { zoomedFovBy, } from "../map/roomScene"; import { roomRenderer } from "../map/roomRenderer"; -import { needsNightVision } from "../map/lightUnits"; +import { needsNightVision, placedLights } from "../map/lightUnits"; +import { sameRoomData } from "../stores/roomStore"; import { type RoomPost, roomPost } from "../map/roomPost"; import { lightRoom, type RoomLight } from "../map/roomBounce"; import { useSpatialStore } from "../stores/spatialStore"; @@ -122,6 +124,7 @@ interface Stage { lastDrawn: RoomScene | null; layout: RoomLayout | null; placed: PlacedThing[]; + youId: string; /** People's figure geometries, reused while their look is unchanged. */ figures: FigureCache; /** The current room's light bounced off its own surfaces (`lightRoom`): probe grid and reflected environment. */ @@ -242,6 +245,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe lastDrawn: null, layout: null, placed: [], + youId: "", figures: new FigureCache(), light: null, post: roomPost(renderer, scene, camera), @@ -354,13 +358,18 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe } } - // Rigid body updates retain the room's meshes and camera. Structural snapshots rebuild it. + // Body deltas retain the room dimensions by reference. Full snapshots arrive as freshly decoded records. useEffect(() => { const stage = stageRef.current; if (!stage) return; if (mode === "dollhouse") stage.controls.maxDistance = dollhouseMaxDistance(layout); - if (stage.room && stage.layout?.size === layout.size && stage.layout.exits === layout.exits && - stage.layout.finishes === layout.finishes && stage.layout.light === layout.light && updateRoomBodies(stage.room, stage.placed, placed)) { + const old = stage.layout; + const sameShell = old && old.num === layout.num && old.room_lifetime === layout.room_lifetime && + sameRoomData(old.size, layout.size) && sameRoomData(old.exits, layout.exits) && + sameRoomData(old.finishes, layout.finishes) && sameRoomData(old.light, layout.light); + const sameLights = sameShell && (stage.placed === placed || sameRoomData(placedLights(stage.placed), placedLights(placed))); + if (stage.room && sameLights && old?.size === layout.size && stage.youId === youId && + updateRoomBodies(stage.room, stage.placed, placed)) { stage.layout = layout; stage.placed = placed; for (const [id, object] of stage.labelObjects) { @@ -375,18 +384,42 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe return; } const previous = stage.room; - if (previous) stage.scene.remove(previous.root); - for (const object of stage.labelObjects.values()) object.removeFromParent(); - stage.labelObjects.clear(); - - // A door or drawer that moved swings or slides there from where it was drawn, unless motion is reduced. - const drawnJoints = previous ? jointPositions(previous) : new Map(); - const room = buildRoomScene({ layout, placed, youId, figures: stage.figures }); - stage.room = room; + // The capture hides people but still sees their light sources, checked above. + const staticThings = (items: PlacedThing[]) => items.filter(p => !isPerson(p.thing)).map(p => p.thing); + const keepRoom = sameLights && sameRoomData(staticThings(stage.placed), staticThings(placed)); + const kept = new Set(); + if (keepRoom) { + const before = new Map(stage.placed.map(p => [p.thing.id, p.thing])); + for (const { thing } of placed) { + if ((thing.id === stage.youId) === (thing.id === youId) && sameRoomData(before.get(thing.id), thing)) kept.add(thing.id); + } + } + if (stage.selection) disposeSelectionOutline(stage.selection); + stage.selection = null; + for (const [id, object] of stage.labelObjects) { + if (kept.has(id)) continue; + object.removeFromParent(); + stage.labelObjects.delete(id); + } + + let room: RoomScene; + if (previous && keepRoom) { + room = previous; + updateRoomOccupants(room, placed, youId, stage.figures, stage.light?.environment, kept); + } else { + if (previous) stage.scene.remove(previous.root); + const drawnJoints = previous ? jointPositions(previous) : new Map(); + room = buildRoomScene({ layout, placed, youId, figures: stage.figures }); + stage.room = room; + stage.scene.add(room.root); + lightStage(stage, room, layout); + stage.stepJoints = animateJoints(room, drawnJoints, + jointSwingMs(typeof window.matchMedia === "function" ? (query) => window.matchMedia(query) : undefined)); + if (previous && previous !== stage.lastDrawn) disposeRoomScene(previous); + } stage.layout = layout; stage.placed = placed; - stage.scene.add(room.root); - lightStage(stage, room, layout); + stage.youId = youId; // In your own eyes you are not drawn. const you = room.things.get(youId); if (you) you.visible = mode !== "eyes"; @@ -403,6 +436,7 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe ]; labelPlan.current = plan; for (const { id, text, person } of plan) { + if (stage.labelObjects.has(id)) continue; const points = room.labelPoints.get(id); const group = room.things.get(id); if (!points || !group) continue; @@ -424,12 +458,8 @@ const RoomLayout3D: React.FC = ({ layout, placed, youId, labe stage.labelObjects.set(id, object); } showSelection(stage, selectedIdRef.current); - // Set before the first frame, so a moving part is first drawn where it was. - stage.stepJoints = animateJoints(room, drawnJoints, - jointSwingMs(typeof window.matchMedia === "function" ? (query) => window.matchMedia(query) : undefined)); stage.renderer.shadowMap.needsUpdate = true; stage.requestDraw(); - if (previous && previous !== stage.lastDrawn) disposeRoomScene(previous); }, [layout, placed, youId, mode]); // The selection changed (in a list, in this picture, by interact mode): outline it. Nothing else moves. diff --git a/src/map/figureMesh.ts b/src/map/figureMesh.ts index 508bf7ef..0c83411c 100644 --- a/src/map/figureMesh.ts +++ b/src/map/figureMesh.ts @@ -1736,9 +1736,9 @@ export class FigureCache { } /** Frees every geometry not asked for since the last sweep: people who left or whose look changed. */ - sweep(): void { + sweep(retained?: Set): void { for (const [key, geometry] of this.geometries) { - if (this.used.has(key)) continue; + if (this.used.has(key) || retained?.has(geometry)) continue; geometry.dispose(); this.geometries.delete(key); } diff --git a/src/map/roomScene.test.ts b/src/map/roomScene.test.ts index 7e4892ed..9ce8f493 100644 --- a/src/map/roomScene.test.ts +++ b/src/map/roomScene.test.ts @@ -18,6 +18,7 @@ import { jointSwingMs, JOINT_ANIMATION_MS, updateRoomBodies, + updateRoomOccupants, CUT_WALL_HEIGHT, cutWalls, DEFAULT_EYE_HEIGHT, @@ -171,6 +172,27 @@ describe("picking and the selection in 3D", () => { }); describe("buildRoomScene", () => { + it("keeps shared figure geometry and marker rings until their last occupant leaves", () => { + const layout = crowdLayout(2, [TEST_CHARACTERS[0]]); + const figures = new FigureCache(); + const placed = placeThings(layout); + const room = buildRoomScene({ layout, placed, figures, youId: "" }); + const first = room.things.get("#p0")!.children[0] as THREE.Mesh; + const second = room.things.get("#p1")!.children[0] as THREE.Mesh; + expect(first.geometry).toBe(second.geometry); + const freeFigure = vi.spyOn(first.geometry, "dispose"); + const freeRing = vi.spyOn(room.markers.get("#p0")!.geometry, "dispose"); + updateRoomOccupants(room, placed.slice(1), "", figures, undefined, new Set(["#p1"])); + expect(freeFigure).not.toHaveBeenCalled(); + expect(freeRing).not.toHaveBeenCalled(); + expect(room.things.get("#p1")!.children[0]).toBe(second); + updateRoomOccupants(room, [], "", figures); + expect(freeFigure).toHaveBeenCalledOnce(); + expect(freeRing).toHaveBeenCalledOnce(); + expect(figures.size).toBe(0); + disposeRoomScene(room); + }); + it("paints individual form parts with the MOO palette and falls back to the host material", () => { const layout = livingRoomLayout(); const fitting = { id: "#123", name: "drawer", lifetime: "1", command: "open #123", opened: false, contents: [] }; diff --git a/src/map/roomScene.ts b/src/map/roomScene.ts index 64b1875d..f550cd0b 100644 --- a/src/map/roomScene.ts +++ b/src/map/roomScene.ts @@ -1025,101 +1025,72 @@ export function buildRoomScene({ layout, placed, youId, figures }: RoomSceneInpu const labelPoints = new Map(); const heads = new Map(); for (const p of placed) { + if (isPerson(p.thing)) continue; const group = new THREE.Group(); group.name = p.thing.id; group.userData.thingId = p.thing.id; const [x, y] = centre(p.bounds); - if (isPerson(p.thing)) { - group.userData.form = "person"; - const base = p.thing.id === youId ? YOU_COLOUR : PERSON_COLOUR; - const { mesh, label, head, animal } = builder.person(p.thing.appearance, x, y, p.bounds.z0, p.bounds.z1, base, isLayoutPose(p.thing.pose) ? p.thing.pose : undefined, { - width: p.bounds.x1 - p.bounds.x0, - depth: p.bounds.y1 - p.bounds.y0, - }); - group.add(mesh); - // An animal form is drawn smaller than its box or beside it: a zoom onto it frames the figure (`personFocus`). - group.userData.animal = animal; - labelPoints.set(p.thing.id, label); - heads.set(p.thing.id, head); - } else { - group.userData.form = thingForm(p.thing); - const pose = p.thing.pose; - if (p.thing.stand) { - // A stand is drawn as its figure wearing what is on it, in place of its own form. - group.userData.form = "stand"; - const figure = builder.stand(p.thing.stand); - group.add(figure); - if (isLayoutPose(pose)) { - figure.position.z = -pose.dimensions_m[2] / 2; - group.quaternion.copy(bodyQuaternion(pose)); - group.position.fromArray(pose.centre_m); - } else figure.position.set(x, y, p.bounds.z0); - group.updateMatrixWorld(true); - const drawn = new THREE.Box3().setFromObject(group); - labelPoints.set(p.thing.id, [new THREE.Vector3(x, y, Math.max(p.bounds.z1, drawn.max.z))]); - root.add(group); - things.set(p.thing.id, group); - continue; - } - if (isLayoutPose(pose) && (pose.box || p.thing.form_parts?.length)) { - const [w, d, h] = pose.dimensions_m; - const local: PlacedThing = { ...p, bounds: { x0: -w / 2, x1: w / 2, y0: -d / 2, y1: d / 2, z0: -h / 2, z1: h / 2 } }; - if (p.thing.form_parts?.length) { - const thing = thingLook(p.thing); - // A lit thing glows from the parts that say they emit, when any does; else, as before, all over. - const glow = thingGlow(p.thing); - const emitting = p.thing.form_parts.some(partEmits); - for (const part of p.thing.form_parts) { - const { role, fitting } = part; - const look = partLook(part, thing); - // A drawer's face without a colour of its own is a shade darker than what it is made of, so it shows. - const colour = fitting && !colourHex(part.colour) ? new THREE.Color(look.colour).multiplyScalar(0.78).getHex() : look.colour; - const geometry = partGeometry(part); - // An open skin (a loft with an opening and no wall) shows its inside through the opening. - const material = builder.material(colour, { surface: look.surface, doubleSided: geometry.userData.open === true, glow: !emitting || partEmits(part) ? glow : undefined, thickness: partThickness(part), detail: materialSurface(part.material) }); - const mesh = new THREE.Mesh(geometry, material); - mesh.userData.part = fitting?.name ?? role ?? "form"; - mesh.matrixAutoUpdate = false; - placePart(mesh, part); - const key = role ?? fitting?.lifetime; - if (part.joint && key) mesh.userData.joint = { key: JSON.stringify([p.thing.id, key]), part }; - if (fitting) mesh.userData.fitting = fitting.lifetime; - if (role && p.thing.lifetime) mesh.userData.inspect = [p.thing.id, p.thing.lifetime, role]; - group.add(mesh); - } - } else if (thingForm(p.thing) === "box") { - const look = wholeThingLook(p.thing); - group.add(builder.box(local.bounds, builder.material(look.colour, { surface: look.surface, glow: thingGlow(p.thing), thickness: boundsThickness(local.bounds), detail: thingSurface(p.thing) }), "box")); - } - else for (const mesh of thingMeshes(builder, local, screenGlow)) group.add(mesh); + group.userData.form = thingForm(p.thing); + const pose = p.thing.pose; + if (p.thing.stand) { + // A stand is drawn as its figure wearing what is on it, in place of its own form. + group.userData.form = "stand"; + const figure = builder.stand(p.thing.stand); + group.add(figure); + if (isLayoutPose(pose)) { + figure.position.z = -pose.dimensions_m[2] / 2; group.quaternion.copy(bodyQuaternion(pose)); group.position.fromArray(pose.centre_m); - } else if (isLayoutPose(pose)) { - for (const mesh of collisionMeshes(builder, p)) group.add(mesh); - } else { - for (const mesh of thingMeshes(builder, p, screenGlow)) group.add(mesh); + } else figure.position.set(x, y, p.bounds.z0); + group.updateMatrixWorld(true); + const drawn = new THREE.Box3().setFromObject(group); + labelPoints.set(p.thing.id, [new THREE.Vector3(x, y, Math.max(p.bounds.z1, drawn.max.z))]); + root.add(group); + things.set(p.thing.id, group); + continue; + } + if (isLayoutPose(pose) && (pose.box || p.thing.form_parts?.length)) { + const [w, d, h] = pose.dimensions_m; + const local: PlacedThing = { ...p, bounds: { x0: -w / 2, x1: w / 2, y0: -d / 2, y1: d / 2, z0: -h / 2, z1: h / 2 } }; + if (p.thing.form_parts?.length) { + const thing = thingLook(p.thing); + // A lit thing glows from the parts that say they emit, when any does; else, as before, all over. + const glow = thingGlow(p.thing); + const emitting = p.thing.form_parts.some(partEmits); + for (const part of p.thing.form_parts) { + const { role, fitting } = part; + const look = partLook(part, thing); + // A drawer's face without a colour of its own is a shade darker than what it is made of, so it shows. + const colour = fitting && !colourHex(part.colour) ? new THREE.Color(look.colour).multiplyScalar(0.78).getHex() : look.colour; + const geometry = partGeometry(part); + // An open skin (a loft with an opening and no wall) shows its inside through the opening. + const material = builder.material(colour, { surface: look.surface, doubleSided: geometry.userData.open === true, glow: !emitting || partEmits(part) ? glow : undefined, thickness: partThickness(part), detail: materialSurface(part.material) }); + const mesh = new THREE.Mesh(geometry, material); + mesh.userData.part = fitting?.name ?? role ?? "form"; + mesh.matrixAutoUpdate = false; + placePart(mesh, part); + const key = role ?? fitting?.lifetime; + if (part.joint && key) mesh.userData.joint = { key: JSON.stringify([p.thing.id, key]), part }; + if (fitting) mesh.userData.fitting = fitting.lifetime; + if (role && p.thing.lifetime) mesh.userData.inspect = [p.thing.id, p.thing.lifetime, role]; + group.add(mesh); + } + } else if (thingForm(p.thing) === "box") { + const look = wholeThingLook(p.thing); + group.add(builder.box(local.bounds, builder.material(look.colour, { surface: look.surface, glow: thingGlow(p.thing), thickness: boundsThickness(local.bounds), detail: thingSurface(p.thing) }), "box")); } - labelPoints.set(p.thing.id, [new THREE.Vector3(x, y, p.bounds.z1)]); + else for (const mesh of thingMeshes(builder, local, screenGlow)) group.add(mesh); + group.quaternion.copy(bodyQuaternion(pose)); + group.position.fromArray(pose.centre_m); + } else if (isLayoutPose(pose)) { + for (const mesh of collisionMeshes(builder, p)) group.add(mesh); + } else { + for (const mesh of thingMeshes(builder, p, screenGlow)) group.add(mesh); } + labelPoints.set(p.thing.id, [new THREE.Vector3(x, y, p.bounds.z1)]); root.add(group); things.set(p.thing.id, group); } - // Figures of people who left, or whose look changed, are freed now. - figures?.sweep(); - // A floor ring for each person, hidden until `updateTinyMarkers` finds their figure too small to see. - const markers = new Map(); - const rings = new THREE.Group(); - rings.name = "tiny figure markers"; - const ring = new THREE.RingGeometry(MARKER_INNER, 1, 40); - for (const [id, group] of things) { - if (group.userData.form !== "person") continue; - const marker = new THREE.Mesh(ring, new THREE.MeshBasicMaterial({ color: MARKER_COLOUR, transparent: true, opacity: 0, depthWrite: false })); - marker.name = `marker ${id}`; - marker.visible = false; - rings.add(marker); - markers.set(id, marker); - } - root.add(rings); // Things and people cast shadows and take them; the floor, walls and ceiling take them. Walls and ceiling cast none: // the wire gives no windows, so the sun and sky light reach in as the MOO says they do rather than being shut out. // Nothing see-through casts one, nor does a thing that sends a light: the light sits at its body's centre, inside @@ -1128,15 +1099,77 @@ export function buildRoomScene({ layout, placed, youId, figures }: RoomSceneInpu for (const object of [ceiling, ...Object.values(walls)]) object.traverse((o) => { o.receiveShadow = true; }); const emitting = new Set(placedLights(placed).filter((l) => l.light.on).map((l) => l.thingId)); for (const [id, group] of things) { - group.traverse((object) => { - if (!(object instanceof THREE.Mesh)) return; - object.receiveShadow = true; - object.castShadow = !emitting.has(id) && (object.material as THREE.Material).userData.castsShadow !== false; - }); + setThingShadows(group, emitting.has(id)); } markSurfaceGrain(root); root.updateMatrixWorld(true); - return { root, walls, ceiling, exits, things, labelPoints, heads, markers, lights, exposure }; + const room = { root, walls, ceiling, exits, things, labelPoints, heads, markers: new Map(), lights, exposure }; + updateRoomOccupants(room, placed, youId, figures); + return room; +} + +function setThingShadows(group: THREE.Group, emits: boolean): void { + group.traverse(object => { + if (!(object instanceof THREE.Mesh)) return; + object.receiveShadow = true; + object.castShadow = !emits && (object.material as THREE.Material).userData.castsShadow !== false; + }); +} + +/** Reconcile the people excluded from the lighting capture. Unchanged IDs keep their meshes, markers and geometry. */ +export function updateRoomOccupants(room: RoomScene, placed: PlacedThing[], youId: string, figures?: FigureCache, environment?: THREE.Texture, kept = new Set()): void { + let ring = room.markers.values().next().value?.geometry; + const retained = new Set(); + for (const [id, marker] of room.markers) { + const group = room.things.get(id)!; + if (kept.has(id)) { + group.traverse(object => { + if (object instanceof THREE.Mesh && object.userData.keptGeometry) retained.add(object.geometry); + }); + continue; + } + disposeMeshes(group); + group.removeFromParent(); + (marker.material as THREE.Material).dispose(); + marker.removeFromParent(); + room.markers.delete(id); + room.things.delete(id); + room.heads.delete(id); + room.labelPoints.delete(id); + } + for (const p of placed) { + if (!isPerson(p.thing) || kept.has(p.thing.id)) continue; + const id = p.thing.id; + // A person's materials leave with them. Figure geometry is shared through the room's cache. + const builder = new Builder(figures, room.exposure); + const group = new THREE.Group(); + group.name = id; + group.userData.thingId = id; + group.userData.form = "person"; + const [x, y] = centre(p.bounds); + const { mesh, label, head, animal } = builder.person(p.thing.appearance, x, y, p.bounds.z0, p.bounds.z1, + id === youId ? YOU_COLOUR : PERSON_COLOUR, isLayoutPose(p.thing.pose) ? p.thing.pose : undefined, + { width: p.bounds.x1 - p.bounds.x0, depth: p.bounds.y1 - p.bounds.y0 }); + group.userData.animal = animal; + group.add(mesh); + setThingShadows(group, Boolean(thingLight(p.thing)?.on)); + if (environment) group.traverse(object => { + if (object instanceof THREE.Mesh && object.material instanceof THREE.MeshStandardMaterial) object.material.envMap = environment; + }); + markSurfaceGrain(group); + room.things.set(id, group); + room.labelPoints.set(id, label); + room.heads.set(id, head); + ring ??= new THREE.RingGeometry(MARKER_INNER, 1, 40); + const marker = new THREE.Mesh(ring, new THREE.MeshBasicMaterial({ color: MARKER_COLOUR, transparent: true, opacity: 0, depthWrite: false })); + marker.name = `marker ${id}`; + marker.visible = false; + room.markers.set(id, marker); + room.root.add(group, marker); + group.updateMatrixWorld(true); + } + if (!room.markers.size) ring?.dispose(); + figures?.sweep(retained); } /** A figure shorter than this on screen, CSS pixels, gets its floor ring; from MARKER_FULL_PX down the ring is at full strength. */ @@ -1720,8 +1753,12 @@ export function eyesPose( /** Frees every geometry and material in the scene. */ export function disposeRoomScene(scene: RoomScene): void { + disposeMeshes(scene.root); +} + +function disposeMeshes(root: THREE.Object3D): void { const materials = new Set(); - scene.root.traverse((object) => { + root.traverse((object) => { if (object instanceof THREE.Mesh || object instanceof THREE.LineSegments) { // A kept figure geometry belongs to its FigureCache, which frees it. if (!object.userData.keptGeometry) object.geometry.dispose(); diff --git a/src/stores/roomStore.ts b/src/stores/roomStore.ts index 19ea4915..09ee0566 100644 --- a/src/stores/roomStore.ts +++ b/src/stores/roomStore.ts @@ -12,6 +12,17 @@ import type { GMCPMessageRoomInfo, RoomLayout, RoomLayoutUpdate, RoomPlayer } fr const sortByFullname = (players: RoomPlayer[]): RoomPlayer[] => [...players].sort((a, b) => a.fullname.localeCompare(b.fullname)); +/** Compare decoded wire values, including records whose JSON keys arrived in a different order. */ +export function sameRoomData(a: unknown, b: unknown): boolean { + if (a === b) return true; + if (!a || !b || typeof a !== "object" || typeof b !== "object" || Array.isArray(a) !== Array.isArray(b)) return false; + const left = a as Record; + const right = b as Record; + const keys = Object.keys(left); + return keys.length === Object.keys(right).length && + keys.every(key => Object.hasOwn(right, key) && sameRoomData(left[key], right[key])); +} + interface RoomState { roomInfo: GMCPMessageRoomInfo | null; roomPlayers: RoomPlayer[]; @@ -39,7 +50,7 @@ export const useRoomStore = create((set) => ({ : { roomInfo: info, roomPlayers: [], roomLayout: null } ), setRoomLayout: (layout) => set((state) => - state.roomInfo && state.roomInfo.num !== layout.num ? state : { roomLayout: layout }), + (state.roomInfo && state.roomInfo.num !== layout.num) || sameRoomData(state.roomLayout, layout) ? state : { roomLayout: layout }), updateRoomLayout: (update) => set((state) => { const layout = state.roomLayout; if (!layout || layout.num !== update.num || layout.room_lifetime !== update.room_lifetime) return state;