Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add three-fenestra interior-mapping windows to CyberCity online towers
[._.]/ Adam Eivy76cddf3c525d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b9406f82cc..606eb815de 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **CyberCity buildings now have real lit-room windows you can look into.** Online towers in the 3D city (CyberCity) render parallax interior-mapped window panes via the [three-fenestra](https://github.com/codedgar/three-fenestra) shader — a `MeshStandardMaterial` that fakes furnished 3D rooms behind flat glass, so as the camera moves you see *into* lit (and unlit) rooms rather than a flat emissive texture. Each building is a single instanced draw call: a deterministic per-pane seed drives the room-cell pick and per-window lit/unlit + warm/cool lighting entirely on the GPU, with the cool tone pulled toward the building's neon accent so windows stay in-family with the scene. The effect is night-only (by day a tower reads as a sunlit solid) and gated to the **high** quality preset and above, so medium/low machines keep the lighter flat-texture facade. (`client/src/components/city/BuildingWindows.jsx`, `client/src/utils/cityInteriorWindows.js`, `client/src/components/city/{Building,Borough}.jsx`)+- **Tribe — a relationship manager for rings, care cadence, focus lists, and touchpoints.** A new **Tribe** page (Brain → Tribe, also reachable via ⌘K / voice) lets you organize the people in your life into Dunbar-style rings (Support / Core / Tribe / Village), each with a default check-in cadence; log touchpoints (manual or sourced from a calendar event), track per-person energy/next-move/notes, and link people to Brain memories. People, touchpoints, and memory links live in Postgres (`tribe_people`, `tribe_touchpoints`, `tribe_memory_links`) so they can be joined to Brain memories and carry calendar event references for future scheduling work — provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` (with audit triggers on people/touchpoints), and exercised by route + service tests. The page reconciles live against a `tribe:changed` socket broadcast (covers other tabs/devices) and falls back to a one-shot import of any legacy `localStorage` contacts on first load. New `/api/tribe` routes + service; relationship data is currently machine-local (the tables carry no sync columns). (`server/routes/tribe.js`, `server/services/tribe.js`, `server/lib/db.js`, `server/scripts/init-db.sql`, `client/src/pages/Tribe.jsx`, `client/src/services/apiTribe.js`, #1436)- **[issue-901] Legacy Export — download your whole identity as a portable bundle (server foundation).** A new `POST /api/legacy-export` endpoint gathers your identity across every PortOS domain — digital-twin prompt, autobiography, brain notes, memories, goals + milestones, key decisions, and a health summary — into a single self-contained `.zip` of human-readable Markdown plus machine-readable JSON and a SHA-256 `manifest.json`. The bundle is readable with **zero PortOS running** (plain files, no database), opens with a privacy banner, and degrades gracefully when a domain is empty. Secrets accidentally pasted into notes are redacted before anything leaves the box. `GET /api/legacy-export/preview` reports which sections are present and the estimated size without building the file. This is the server core of the Knowledge Legacy export; PDF rendering and a one-click UI are tracked as follow-ups. (#901)diff --git a/client/package.json b/client/package.jsonindex 79f5a225aa..5b6963e96a 100644--- a/client/package.json+++ b/client/package.json@@ -27,7 +27,8 @@"react-router-dom": "7.16.0","recharts": "3.7.0","socket.io-client": "4.8.3",- "three": "0.184.0"+ "three": "0.184.0",+ "three-fenestra": "^0.3.0"},"devDependencies": {"@eslint/js": "9.39.4",diff --git a/client/src/components/city/Borough.jsx b/client/src/components/city/Borough.jsxindex f85babf17d..005fa4f670 100644--- a/client/src/components/city/Borough.jsx+++ b/client/src/components/city/Borough.jsx@@ -1,5 +1,5 @@import { useMemo } from 'react';-import { getBuildingHeight, BOROUGH_PARAMS, cityDayMix, cityShowDetail } from './cityConstants';+import { getBuildingHeight, BOROUGH_PARAMS, cityDayMix, cityShowDetail, cityShowInteriorWindows } from './cityConstants';import { hashString } from '../../utils/hashString';import Building from './Building';import AgentEntity from './AgentEntity';@@ -47,6 +47,7 @@ export default function Borough({ app, position, agentMap, onBuildingClick, playonClick={() => onBuildingClick?.(app)}playSfx={playSfx}rooftops={cityShowDetail(settings)}+ interiorWindows={cityShowInteriorWindows(settings)}neonBrightness={neonBrightness}isProximity={isProximity}dimmed={dimmed}diff --git a/client/src/components/city/Building.jsx b/client/src/components/city/Building.jsxindex cc45372e71..a0716054a3 100644--- a/client/src/components/city/Building.jsx+++ b/client/src/components/city/Building.jsx@@ -6,7 +6,9 @@ import { useCityPalette } from './CityPaletteContext';import CityLabel from './CityLabel';import HolographicPanel from './HolographicPanel';import BuildingHologram from './BuildingHologram';+import BuildingWindows from './BuildingWindows';import { computeRooftopKit } from '../../utils/cityRooftops';+import { buildingHasInteriorWindows } from '../../utils/cityInteriorWindows';// Rooftop fixture geometry/materials are module-scope singletons shared by every// building — fixtures are tiny set dressing, so they keep fixed colors (the antenna@@ -392,7 +394,7 @@ function FloorLightBands({ width, depth, height, color, accentColor, seed, dimMu);}-export default function Building({ app, position, agentCount, onClick, playSfx, neonBrightness = 1.2, isProximity = false, dimmed = false, dayMix = 0, playback = false, transitionState = null, onExited, rooftops = true }) {+export default function Building({ app, position, agentCount, onClick, playSfx, neonBrightness = 1.2, isProximity = false, dimmed = false, dayMix = 0, playback = false, transitionState = null, onExited, rooftops = true, interiorWindows = false }) {const meshRef = useRef();const glowRef = useRef();const haloRef = useRef();@@ -557,6 +559,22 @@ export default function Building({ app, position, agentCount, onClick, playSfx,/></mesh>+ {/* Interior-mapped window panes (three-fenestra) — parallax fake-3D lit+ rooms on selected online towers. Night-only (by day the tower reads as a+ sunlit solid) and gated to the high quality preset by the caller. */}+ {!daytime && interiorWindows && buildingHasInteriorWindows(app, height) && (+ <BuildingWindows+ width={width}+ depth={depth}+ height={height}+ seed={seed}+ accentColor={accentColor}+ edgeColor={edgeColor}+ neonBrightness={neonBrightness}+ dimMul={dimMul}+ />+ )}+{/* Building edges — bright neon by night, a plain architectural outline by day */}<lineSegments position={[0, height / 2, 0]} geometry={edgesGeom}><lineBasicMaterialdiff --git a/client/src/components/city/BuildingWindows.jsx b/client/src/components/city/BuildingWindows.jsxnew file mode 100644index 0000000000..9a3d6f45ab--- /dev/null+++ b/client/src/components/city/BuildingWindows.jsx@@ -0,0 +1,204 @@+import { useMemo, useEffect } from 'react';+import * as THREE from 'three';+import { InteriorMappingMaterial } from 'three-fenestra';+import { computeWindowGrid, INTERIOR_WINDOW } from '../../utils/cityInteriorWindows';+import { mixHex, seededRand } from './cityConstants';++// Interior-mapped window panes for a building, using the three-fenestra+// InteriorMappingMaterial — a parallax shader that fakes furnished 3D rooms+// behind flat window planes (no real interior geometry). Selected towers get a+// grid of these panes proud of each face so you can "look into" lit rooms as the+// camera moves, instead of the flat emissive window texture alone.+//+// Every pane of every building is ONE InstancedMesh draw call: the grid math+// (cityInteriorWindows.computeWindowGrid) places each pane, and a deterministic+// per-pane `instanceWindowId` drives the shader's room-cell pick + lit/unlit and+// warm/cool variation entirely on the GPU. Night-only + high-quality-preset+// gated by the callers (Building / Borough), since the ray-march costs more than+// the flat texture.++const ATLAS_COLS = 4;+const ATLAS_ROWS = 4;++// Shared, palette-neutral interior-room atlas (4×4 = 16 room variants). Built+// once and reused by every building — the per-building warm/cool tint comes from+// the material's emissiveVariation, not the atlas, so a single grayscale-ish+// atlas serves the whole city (and never needs disposing, like the rooftop-kit+// singletons). Lazy so importing this module stays side-effect-free; returns+// null under headless/jsdom where canvas has no 2d context.+let _atlas = null;+function getInteriorAtlas() {+ if (_atlas) return _atlas;+ const cell = 128;+ const canvas = document.createElement('canvas');+ canvas.width = cell * ATLAS_COLS;+ canvas.height = cell * ATLAS_ROWS;+ const ctx = canvas.getContext('2d');+ if (!ctx) return null;++ for (let row = 0; row < ATLAS_ROWS; row++) {+ for (let col = 0; col < ATLAS_COLS; col++) {+ const ox = col * cell;+ const oy = row * cell;+ const rand = seededRand(row * ATLAS_COLS + col + 1);++ // Back wall, floor band, ceiling band — neutral warm-gray so the emissive+ // tint reads as the room's light color rather than fighting a hue.+ ctx.fillStyle = '#3a3a42';+ ctx.fillRect(ox, oy, cell, cell);+ ctx.fillStyle = '#2b2b32';+ ctx.fillRect(ox, oy, cell, cell * 0.12);+ ctx.fillStyle = '#4c4c55';+ ctx.fillRect(ox, oy + cell * 0.7, cell, cell * 0.3);++ // 1–3 furniture silhouettes standing on the floor (desk/shelf/monitor).+ const pieces = 1 + Math.floor(rand() * 3);+ for (let p = 0; p < pieces; p++) {+ const w = cell * (0.18 + rand() * 0.24);+ const h = cell * (0.18 + rand() * 0.34);+ const x = ox + cell * 0.08 + rand() * (cell * 0.84 - w);+ const y = oy + cell * 0.7 - h;+ const shade = 35 + Math.floor(rand() * 45);+ ctx.fillStyle = `rgb(${shade},${shade},${shade + 8})`;+ ctx.fillRect(x, y, w, h);+ }++ // Occasional lit focal element (screen/lamp) — a small near-white block+ // that the warm/cool emissive turns into the visible "lights on" glow.+ if (rand() > 0.3) {+ const w = cell * (0.1 + rand() * 0.14);+ const h = cell * (0.08 + rand() * 0.12);+ const x = ox + cell * 0.12 + rand() * (cell * 0.68);+ const y = oy + cell * 0.3 + rand() * (cell * 0.3);+ ctx.fillStyle = '#dfe6f0';+ ctx.fillRect(x, y, w, h);+ }+ }+ }++ const tex = new THREE.CanvasTexture(canvas);+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.wrapS = THREE.ClampToEdgeWrapping;+ tex.wrapT = THREE.ClampToEdgeWrapping;+ tex.minFilter = THREE.LinearFilter;+ tex.magFilter = THREE.LinearFilter;+ tex.needsUpdate = true;+ _atlas = tex;+ return _atlas;+}++// Hex → HDR-ish THREE.Color: emissive contributions want values >1 to read as a+// glow under tone mapping, mirroring three-fenestra's own warm/cool defaults.+function emissiveColor(hex, scale) {+ return new THREE.Color(hex).multiplyScalar(scale);+}++export default function BuildingWindows({+ width,+ depth,+ height,+ seed = 0,+ accentColor,+ edgeColor,+ neonBrightness = 1.2,+ dimMul = 1,+}) {+ const atlas = getInteriorAtlas();++ // Geometry + per-pane instance data. Independent of palette/dim so a theme or+ // proximity-dim change doesn't rebuild the (potentially hundreds of) panes.+ const built = useMemo(() => {+ if (!atlas) return null;+ const windows = computeWindowGrid({ width, depth, height, seed });+ if (windows.length === 0) return null;++ const size = INTERIOR_WINDOW.size;+ const geo = new THREE.PlaneGeometry(size, size);+ const count = windows.length;+ const ids = new Float32Array(count * 3);+ const lods = new Float32Array(count).fill(1);+ const fades = new Float32Array(count).fill(1);+ const matrices = new Array(count);++ const m = new THREE.Matrix4();+ const q = new THREE.Quaternion();+ const e = new THREE.Euler();+ const v = new THREE.Vector3();+ const one = new THREE.Vector3(1, 1, 1);+ windows.forEach((w, i) => {+ e.set(0, w.rotationY, 0);+ q.setFromEuler(e);+ v.set(w.position[0], w.position[1], w.position[2]);+ m.compose(v, q, one);+ matrices[i] = m.clone();+ ids[i * 3] = w.windowId[0];+ ids[i * 3 + 1] = w.windowId[1];+ ids[i * 3 + 2] = w.windowId[2];+ });++ geo.setAttribute('instanceWindowId', new THREE.InstancedBufferAttribute(ids, 3));+ geo.setAttribute('instanceLod', new THREE.InstancedBufferAttribute(lods, 1));+ geo.setAttribute('instanceFade', new THREE.InstancedBufferAttribute(fades, 1));+ return { geo, matrices, count };+ }, [atlas, width, depth, height, seed]);++ // Palette-driven material — emissiveVariation gives per-window lit/unlit and+ // warm/cool rooms, with the cool tone pulled toward the building's neon accent+ // so the windows stay in-family with the rest of the scene.+ const material = useMemo(() => {+ if (!atlas) return null;+ const nb = neonBrightness;+ return new InteriorMappingMaterial({+ backAtlas: atlas,+ backAtlasCols: ATLAS_COLS,+ backAtlasRows: ATLAS_ROWS,+ planeSize: new THREE.Vector2(INTERIOR_WINDOW.size, INTERIOR_WINDOW.size),+ instanced: true,+ depth: 0.7,+ backScale: 0.6,+ roughness: 0.18,+ metalness: 0,+ transparent: true,+ glassFresnelStrength: 0.35,+ glassFresnelColor: emissiveColor(mixHex('#e8f0ff', accentColor, 0.2), 1),+ emissiveVariation: {+ litRatio: 0.55,+ warm: emissiveColor(mixHex('#ffd9a8', accentColor, 0.1), 1.6 * nb),+ cool: emissiveColor(accentColor, 1.4 * nb),+ coolChance: 0.5,+ brightMin: 0.35,+ brightRange: 0.5,+ dim: emissiveColor(edgeColor, 0.08),+ },+ });+ }, [atlas, accentColor, edgeColor, neonBrightness]);++ const mesh = useMemo(() => {+ if (!built || !material) return null;+ const im = new THREE.InstancedMesh(built.geo, material, built.count);+ for (let i = 0; i < built.count; i++) im.setMatrixAt(i, built.matrices[i]);+ im.instanceMatrix.needsUpdate = true;+ // Derive the bounding sphere from the instance matrices (the geometry's own+ // sphere is a single pane at the origin) so off-screen towers still cull.+ im.computeBoundingSphere();+ return im;+ }, [built, material]);++ // Proximity dim scales each pane's output alpha via instanceFade — done live so+ // a dim toggle never rebuilds the mesh. Re-applied whenever the mesh is rebuilt+ // too, since a fresh InstancedMesh starts with every fade at 1.+ useEffect(() => {+ if (!mesh) return;+ const attr = mesh.geometry.getAttribute('instanceFade');+ for (let i = 0; i < attr.count; i++) attr.setX(i, dimMul);+ attr.needsUpdate = true;+ }, [mesh, dimMul]);++ // R3F only auto-disposes objects it created via JSX; these are built+ // imperatively, so free their GPU buffers on replace/unmount ourselves.+ useEffect(() => (built ? () => built.geo.dispose() : undefined), [built]);+ useEffect(() => (material ? () => material.dispose() : undefined), [material]);++ if (!mesh) return null;+ return <primitive object={mesh} />;+}diff --git a/client/src/components/city/cityConstants.js b/client/src/components/city/cityConstants.jsindex b1098ef701..c8befabe2b 100644--- a/client/src/components/city/cityConstants.js+++ b/client/src/components/city/cityConstants.js@@ -220,6 +220,13 @@ export const cityDayMix = (settings) => {// boundary is exact-0.5-excluded on purpose: the low preset renders structure only.export const cityShowDetail = (settings) => (settings?.particleDensity ?? 1) > 0.5;+// True when the active quality preset is "high" or above (particleDensity ≥ 1.0)+// — the gate for the heavier three-fenestra interior-mapping window panes, which+// ray-march a fake interior per pane and so cost more than the flat window+// texture. Held one tier above cityShowDetail so medium-tier machines keep the+// rest of the set dressing but skip the per-pane interior shader.+export const cityShowInteriorWindows = (settings) => (settings?.particleDensity ?? 1) >= 1;+// Drei <Text> props for an informational in-world label that stays legible in both// the night-neon scene AND the bright daytime scene. At night (dayMix→0) the label// keeps its neon fill with no outline, so the established look is untouched. As daydiff --git a/client/src/components/city/cityTheme.test.js b/client/src/components/city/cityTheme.test.jsindex 0b69029b6b..fee7ac3385 100644--- a/client/src/components/city/cityTheme.test.js+++ b/client/src/components/city/cityTheme.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { deriveCityPalette, resolveCityTimeOfDay, cityLabelColors, tintTowardAccent, tintStructure, CITY_COLORS, getBuildingColor, getAccentColor, seededRand, smoothstepRange, cityDayMix, getTimeOfDayPreset } from './cityConstants';+import { deriveCityPalette, resolveCityTimeOfDay, cityLabelColors, tintTowardAccent, tintStructure, CITY_COLORS, getBuildingColor, getAccentColor, seededRand, smoothstepRange, cityDayMix, getTimeOfDayPreset, cityShowDetail, cityShowInteriorWindows } from './cityConstants';const hexLum = (hex) => {const n = parseInt(hex.slice(1), 16);@@ -298,3 +298,20 @@ describe('cityDayMix', () => {expect(cityDayMix(undefined)).toBe(0);});});++describe('quality-preset gates', () => {+ // Preset densities: low 0.5, medium 0.75, high 1.0, ultra 1.5.+ it('cityShowDetail turns on above the low preset', () => {+ expect(cityShowDetail({ particleDensity: 0.5 })).toBe(false);+ expect(cityShowDetail({ particleDensity: 0.75 })).toBe(true);+ expect(cityShowDetail(undefined)).toBe(true); // defaults to 1+ });++ it('cityShowInteriorWindows holds one tier above detail (high+)', () => {+ expect(cityShowInteriorWindows({ particleDensity: 0.5 })).toBe(false);+ expect(cityShowInteriorWindows({ particleDensity: 0.75 })).toBe(false);+ expect(cityShowInteriorWindows({ particleDensity: 1.0 })).toBe(true);+ expect(cityShowInteriorWindows({ particleDensity: 1.5 })).toBe(true);+ expect(cityShowInteriorWindows(undefined)).toBe(true); // defaults to 1+ });+});diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 30e9b08354..d71cc67aad 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -79,6 +79,7 @@ its tunable constants and placement helpers.| `cityFlowLines` | Inter-building flow-line connections between active/agent nodes (`computeFlowConnections`). || `cityGoalMonuments` | Goal monuments & forest: stall detection, milestone segments, placement (`computeGoalMonuments`, `computeGoalForest`). || `cityHealthTower` | Health-metric tower segments from the latest health entry (`computeHealthTower`). |+| `cityInteriorWindows` | Per-building interior-mapping window grid + selection predicate for three-fenestra panes (`computeWindowGrid`, `buildingHasInteriorWindows`, `INTERIOR_WINDOW`). || `cityJiraDistrict` | Jira ticket district: ticket state, sprint structures, placement (`computeJiraDistrict`). || `cityMemoryDistrict` | Brain-graph memory district: category clustering, bridges, placement (`computeMemoryDistrict`). || `cityMiniMap` | Mini-map projection of building positions into 2D bounds, plus opt-in waterfront geography (bay/shoreline/harbor) read from `cityPlan` (`computeMiniMap`, `projectPoint`, `geographyWorldPoints`, `projectGeography`). |diff --git a/client/src/utils/cityInteriorWindows.js b/client/src/utils/cityInteriorWindows.jsnew file mode 100644index 0000000000..d980680da4--- /dev/null+++ b/client/src/utils/cityInteriorWindows.js@@ -0,0 +1,105 @@+// Procedural window-grid layout for CyberCity buildings that use the+// three-fenestra interior-mapping material (parallax fake-3D rooms behind flat+// window panes). The geometry/material live in+// `client/src/components/city/BuildingWindows.jsx`; this module is the pure,+// side-effect-free math it consumes so the placement is unit-testable without a+// WebGL context (headless GL can't render the city — see the city visual+// verification notes).+//+// A building's four vertical faces are each tiled with a centered grid of square+// panes. Each pane becomes one InstancedMesh instance carrying a deterministic+// `windowId` (vec3) the shader hashes to pick an interior room cell and to decide+// lit/unlit + warm/cool, so a building keeps the exact same lit rooms forever+// (same determinism contract as the flat window texture and rooftop kits).++// Pane + spacing geometry, in building-local world units. Tuned so a default+// 2.0-wide face reads as ~4 columns of distinct windows and a 5-tall online+// tower as ~7 stacked floors.+export const INTERIOR_WINDOW = {+ size: 0.26, // square pane edge+ gapX: 0.14, // horizontal gap between panes+ gapY: 0.22, // vertical gap (taller → reads as stacked floors)+ inset: 0.015, // how far the pane sits proud of the wall (avoids z-fighting)+ edgePad: 0.2, // horizontal margin kept clear at each face edge+ marginBottom: 0.5, // skip the ground-floor / base-glow band+ marginTop: 0.5, // skip the roof cap + crown floor band+ // Below this building height there isn't enough clear facade for a readable+ // grid, so the building keeps just its flat emissive window texture.+ minHeight: 3,+};++// Which buildings get interior-mapped windows. Kept deliberately narrow ("some+// of the buildings"): online, non-archived towers tall enough for a real grid.+// Stopped/idle/short buildings stay on the cheaper flat texture. Height is read+// from the already-resolved value (getBuildingHeight) rather than recomputed.+export function buildingHasInteriorWindows(app, height) {+ if (!app || app.archived) return false;+ if (!(height >= INTERIOR_WINDOW.minHeight)) return false;+ return app.overallStatus === 'online';+}++// Count panes that fit along a span, centered, given pane size + gap. Returns 0+// when not even one pane fits in the usable span.+function fitCount(span, size, gap) {+ if (!(span > 0)) return 0;+ return Math.max(0, Math.floor((span + gap) / (size + gap)));+}++// The four vertical faces, as (faceIndex, rotationY about the building's up axis,+// outward normal axis + sign). PlaneGeometry faces +Z at rotation 0.+const FACES = [+ { index: 0, axis: 'z', sign: 1, rotationY: 0 }, // front (+Z)+ { index: 1, axis: 'z', sign: -1, rotationY: Math.PI }, // back (-Z)+ { index: 2, axis: 'x', sign: 1, rotationY: Math.PI / 2 }, // right (+X)+ { index: 3, axis: 'x', sign: -1, rotationY: -Math.PI / 2 }, // left (-X)+];++// Compute every window instance for a building. Returns a flat array of+// `{ position: [x,y,z], rotationY, windowId: [a,b,c] }`. `planeSize` (the square+// pane edge) is uniform across all panes, so the material's `planeSize` uniform+// is just `INTERIOR_WINDOW.size`.+export function computeWindowGrid({ width, depth, height, seed = 0 }) {+ const { size, gapX, gapY, inset, edgePad, marginBottom, marginTop } = INTERIOR_WINDOW;+ const usableH = height - marginBottom - marginTop;+ const rows = fitCount(usableH, size, gapY);+ if (rows <= 0) return [];++ const gridH = rows * size + (rows - 1) * gapY;+ const startY = marginBottom + (usableH - gridH) / 2 + size / 2;+ const stepY = size + gapY;++ const windows = [];+ for (const face of FACES) {+ // The horizontal extent of this face: building width for front/back, depth+ // for the sides. The pane plane is always normal to the face's axis.+ const faceWidth = face.axis === 'z' ? width : depth;+ const usableW = faceWidth - 2 * edgePad;+ const cols = fitCount(usableW, size, gapX);+ if (cols <= 0) continue;++ const gridW = cols * size + (cols - 1) * gapX;+ const startH = -gridW / 2 + size / 2;+ const stepX = size + gapX;+ // Distance from center out to the (slightly proud) face plane.+ const offset = (face.axis === 'z' ? depth : width) / 2 + inset;++ for (let r = 0; r < rows; r++) {+ const y = startY + r * stepY;+ for (let c = 0; c < cols; c++) {+ const h = startH + c * stepX; // position along the face's horizontal axis+ const position = face.axis === 'z'+ ? [h, y, face.sign * offset]+ : [face.sign * offset, y, h];+ // Deterministic, well-spread seed per pane so the shader hash varies+ // per window, per face, and per building.+ const windowId = [+ c + face.index * 3.1 + seed * 0.37,+ r + face.index * 1.7 + seed * 0.21,+ face.index + (seed % 17) * 0.13,+ ];+ windows.push({ position, rotationY: face.rotationY, windowId });+ }+ }+ }+ return windows;+}diff --git a/client/src/utils/cityInteriorWindows.test.js b/client/src/utils/cityInteriorWindows.test.jsnew file mode 100644index 0000000000..5d8292e0b1--- /dev/null+++ b/client/src/utils/cityInteriorWindows.test.js@@ -0,0 +1,83 @@+import { describe, it, expect } from 'vitest';+import {+ INTERIOR_WINDOW,+ buildingHasInteriorWindows,+ computeWindowGrid,+} from './cityInteriorWindows';++describe('buildingHasInteriorWindows', () => {+ it('selects online, non-archived towers tall enough for a grid', () => {+ expect(buildingHasInteriorWindows({ overallStatus: 'online' }, 5)).toBe(true);+ });++ it('rejects archived buildings even when online and tall', () => {+ expect(buildingHasInteriorWindows({ overallStatus: 'online', archived: true }, 5)).toBe(false);+ });++ it('rejects non-online statuses', () => {+ for (const overallStatus of ['stopped', 'not_started', 'not_found', 'unknown']) {+ expect(buildingHasInteriorWindows({ overallStatus }, 5)).toBe(false);+ }+ });++ it('rejects towers below the minimum height', () => {+ expect(buildingHasInteriorWindows({ overallStatus: 'online' }, INTERIOR_WINDOW.minHeight - 0.01)).toBe(false);+ expect(buildingHasInteriorWindows({ overallStatus: 'online' }, INTERIOR_WINDOW.minHeight)).toBe(true);+ });++ it('rejects a missing app', () => {+ expect(buildingHasInteriorWindows(null, 5)).toBe(false);+ expect(buildingHasInteriorWindows(undefined, 5)).toBe(false);+ });+});++describe('computeWindowGrid', () => {+ const dims = { width: 2, depth: 2, height: 5, seed: 42 };++ it('tiles all four vertical faces', () => {+ const windows = computeWindowGrid(dims);+ expect(windows.length).toBeGreaterThan(0);+ const rotations = new Set(windows.map((w) => w.rotationY.toFixed(4)));+ expect(rotations).toEqual(+ new Set([0, Math.PI, Math.PI / 2, -Math.PI / 2].map((r) => r.toFixed(4)))+ );+ });++ it('is deterministic for the same input', () => {+ expect(computeWindowGrid(dims)).toEqual(computeWindowGrid(dims));+ });++ it('varies window ids by seed', () => {+ const a = computeWindowGrid(dims);+ const b = computeWindowGrid({ ...dims, seed: 43 });+ expect(a[0].windowId).not.toEqual(b[0].windowId);+ });++ it('places panes proud of the correct face plane', () => {+ const { width, depth } = dims;+ const offset = depth / 2 + INTERIOR_WINDOW.inset;+ for (const w of computeWindowGrid(dims)) {+ const [x, , z] = w.position;+ if (w.rotationY === 0) expect(z).toBeCloseTo(offset, 5);+ else if (w.rotationY === Math.PI) expect(z).toBeCloseTo(-offset, 5);+ else if (w.rotationY === Math.PI / 2) expect(x).toBeCloseTo(width / 2 + INTERIOR_WINDOW.inset, 5);+ else if (w.rotationY === -Math.PI / 2) expect(x).toBeCloseTo(-(width / 2 + INTERIOR_WINDOW.inset), 5);+ }+ });++ it('keeps every pane within the usable vertical band and face width', () => {+ const { width, height } = dims;+ for (const w of computeWindowGrid(dims)) {+ const [x, y, z] = w.position;+ expect(y).toBeGreaterThanOrEqual(INTERIOR_WINDOW.marginBottom);+ expect(y).toBeLessThanOrEqual(height - INTERIOR_WINDOW.marginTop);+ // The horizontal axis of each face stays inside the face half-width.+ const horiz = w.rotationY === 0 || w.rotationY === Math.PI ? x : z;+ expect(Math.abs(horiz)).toBeLessThanOrEqual(width / 2);+ }+ });++ it('returns no windows when the tower is too short for a single row', () => {+ expect(computeWindowGrid({ width: 2, depth: 2, height: 1, seed: 1 })).toEqual([]);+ });+});diff --git a/client/src/utils/index.js b/client/src/utils/index.jsindex ed8b18bded..39db3e5dfd 100644--- a/client/src/utils/index.js+++ b/client/src/utils/index.js@@ -48,6 +48,7 @@ export * from './cityFilter.js';export * from './cityFlowLines.js';export * from './cityGoalMonuments.js';export * from './cityHealthTower.js';+export * from './cityInteriorWindows.js';export * from './cityJiraDistrict.js';export * from './cityMemoryDistrict.js';export * from './cityMiniMap.js';