@iwsdk/vite-plugin-dev 1.0.1-rc.0 → 1.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ var n="// Generated by @iwer/sem rooms/build.mjs from rooms/src/kit.ts and rooms/src/open_office.ts; edit those and rebuild.\nimport * as THREE from 'three';\nimport { onDispose, onFrame, scene } from '@drawcall/glts';\n\n// IWER room kit: shared building blocks for procedural GLTS rooms.\n// The builders are used by the room scripts this file is concatenated with.\n/* eslint-disable @typescript-eslint/no-unused-vars */\n//\n// A room script calls createRoom(spec) once, builds its furniture with the\n// builders below, then calls room.finish(). Builders tag WebXR planes\n// (userData.xrPlane) and add invisible volumes (userData.xrMesh) that also\n// shape the baked lighting. finish() adds the shell (floor, ceiling, walls\n// with window openings, windows, doors, baseboards, downlights), bakes\n// lightmaps and furniture ambient occlusion, merges static meshes per\n// material, paints the reflection probe and adds the sun.\n//\n// Conventions (meters): +Y up; the viewer starts at the origin facing -Z, so\n// keep the origin on open floor. The room spans x in [-width/2, width/2] and\n// z in [z0, z0 + depth]. Walls: back (-Z), front (+Z), left (-X), right (+X).\n// A position \"at\" along a wall is world x for back/front walls and world z\n// for left/right walls. Builders face +Z (their back is at local -Z), so\n// room.against(wall, ...) turns them to face into the room.\n//\n// SEM reports the scene's static geometry as the room's 'global mesh' (a\n// Quest behavior); objects that move or lie outside the room are tagged\n// userData.xrGlobalMesh = false. finish() merges untagged static meshes, so\n// an animated object must be tagged or added after finish().\n//\n// Realism limits: a Quest room scan covers at most 10 x 10 m, and a scanned\n// room holds a few dozen detected objects (the office_large capture has 38).\n// createRoom rejects larger rooms and finish() warns above 40 planes and\n// meshes.\n\ntype Vec3 = [number, number, number];\ntype Wall = 'back' | 'front' | 'left' | 'right';\nconst WALLS: Wall[] = ['back', 'front', 'left', 'right'];\nconst MAX_ROOM_SIZE = 10;\nconst MAX_ENTITIES = 40;\n\nconst owned: { dispose(): void }[] = [];\nfunction own<T extends { dispose(): void }>(value: T): T {\n owned.push(value);\n return value;\n}\nonDispose(() => owned.forEach((value) => value.dispose()));\n\nfunction once<T>(make: () => T): () => T {\n let value: T | undefined;\n return () => (value ??= make());\n}\n\n// ------------------------------------------------------------------ noise\n\nfunction hash(x: number, y: number, seed: number) {\n let h =\n Math.imul(x | 0, 374761393) ^\n Math.imul(y | 0, 668265263) ^\n Math.imul(seed | 0, 982451653);\n h = Math.imul(h ^ (h >>> 13), 1274126177);\n return ((h ^ (h >>> 16)) >>> 0) / 4294967295;\n}\n\nconst mod = (a: number, n: number) => ((a % n) + n) % n;\nconst clamp01 = (v: number) => Math.min(1, Math.max(0, v));\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\n\n// Value noise, tileable with integer periods px / py.\nfunction noise(x: number, y: number, seed: number, px: number, py: number) {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const fx = x - ix;\n const fy = y - iy;\n const ux = fx * fx * (3 - 2 * fx);\n const uy = fy * fy * (3 - 2 * fy);\n const x0 = mod(ix, px);\n const x1 = mod(ix + 1, px);\n const y0 = mod(iy, py);\n const y1 = mod(iy + 1, py);\n const a = hash(x0, y0, seed);\n const b = hash(x1, y0, seed);\n const c = hash(x0, y1, seed);\n const d = hash(x1, y1, seed);\n return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy;\n}\n\nfunction fbm(\n x: number,\n y: number,\n seed: number,\n octaves: number,\n px = 1 << 16,\n py = 1 << 16,\n) {\n let sum = 0;\n let amp = 0.5;\n let norm = 0;\n for (let o = 0; o < octaves; o++) {\n sum += amp * noise(x, y, seed + o * 17, px, py);\n norm += amp;\n x *= 2;\n y *= 2;\n px *= 2;\n py *= 2;\n amp *= 0.5;\n }\n return sum / norm;\n}\n\n// --------------------------------------------------------------- textures\n\ntype RGBA = [number, number, number, number?];\n\n// Fills `count` canvases in one pass; `pixel` returns one color per canvas.\n// u, v are in [0, 1) with v = 0 at the bottom (texture convention).\nfunction paint(\n width: number,\n height: number,\n count: number,\n pixel: (u: number, v: number) => RGBA[],\n) {\n const canvases = Array.from({ length: count }, () => {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n });\n const images = canvases.map((canvas) =>\n canvas.getContext('2d')!.createImageData(width, height),\n );\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const colors = pixel((x + 0.5) / width, 1 - (y + 0.5) / height);\n const i = (y * width + x) * 4;\n for (let c = 0; c < count; c++) {\n const [r, g, b, a = 1] = colors[c];\n const data = images[c].data;\n data[i] = clamp01(r) * 255;\n data[i + 1] = clamp01(g) * 255;\n data[i + 2] = clamp01(b) * 255;\n data[i + 3] = clamp01(a) * 255;\n }\n }\n }\n canvases.forEach((canvas, c) =>\n canvas.getContext('2d')!.putImageData(images[c], 0, 0),\n );\n return canvases;\n}\n\n// A repeating texture; geometry UVs are in meters, so `meters` is the tile.\nfunction tiled(\n canvas: HTMLCanvasElement,\n color: boolean,\n metersU: number,\n metersV = metersU,\n) {\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = color ? THREE.SRGBColorSpace : THREE.NoColorSpace;\n tex.wrapS = tex.wrapT = THREE.RepeatWrapping;\n tex.repeat.set(1 / metersU, 1 / metersV);\n tex.anisotropy = 8;\n return tex;\n}\n\n// A texture covering a centered w x h panel (UVs in meters).\nfunction fitted(canvas: HTMLCanvasElement, w: number, h: number) {\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n tex.repeat.set(1 / w, 1 / h);\n tex.offset.set(0.5, 0.5);\n tex.anisotropy = 8;\n return tex;\n}\n\nfunction canvasTexture(canvas: HTMLCanvasElement) {\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n return tex;\n}\n\n// Engineered oak: a 2 m x 4 m tile of 20 cm planks, 1-2 m long.\nconst oakTextures = once(() => {\n const planks = 10;\n const lengths = [2, 4 / 3, 2, 1, 4 / 3, 2, 1, 4 / 3, 2, 4 / 3];\n const shifts = lengths.map((_, i) => hash(i, 3, 7) * 4);\n const [color, rough, bump] = paint(512, 1024, 3, (u, v) => {\n const column = Math.floor(u * planks);\n const across = u * planks - column;\n const along = mod(v * 4 + shifts[column], 4);\n const row = Math.floor(along / lengths[column]);\n const end = along - row * lengths[column];\n const seed = column * 31 + row * 7 + 1;\n const gap =\n Math.min(across, 1 - across) * 0.2 < 0.0012 ||\n Math.min(end, lengths[column] - end) < 0.0015;\n const offset = hash(seed, 1, 2) * 50;\n const warp = fbm(across * 2 + offset, along * 0.8, seed, 3) * 9;\n const grain = 0.5 + 0.5 * Math.sin(across * 26 + warp);\n const fine = fbm(across * 40, along * 2 + offset, seed + 3, 2);\n const tone = 0.94 + (hash(seed, 2, 9) - 0.5) * 0.12;\n const t = tone * (0.9 + 0.07 * grain + 0.06 * fine);\n const shade = gap ? 0.55 : 1;\n const r = gap ? 0.9 : 0.45 + 0.1 * hash(seed, 4, 4);\n const b = gap ? 0 : 0.7 + 0.12 * grain + 0.05 * fine;\n return [\n [0.8 * t * shade, 0.65 * t * shade, 0.48 * t * shade],\n [r, r, r],\n [b, b, b],\n ];\n });\n return {\n map: tiled(color, true, 2, 4),\n roughnessMap: tiled(rough, false, 2, 4),\n bumpMap: tiled(bump, false, 2, 4),\n };\n});\n\n// Fine plaster bump, 1 m tile.\nconst plasterBump = once(() => {\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const b = 0.45 + 0.4 * fbm(u * 16, v * 16, 3, 4, 16, 16);\n return [[b, b, b]];\n });\n return tiled(canvas, false, 1);\n});\n\n// Woven fabric color + bump, 10 cm tile.\nconst fabricTextures = new Map<\n number,\n { map: THREE.Texture; bumpMap: THREE.Texture }\n>();\nfunction fabricTexture(seed: number) {\n let textures = fabricTextures.get(seed);\n if (!textures) {\n const threads = 48;\n const [color, bump] = paint(128, 128, 2, (u, v) => {\n const cell = (Math.floor(u * threads) + Math.floor(v * threads)) % 2;\n const warp = Math.sin(mod(u * threads, 1) * Math.PI);\n const weft = Math.sin(mod(v * threads, 1) * Math.PI);\n const thread = cell ? warp : weft;\n const slub = fbm(u * 6, v * 48, seed, 3, 6, 48);\n const t = 0.86 + 0.08 * thread + 0.1 * slub;\n return [\n [t, t, t],\n [thread, thread, thread],\n ];\n });\n textures = {\n map: tiled(color, true, 0.1),\n bumpMap: tiled(bump, false, 0.1),\n };\n fabricTextures.set(seed, textures);\n }\n return textures;\n}\n\n// Walnut veneer, 1 m tile, grain along U.\nconst walnutTexture = once(() => {\n const [canvas] = paint(512, 512, 1, (u, v) => {\n const warp = fbm(u * 3, v * 8, 11, 4, 3, 8) * 5;\n const ring = 0.5 + 0.5 * Math.sin((v * 90 + warp) * Math.PI);\n const pores = fbm(u * 160, v * 24, 12, 2, 160, 24);\n const t = 0.8 + 0.12 * ring + 0.1 * pores;\n return [[0.33 * t, 0.2 * t, 0.12 * t]];\n });\n return tiled(canvas, true, 1);\n});\n\n// Light oak veneer for furniture, 1 m tile, grain along U.\nconst oakVeneerTexture = once(() => {\n const [canvas] = paint(512, 512, 1, (u, v) => {\n const warp = fbm(u * 2, v * 6, 13, 4, 2, 6) * 6;\n const ring = 0.5 + 0.5 * Math.sin((v * 60 + warp) * Math.PI);\n const pores = fbm(u * 140, v * 20, 14, 2, 140, 20);\n const t = 0.88 + 0.07 * ring + 0.07 * pores;\n return [[0.78 * t, 0.62 * t, 0.44 * t]];\n });\n return tiled(canvas, true, 1);\n});\n\n// Short-pile carpet tiles, 50 cm tile with a faint seam.\nconst carpetTexture = once(() => {\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const fiber =\n (fbm(u * 120, v * 120, 61, 2) - 0.5) * 0.12 +\n (fbm(u * 6, v * 6, 62, 3) - 0.5) * 0.06;\n const seam = Math.min(u, 1 - u, v, 1 - v) < 0.006 ? 0.92 : 1;\n const t = (0.62 + fiber) * seam;\n return [[t, t * 0.97, t * 0.92]];\n });\n return tiled(canvas, true, 0.5);\n});\n\n// Polished concrete, 2 m tile.\nconst concreteTexture = once(() => {\n const [canvas] = paint(512, 512, 1, (u, v) => {\n const cloud = fbm(u * 6, v * 6, 71, 5, 6, 6);\n const speck =\n hash(Math.floor(u * 512), Math.floor(v * 512), 72) > 0.985 ? 0.9 : 1;\n const t = (0.72 + 0.12 * cloud) * speck;\n return [[t, t * 0.98, t * 0.95]];\n });\n return tiled(canvas, true, 2);\n});\n\n// Square glazed tiles with grout; `color` is the tile color.\nconst tileTextures = new Map<string, THREE.Texture>();\nfunction tileTexture(color: string, tile = 0.1) {\n const key = `${color}:${tile}`;\n let tex = tileTextures.get(key);\n if (!tex) {\n const c = new THREE.Color(color);\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const gu = mod(u * 4, 1);\n const gv = mod(v * 4, 1);\n if (Math.min(gu, 1 - gu, gv, 1 - gv) < 0.03) return [[0.86, 0.84, 0.8]];\n const cell = hash(Math.floor(u * 4), Math.floor(v * 4), 81);\n const t = 0.92 + 0.12 * cell + 0.04 * fbm(u * 20, v * 20, 82, 2);\n return [[c.r * t, c.g * t, c.b * t]];\n });\n tex = tiled(canvas, true, tile * 4);\n tileTextures.set(key, tex);\n }\n return tex;\n}\n\n// Cork board, 50 cm tile.\nconst corkTexture = once(() => {\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const grain = fbm(u * 60, v * 60, 91, 3);\n const t = 0.7 + 0.35 * grain;\n return [[0.72 * t, 0.53 * t, 0.36 * t]];\n });\n return tiled(canvas, true, 0.5);\n});\n\n// Rugs: 'lattice' (ivory field, charcoal lattice), 'border' (plain field with\n// a band), 'stripe' (woven stripes) or 'plain'.\ntype RugStyle = 'lattice' | 'border' | 'stripe' | 'plain';\nfunction rugCanvas(\n w: number,\n h: number,\n style: RugStyle,\n field: string,\n accent: string,\n) {\n const f = new THREE.Color(field);\n const a = new THREE.Color(accent);\n const [canvas] = paint(512, Math.round((512 * h) / w), 1, (u, v) => {\n const x = u * w;\n const y = v * h;\n const fiber =\n (fbm(x * 140, y * 140, 21, 2) - 0.5) * 0.14 +\n (fbm(x * 3, y * 3, 22, 3) - 0.5) * 0.08;\n const border = Math.min(x, w - x, y, h - y);\n let accentHere = false;\n if (style === 'lattice') {\n const dx = Math.abs(mod(x / 0.32, 1) - 0.5);\n const dy = Math.abs(mod(y / 0.32, 1) - 0.5);\n accentHere =\n (border > 0.1 && border < 0.13) ||\n (border > 0.2 && Math.abs(dx + dy - 0.5) < 0.025);\n } else if (style === 'border') {\n accentHere = border > 0.08 && border < 0.16;\n } else if (style === 'stripe') {\n accentHere = mod(y / 0.24, 1) < 0.18;\n }\n const c = accentHere ? a : f;\n const t = 1 + fiber;\n return [[c.r * t, c.g * t, c.b * t]];\n });\n return canvas;\n}\n\n// Abstract painting with soft overlapping discs and a line.\nfunction paintingTexture(seed: number, palette: string[], aspect: number) {\n const width = 512;\n const height = Math.round(width / aspect);\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.fillStyle = '#e9e2d4';\n ctx.fillRect(0, 0, width, height);\n ctx.filter = 'blur(1.2px)';\n for (let i = 0; i < 4; i++) {\n ctx.globalAlpha = 0.88;\n ctx.fillStyle = palette[i % palette.length];\n ctx.beginPath();\n const r = (0.14 + hash(i, 1, seed) * 0.16) * Math.min(width, height) * 1.4;\n ctx.arc(\n (0.2 + hash(i, 2, seed) * 0.6) * width,\n (0.25 + hash(i, 3, seed) * 0.5) * height,\n r,\n 0,\n Math.PI * 2,\n );\n ctx.fill();\n }\n ctx.globalAlpha = 0.85;\n ctx.strokeStyle = '#1d1d1d';\n ctx.lineWidth = 4;\n ctx.beginPath();\n ctx.moveTo(width * 0.12, height * 0.8);\n ctx.bezierCurveTo(\n width * 0.35,\n height * 0.2,\n width * 0.65,\n height,\n width * 0.9,\n height * 0.2,\n );\n ctx.stroke();\n return canvasTexture(canvas);\n}\n\n// Line-drawn botanical print on paper.\nfunction botanicalTexture(seed: number) {\n const canvas = document.createElement('canvas');\n canvas.width = 400;\n canvas.height = 600;\n const ctx = canvas.getContext('2d')!;\n ctx.fillStyle = '#efe9de';\n ctx.fillRect(0, 0, 400, 600);\n ctx.strokeStyle = '#3d4a3a';\n ctx.lineWidth = 3;\n ctx.lineCap = 'round';\n ctx.beginPath();\n ctx.moveTo(200, 560);\n ctx.bezierCurveTo(190, 420, 230, 260, 205, 60);\n ctx.stroke();\n for (let i = 0; i < 7; i++) {\n const y = 500 - i * 62;\n const side = (i + seed) % 2 ? 1 : -1;\n const x = 200 + Math.sin(i + seed) * 8;\n ctx.beginPath();\n ctx.moveTo(x, y);\n ctx.quadraticCurveTo(x + side * 90, y - 70, x + side * 120, y - 20);\n ctx.quadraticCurveTo(x + side * 70, y + 10, x, y);\n ctx.stroke();\n }\n return canvasTexture(canvas);\n}\n\n// Minimal landscape: layered hills under a sun disc.\nfunction landscapeTexture(seed: number, aspect: number) {\n const width = 512;\n const height = Math.round(width / aspect);\n const hills = ['#c9b79c', '#9aa58a', '#6f7f62', '#556349'];\n const [canvas] = paint(width, height, 1, (u, v) => {\n const sun = Math.hypot(u - 0.62, (v - 0.72) / aspect) < 0.07;\n let c = new THREE.Color(sun ? '#c96f3e' : '#efe6d6');\n for (let i = 0; i < hills.length; i++) {\n const ridge =\n 0.55 -\n i * 0.12 +\n 0.06 * Math.sin(u * (3 + i) + seed + i * 2) +\n 0.02 * fbm(u * 8, i, seed + i, 2);\n if (v < ridge) c = new THREE.Color(hills[i]);\n }\n return [[c.r, c.g, c.b]];\n });\n return canvasTexture(canvas);\n}\n\n// Bright, hazy view out of a window: sky, a tree line, a hedge.\nconst outsideTexture = once(() => {\n const [canvas] = paint(1024, 512, 1, (u, v) => {\n const sky: Vec3 = [\n mix(0.97, 0.9, v),\n mix(0.98, 0.94, v),\n mix(0.99, 0.98, v),\n ];\n const ridge =\n 0.33 + 0.05 * fbm(u * 4, 0, 31, 3) + 0.02 * fbm(u * 40, v * 20, 32, 2);\n const foliage = clamp01((ridge - v) / 0.04);\n const leaf = fbm(u * 60, v * 40, 33, 4);\n const t = (0.45 + 0.6 * leaf) * mix(0.7, 1, v / 0.35);\n const haze = 0.2 * (v / 0.35);\n const green = [\n mix(0.42 * t, sky[0], haze),\n mix(0.52 * t, sky[1], haze),\n mix(0.36 * t, sky[2], haze),\n ];\n return [\n [\n mix(sky[0], green[0], foliage),\n mix(sky[1], green[1], foliage),\n mix(sky[2], green[2], foliage),\n ],\n ];\n });\n return canvasTexture(canvas);\n});\n\n// Softly lit corridor seen through interior glazing.\nconst corridorTexture = once(() => {\n const [canvas] = paint(512, 256, 1, (u, v) => {\n const wall = 0.8 + 0.06 * fbm(u * 4, v * 4, 101, 3);\n const floor = v < 0.22 ? 0.55 + 0.05 * fbm(u * 20, v * 20, 102, 2) : 0;\n const door =\n mod(u * 3, 1) > 0.42 && mod(u * 3, 1) < 0.58 && v < 0.75 && v >= 0.22;\n const light =\n Math.exp(-Math.pow((mod(u * 3, 1) - 0.5) / 0.25, 2)) * 0.08 * v;\n if (floor) return [[floor * 0.9, floor * 0.8, floor * 0.68]];\n if (door) return [[0.62, 0.5, 0.38]];\n const t = wall + light;\n return [[t, t * 0.98, t * 0.94]];\n });\n return canvasTexture(canvas);\n});\n\n// Broad leaf with veins; alpha cut-out.\nconst leafTextures = once(() => {\n const [color, bump] = paint(256, 256, 2, (u, v) => {\n const x = (u - 0.5) * 2;\n const waist = 1 - 0.12 * Math.exp(-Math.pow((v - 0.42) / 0.12, 2));\n const width =\n 0.96 *\n Math.pow(Math.sin(Math.PI * Math.pow(Math.min(v, 0.999), 0.5)), 0.6) *\n (0.5 + 0.5 * v) *\n waist;\n const inside = Math.abs(x) < width ? 1 : 0;\n const midrib = Math.abs(x) < 0.025 ? 1 : 0;\n const vein =\n Math.abs(mod(v * 5 - Math.abs(x) * 1.3, 1) - 0.5) < 0.03 ? 1 : 0;\n const shade = 0.82 + 0.18 * fbm(u * 6, v * 6, 41, 3);\n const edge =\n 1 - 0.2 * clamp01((Math.abs(x) / Math.max(width, 0.01) - 0.8) * 5);\n const light = (midrib ? 1.5 : vein ? 1.18 : 1) * edge;\n const height = midrib || vein ? 0.35 : 0.6;\n return [\n [\n 0.19 * shade * light,\n 0.31 * shade * light,\n 0.12 * shade * light,\n inside,\n ],\n [height, height, height],\n ];\n });\n const map = canvasTexture(color);\n return { map, bumpMap: own(new THREE.CanvasTexture(bump)) };\n});\n\n// ---------------------------------------------------------------- geometry\n\n// Scales BoxGeometry UVs (0..1 per face) to meters so tiled textures keep\n// their real-world size on any box.\nfunction meterUVs(\n geometry: THREE.BoxGeometry,\n w: number,\n h: number,\n d: number,\n) {\n const uv = geometry.getAttribute('uv');\n const perFace = uv.count / 6;\n const sizes = [\n [d, h],\n [d, h],\n [w, d],\n [w, d],\n [w, h],\n [w, h],\n ];\n for (let i = 0; i < uv.count; i++) {\n const [su, sv] = sizes[Math.floor(i / perFace)];\n uv.setXY(i, uv.getX(i) * su, uv.getY(i) * sv);\n }\n return geometry;\n}\n\n// Box with rounded edges; `puff` bulges the top/bottom faces like a cushion.\nfunction roundedBox(\n w: number,\n h: number,\n d: number,\n r: number,\n puff = 0,\n segments = 4,\n) {\n const geometry = own(\n meterUVs(\n new THREE.BoxGeometry(w, h, d, segments, segments, segments),\n w,\n h,\n d,\n ),\n );\n const position = geometry.getAttribute('position');\n const normal = geometry.getAttribute('normal');\n const p = new THREE.Vector3();\n const inner = new THREE.Vector3();\n const n = new THREE.Vector3();\n const hx = w / 2 - r;\n const hy = h / 2 - r;\n const hz = d / 2 - r;\n for (let i = 0; i < position.count; i++) {\n p.fromBufferAttribute(position, i);\n inner.set(\n THREE.MathUtils.clamp(p.x, -hx, hx),\n THREE.MathUtils.clamp(p.y, -hy, hy),\n THREE.MathUtils.clamp(p.z, -hz, hz),\n );\n n.subVectors(p, inner).normalize();\n p.copy(inner).addScaledVector(n, r);\n if (puff) {\n const fx = Math.max(0, 1 - Math.pow(p.x / (w / 2), 2));\n const fz = Math.max(0, 1 - Math.pow(p.z / (d / 2), 2));\n p.y += Math.sign(p.y) * puff * Math.sqrt(fx * fz);\n }\n position.setXYZ(i, p.x, p.y, p.z);\n normal.setXYZ(i, n.x, n.y, n.z);\n }\n if (puff) geometry.computeVertexNormals();\n return geometry;\n}\n\n// Rectangle in the XY plane, UVs in meters, with optional rectangular holes.\nfunction panel(\n w: number,\n h: number,\n holes: [number, number, number, number][] = [],\n) {\n const shape = new THREE.Shape();\n shape.moveTo(-w / 2, -h / 2);\n shape.lineTo(w / 2, -h / 2);\n shape.lineTo(w / 2, h / 2);\n shape.lineTo(-w / 2, h / 2);\n for (const [x0, y0, x1, y1] of holes) {\n const hole = new THREE.Path();\n hole.moveTo(x0, y0);\n hole.lineTo(x0, y1);\n hole.lineTo(x1, y1);\n hole.lineTo(x1, y0);\n shape.holes.push(hole);\n }\n return own(new THREE.ShapeGeometry(shape));\n}\n\nconst unitPlane = own(new THREE.PlaneGeometry(1, 1));\n\n// --------------------------------------------------------------- materials\n\nconst standard = (params: THREE.MeshStandardMaterialParameters) =>\n own(new THREE.MeshStandardMaterial(params));\n\nconst mats = {\n trim: once(() => standard({ color: '#f3f1ec', roughness: 0.5 })),\n walnut: once(() => standard({ map: walnutTexture(), roughness: 0.5 })),\n darkWalnut: once(() =>\n standard({ map: walnutTexture(), color: '#8a7a70', roughness: 0.55 }),\n ),\n oak: once(() => standard({ map: oakVeneerTexture(), roughness: 0.55 })),\n blackMetal: once(() =>\n standard({ color: '#1a1a1a', roughness: 0.4, metalness: 0.85 }),\n ),\n steel: once(() =>\n standard({ color: '#b8b8b4', roughness: 0.3, metalness: 1 }),\n ),\n brass: once(() =>\n standard({ color: '#c6a062', roughness: 0.28, metalness: 1 }),\n ),\n ceramic: once(() => standard({ color: '#ebe6dc', roughness: 0.3 })),\n stoneware: once(() => standard({ color: '#4a4844', roughness: 0.55 })),\n terracotta: once(() => standard({ color: '#a65f40', roughness: 0.85 })),\n soil: once(() => standard({ color: '#2a2019', roughness: 1 })),\n white: once(() => standard({ color: '#f2efe9', roughness: 0.6 })),\n charcoal: once(() => standard({ color: '#2b2b2d', roughness: 0.75 })),\n stone: once(() => standard({ color: '#e4e0d8', roughness: 0.35 })),\n book: once(() => standard({ roughness: 0.8 })),\n pot: once(() => standard({ color: '#e4ded3', roughness: 0.85 })),\n glass: once(() =>\n standard({\n color: '#e6f0f5',\n roughness: 0.03,\n transparent: true,\n opacity: 0.12,\n }),\n ),\n hidden: once(() => own(new THREE.MeshBasicMaterial({ visible: false }))),\n bulb: once(() => {\n const material = own(new THREE.MeshBasicMaterial({ color: '#fff1dc' }));\n material.color.setScalar(5);\n return material;\n }),\n lampShade: once(() =>\n standard({\n color: '#efe4cf',\n roughness: 1,\n side: THREE.DoubleSide,\n emissive: '#ffc985',\n emissiveIntensity: 1.1,\n }),\n ),\n linenShade: once(() =>\n standard({ color: '#d8d0c2', roughness: 0.9, side: THREE.DoubleSide }),\n ),\n screen: once(() =>\n customizeEnvironment(\n standard({\n color: '#050506',\n roughness: 0.05,\n metalness: 0.2,\n envMapIntensity: 0.3,\n }),\n { boxProjected: true },\n ),\n ),\n mirror: once(() =>\n customizeEnvironment(\n standard({ color: '#d8dcdc', roughness: 0.15, metalness: 1 }),\n { boxProjected: true },\n ),\n ),\n leaf: once(() =>\n standard({\n ...leafTextures(),\n bumpScale: 0.6,\n alphaTest: 0.5,\n side: THREE.DoubleSide,\n roughness: 0.45,\n envMapIntensity: 0.12,\n }),\n ),\n bark: once(() => standard({ color: '#5b4835', roughness: 0.9 })),\n};\n\nconst coloredMaterials = new Map<string, THREE.MeshStandardMaterial>();\n// A plain material by color, shared per (color, roughness, metalness).\nfunction paintMaterial(color: string, roughness = 0.7, metalness = 0) {\n const key = `${color}:${roughness}:${metalness}`;\n let material = coloredMaterials.get(key);\n if (!material) {\n material = standard({ color, roughness, metalness });\n coloredMaterials.set(key, material);\n }\n return material;\n}\n\nconst fabricMaterials = new Map<string, THREE.MeshStandardMaterial>();\n// Woven upholstery in `color`.\nfunction fabricMaterial(color: string, seed = 51) {\n const key = `${color}:${seed}`;\n let material = fabricMaterials.get(key);\n if (!material) {\n material = standard({\n color,\n roughness: 0.95,\n ...fabricTexture(seed),\n bumpScale: 0.5,\n });\n fabricMaterials.set(key, material);\n }\n return material;\n}\n\n// --------------------------------------------------------------- the room\n\ntype Occluder = { min: THREE.Vector3; max: THREE.Vector3; strength: number };\n\ninterface WindowSpec {\n wall: Wall;\n at: number;\n width: number;\n sill?: number;\n head?: number;\n // 'outside' (default) lets in daylight and sun; 'corridor' is interior\n // glazing onto a softly lit corridor, with a frosted band.\n view?: 'outside' | 'corridor';\n sheers?: boolean;\n mullions?: number;\n // Fraction (0..1) a roller blind is lowered.\n blind?: number;\n}\n\ninterface DoorSpec {\n wall: Wall;\n at: number;\n width?: number;\n height?: number;\n}\n\ninterface RoomSpec {\n name: string;\n width: number;\n depth: number;\n height?: number;\n // Back wall z; the default puts the origin 60% of the way to the front.\n z0?: number;\n windows: WindowSpec[];\n doors?: DoorSpec[];\n floor?: 'oak' | 'carpet' | 'concrete';\n wall?: string;\n // Sun through one outside window (`window` indexes the outside windows\n // only, skipping corridor glazing): elevation and azimuth in degrees\n // (azimuth turns it along the wall).\n sun?: { window?: number; elevation?: number; azimuth?: number };\n downlights?: [number, number][];\n texelsPerMeter?: number;\n // A robot vacuum driving an elliptical loop: visible, hit-testable and in\n // depth, but not a tracked plane/mesh.\n robot?: {\n center: [number, number];\n radius: [number, number];\n speed?: number;\n };\n}\n\ninterface Win {\n wall: Wall;\n at: number;\n width: number;\n sill: number;\n head: number;\n exterior: boolean;\n light: number;\n normal: THREE.Vector3;\n u: THREE.Vector3;\n center: THREE.Vector3;\n samples: THREE.Vector3[];\n sampleArea: number;\n spec: WindowSpec;\n}\n\ninterface RoomState {\n spec: RoomSpec;\n x0: number;\n x1: number;\n z0: number;\n z1: number;\n h: number;\n windows: Win[];\n sunDirection: THREE.Vector3;\n sunTarget: THREE.Vector3;\n hasSun: boolean;\n patchSamples: THREE.Vector3[];\n patchSampleArea: number[];\n bounceScale: number;\n probe: THREE.Vector3;\n occluders: Occluder[];\n lit: { object: THREE.Mesh; w: number; h: number }[];\n wallColor: string;\n}\n\nlet R: RoomState;\n// Baked lightmap values are irradiance / LIGHTMAP_INTENSITY.\nconst LIGHTMAP_INTENSITY = 2.4;\nconst SUN_INTENSITY = 22;\n\nfunction wallInfo(wall: Wall) {\n const { x0, x1, z0, z1, h } = R;\n const zc = (z0 + z1) / 2;\n const V = THREE.Vector3;\n switch (wall) {\n case 'back':\n return {\n normal: new V(0, 0, 1),\n u: new V(1, 0, 0),\n rotationY: 0,\n length: x1 - x0,\n center: new V(0, h / 2, z0),\n point: (at: number, y: number) => new V(at, y, z0),\n };\n case 'front':\n return {\n normal: new V(0, 0, -1),\n u: new V(-1, 0, 0),\n rotationY: Math.PI,\n length: x1 - x0,\n center: new V(0, h / 2, z1),\n point: (at: number, y: number) => new V(at, y, z1),\n };\n case 'left':\n return {\n normal: new V(1, 0, 0),\n u: new V(0, 0, -1),\n rotationY: Math.PI / 2,\n length: z1 - z0,\n center: new V(x0, h / 2, zc),\n point: (at: number, y: number) => new V(x0, y, at),\n };\n case 'right':\n return {\n normal: new V(-1, 0, 0),\n u: new V(0, 0, 1),\n rotationY: -Math.PI / 2,\n length: z1 - z0,\n center: new V(x1, h / 2, zc),\n point: (at: number, y: number) => new V(x1, y, at),\n };\n }\n}\n\n// Windows (with their sheers and rods) and doors must fit their wall and not\n// overlap, or the wall holes and window geometry break.\nfunction checkOpenings(spec: RoomSpec, h: number, z0: number) {\n // `owner` is the opening a span belongs to (a window and its sheers).\n const spans: {\n wall: Wall;\n from: number;\n to: number;\n name: string;\n owner: string;\n }[] = [];\n const add = (\n name: string,\n owner: string,\n wall: Wall,\n at: number,\n halfWidth: number,\n top: number,\n ) => {\n const [min, max] =\n wall === 'back' || wall === 'front'\n ? [-spec.width / 2, spec.width / 2]\n : [z0, z0 + spec.depth];\n if (at - halfWidth < min || at + halfWidth > max || top > h) {\n throw new Error(`${spec.name}: ${name} does not fit the ${wall} wall`);\n }\n spans.push({ wall, from: at - halfWidth, to: at + halfWidth, name, owner });\n };\n spec.windows.forEach((w, i) => {\n const sill = w.sill ?? 0.55;\n const head = w.head ?? Math.min(h - 0.35, 2.35);\n if (sill < 0 || sill >= head) {\n throw new Error(`${spec.name}: window ${i} needs 0 <= sill < head`);\n }\n add(`window ${i}`, `window ${i}`, w.wall, w.at, w.width / 2, head);\n const sheers = (w.view ?? 'outside') === 'outside' && !w.blind;\n if (sheers && w.sheers !== false) {\n add(\n `window ${i}'s sheers`,\n `window ${i}`,\n w.wall,\n w.at,\n w.width / 2 + 0.53,\n head + 0.17,\n );\n }\n });\n (spec.doors ?? []).forEach((d, i) =>\n add(\n `door ${i}`,\n `door ${i}`,\n d.wall,\n d.at,\n (d.width ?? 0.86) / 2,\n d.height ?? 2.06,\n ),\n );\n for (const a of spans) {\n for (const b of spans) {\n if (a.owner === b.owner || a.wall !== b.wall) continue;\n if (a.from < b.to && b.from < a.to) {\n throw new Error(`${spec.name}: ${a.name} overlaps ${b.name}`);\n }\n }\n }\n}\n\nfunction createRoom(spec: RoomSpec) {\n if (spec.width > MAX_ROOM_SIZE || spec.depth > MAX_ROOM_SIZE) {\n throw new Error(\n `${spec.name}: ${spec.width} x ${spec.depth} m exceeds the ${MAX_ROOM_SIZE} x ${MAX_ROOM_SIZE} m a Quest room scan supports`,\n );\n }\n const h = spec.height ?? 2.7;\n const z0 = spec.z0 ?? -spec.depth * 0.6;\n checkOpenings(spec, h, z0);\n R = {\n spec,\n x0: -spec.width / 2,\n x1: spec.width / 2,\n z0,\n z1: z0 + spec.depth,\n h,\n windows: [],\n sunDirection: new THREE.Vector3(0, -1, 0),\n sunTarget: new THREE.Vector3(),\n hasSun: false,\n patchSamples: [],\n patchSampleArea: [],\n bounceScale: 1,\n probe: new THREE.Vector3(0, 1.3, z0 + spec.depth / 2),\n occluders: [],\n lit: [],\n wallColor: spec.wall ?? '#eeeae3',\n };\n\n for (const w of spec.windows) {\n const info = wallInfo(w.wall);\n const sill = w.sill ?? 0.55;\n const head = w.head ?? Math.min(h - 0.35, 2.35);\n const exterior = (w.view ?? 'outside') === 'outside';\n const center = info.point(w.at, (sill + head) / 2);\n const samples: THREE.Vector3[] = [];\n const columns = Math.max(2, Math.round(w.width / 0.45));\n for (let i = 0; i < columns; i++) {\n for (let j = 0; j < 3; j++) {\n const along = -w.width / 2 + ((i + 0.5) / columns) * w.width;\n samples.push(\n info\n .point(w.at, sill + ((j + 0.5) / 3) * (head - sill))\n .addScaledVector(info.u, along),\n );\n }\n }\n R.windows.push({\n wall: w.wall,\n at: w.at,\n width: w.width,\n sill,\n head,\n exterior,\n light: exterior ? 1 : 0.3,\n normal: info.normal,\n u: info.u,\n center,\n samples,\n sampleArea: (w.width * (head - sill)) / samples.length,\n spec: w,\n });\n }\n\n // Sun through an outside window, landing on the floor.\n const outside = R.windows.filter((w) => w.exterior);\n const sunWindow = outside[spec.sun?.window ?? 0];\n if (sunWindow) {\n const elevation = THREE.MathUtils.degToRad(spec.sun?.elevation ?? 39);\n const azimuth = THREE.MathUtils.degToRad(spec.sun?.azimuth ?? 15);\n R.sunDirection = sunWindow.normal\n .clone()\n .multiplyScalar(Math.cos(elevation) * Math.cos(azimuth))\n .addScaledVector(sunWindow.u, Math.cos(elevation) * Math.sin(azimuth))\n .add(new THREE.Vector3(0, -Math.sin(elevation), 0))\n .normalize();\n R.sunTarget = sunWindow.center\n .clone()\n .addScaledVector(R.sunDirection, -sunWindow.center.y / R.sunDirection.y);\n R.hasSun = true;\n const d = R.sunDirection;\n for (const w of outside) {\n const facing = d.dot(w.normal);\n if (facing <= 0.05) continue;\n for (const s of w.samples) {\n const f = s.clone().addScaledVector(d, -s.y / d.y);\n if (f.x > R.x0 && f.x < R.x1 && f.z > R.z0 && f.z < R.z1) {\n R.patchSamples.push(f);\n R.patchSampleArea.push((w.sampleArea * facing) / -d.y);\n }\n }\n }\n }\n\n // Indirect light scales with how much window the room has for its size,\n // relative to the reference living room (a 2.1 x 1.8 m window, 116 m2).\n const surface =\n 2 * spec.width * spec.depth + 2 * (spec.width + spec.depth) * h;\n const opening = R.windows.reduce(\n (sum, w) => sum + w.width * (w.head - w.sill) * w.light,\n 0,\n );\n R.bounceScale = THREE.MathUtils.clamp(opening / surface / 0.0325, 0.6, 1.5);\n\n // A group on a wall at height y, `out` meters into the room, facing in.\n const onWall = (wall: Wall, at: number, y = 0, out = 0) => {\n const info = wallInfo(wall);\n const p = info.point(at, y).addScaledVector(info.normal, out);\n return group(p.x, p.y, p.z, info.rotationY);\n };\n\n return {\n bounds: { x0: R.x0, x1: R.x1, z0: R.z0, z1: R.z1, height: h },\n // A group at floor position (x, z), turned by rotationY.\n place(x: number, z: number, rotationY = 0, y = 0) {\n return group(x, y, z, rotationY);\n },\n onWall,\n // A group for furniture of the given depth standing against a wall.\n against(wall: Wall, at: number, depth: number, gap = 0.02) {\n return onWall(wall, at, 0, depth / 2 + gap);\n },\n finish,\n };\n}\n\n// --------------------------------------------------------------- helpers\n\nfunction mesh(\n geometry: THREE.BufferGeometry,\n material: THREE.Material,\n [x, y, z]: Vec3,\n parent: THREE.Object3D = scene,\n { cast = true, receive = true } = {},\n) {\n const object = new THREE.Mesh(geometry, material);\n object.position.set(x, y, z);\n object.castShadow = cast;\n object.receiveShadow = receive;\n parent.add(object);\n return object;\n}\n\nfunction box(\n [w, h, d]: Vec3,\n material: THREE.Material,\n position: Vec3,\n parent: THREE.Object3D = scene,\n) {\n return mesh(\n own(meterUVs(new THREE.BoxGeometry(w, h, d), w, h, d)),\n material,\n position,\n parent,\n );\n}\n\nfunction cylinder(\n radiusTop: number,\n radiusBottom: number,\n height: number,\n material: THREE.Material,\n position: Vec3,\n parent: THREE.Object3D,\n segments = 24,\n) {\n return mesh(\n own(new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments)),\n material,\n position,\n parent,\n );\n}\n\nfunction group(\n x: number,\n y: number,\n z: number,\n rotationY = 0,\n parent: THREE.Object3D = scene,\n) {\n const object = new THREE.Group();\n object.position.set(x, y, z);\n object.rotation.y = rotationY;\n parent.add(object);\n return object;\n}\n\n// Invisible furniture volume, reported as an XRMesh and used as an occluder\n// for the baked lighting.\nfunction volume(\n label: string,\n [w, h, d]: Vec3,\n position: Vec3,\n parent: THREE.Object3D,\n strength = 0.7,\n) {\n const object = mesh(\n own(new THREE.BoxGeometry(w, h, d)),\n mats.hidden(),\n position,\n parent,\n { cast: false, receive: false },\n );\n object.userData.xrMesh = label;\n object.updateWorldMatrix(true, false);\n const bounds = new THREE.Box3().setFromObject(object);\n R.occluders.push({ min: bounds.min, max: bounds.max, strength });\n return object;\n}\n\n// Like volume(), but only occludes the baked lighting: nothing is added to\n// the scene or reported.\nfunction occluder(\n _label: string,\n [w, h, d]: Vec3,\n [x, y, z]: Vec3,\n parent: THREE.Object3D,\n strength = 0.7,\n) {\n parent.updateWorldMatrix(true, false);\n const bounds = new THREE.Box3(\n new THREE.Vector3(x - w / 2, y - h / 2, z - d / 2),\n new THREE.Vector3(x + w / 2, y + h / 2, z + d / 2),\n ).applyMatrix4(parent.matrixWorld);\n R.occluders.push({ min: bounds.min, max: bounds.max, strength });\n}\n\n// Registers a flat mesh (UVs = local XY in meters over a centered w x h\n// rectangle) for a baked lightmap. Its material must not be shared.\nfunction litSurface(object: THREE.Mesh, w: number, h: number) {\n R.lit.push({ object, w, h });\n return object;\n}\n\n// --------------------------------------------------------- baked lighting\n\nconst toSample = new THREE.Vector3();\nconst closest = new THREE.Vector3();\nconst center = new THREE.Vector3();\n\n// True if the segment a -> b passes through the box (slab test).\nfunction blocks(a: THREE.Vector3, b: THREE.Vector3, o: Occluder) {\n let t0 = 0.0001;\n let t1 = 0.9999;\n for (const axis of ['x', 'y', 'z'] as const) {\n const delta = b[axis] - a[axis];\n if (Math.abs(delta) < 1e-9) {\n if (a[axis] < o.min[axis] || a[axis] > o.max[axis]) return false;\n continue;\n }\n let near = (o.min[axis] - a[axis]) / delta;\n let far = (o.max[axis] - a[axis]) / delta;\n if (near > far) [near, far] = [far, near];\n t0 = Math.max(t0, near);\n t1 = Math.min(t1, far);\n if (t0 > t1) return false;\n }\n return true;\n}\n\nconst inside = (p: THREE.Vector3, o: Occluder) =>\n p.x > o.min.x - 0.02 &&\n p.x < o.max.x + 0.02 &&\n p.y > o.min.y - 0.02 &&\n p.y < o.max.y + 0.02 &&\n p.z > o.min.z - 0.02 &&\n p.z < o.max.z + 0.02;\n\n// Ambient occlusion from room corners and nearby furniture.\nfunction occlusion(p: THREE.Vector3, n: THREE.Vector3, active: Occluder[]) {\n const planes: [THREE.Vector3, number][] = [\n [new THREE.Vector3(1, 0, 0), -R.x0],\n [new THREE.Vector3(-1, 0, 0), R.x1],\n [new THREE.Vector3(0, 1, 0), 0],\n [new THREE.Vector3(0, -1, 0), R.h],\n [new THREE.Vector3(0, 0, 1), -R.z0],\n [new THREE.Vector3(0, 0, -1), R.z1],\n ];\n let ao = 1;\n for (const [normal, d] of planes) {\n if (Math.abs(normal.dot(n)) > 0.5) continue;\n const distance = Math.max(0, normal.dot(p) + d);\n ao *=\n (1 - 0.45 * Math.exp(-distance / 0.3)) *\n (1 - 0.2 * Math.exp(-distance / 0.04));\n }\n for (const o of active) {\n center.addVectors(o.min, o.max).multiplyScalar(0.5);\n if (n.dot(toSample.subVectors(center, p)) < 0) continue;\n closest.copy(p).clamp(o.min, o.max);\n const distance = closest.distanceTo(p);\n ao *=\n (1 - o.strength * Math.exp(-distance / 0.25)) *\n (1 - 0.5 * Math.exp(-distance / 0.04));\n }\n return ao;\n}\n\n// Diffuse irradiance (relative units) at p with normal n: skylight through\n// the windows (area lights shadowed by furniture), bounce from the sun patch\n// and a warm multi-bounce ambient. `self` ignores the volume containing p.\nfunction irradiance(\n p: THREE.Vector3,\n n: THREE.Vector3,\n self = false,\n): [number, number, number] {\n const active = self ? R.occluders.filter((o) => !inside(p, o)) : R.occluders;\n let sky = 0;\n for (const w of R.windows) {\n for (const s of w.samples) {\n toSample.subVectors(s, p);\n const d2 = Math.max(toSample.lengthSq(), 0.05);\n toSample.normalize();\n const cosP = n.dot(toSample);\n const cosW = -w.normal.dot(toSample);\n if (cosP <= 0 || cosW <= 0) continue;\n if (active.some((o) => blocks(p, s, o))) continue;\n sky += (w.light * cosP * cosW * w.sampleArea) / (Math.PI * d2);\n }\n }\n let patch = 0;\n for (let i = 0; i < R.patchSamples.length; i++) {\n toSample.subVectors(R.patchSamples[i], p);\n const d2 = Math.max(toSample.lengthSq(), 0.1);\n toSample.normalize();\n const cosP = n.dot(toSample);\n const cosE = -toSample.y;\n if (cosP > 0 && cosE > 0)\n patch += (cosP * cosE * R.patchSampleArea[i]) / (Math.PI * d2);\n }\n const ao = occlusion(p, n, active);\n const bounce =\n ((1.2 * R.bounceScale) / LIGHTMAP_INTENSITY) * ao * (n.y < -0.5 ? 0.7 : 1);\n const direct = sky * (0.6 + 0.4 * ao) * 1.6;\n // Floor exitance in the patch: sun x cos(elevation) x albedo (0.45).\n const warm =\n ((SUN_INTENSITY * -R.sunDirection.y * 0.45) / LIGHTMAP_INTENSITY) *\n patch *\n (Math.abs(n.y) < 0.5 && p.y < R.h / 2 ? 1.25 : 1);\n return [\n bounce * 1.0 + direct * 0.93 + warm,\n bounce * 0.9 + direct * 0.95 + warm * 0.85,\n bounce * 0.78 + direct * 1.0 + warm * 0.66,\n ];\n}\n\n// Bakes a half-float lightmap for a registered lit surface.\nfunction bakeLightmap(object: THREE.Object3D, w: number, h: number) {\n object.updateWorldMatrix(true, false);\n // Keep textures modest in large rooms.\n const texelsPerMeter = Math.min(\n R.spec.texelsPerMeter ?? 24,\n 256 / Math.max(w, h),\n );\n const width = Math.max(8, Math.round(w * texelsPerMeter));\n const height = Math.max(8, Math.round(h * texelsPerMeter));\n const data = new Uint16Array(width * height * 4);\n const normal = new THREE.Vector3(0, 0, 1).transformDirection(\n object.matrixWorld,\n );\n const p = new THREE.Vector3();\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n p.set(((x + 0.5) / width - 0.5) * w, ((y + 0.5) / height - 0.5) * h, 0);\n p.applyMatrix4(object.matrixWorld);\n const [r, g, b] = irradiance(p, normal);\n const i = (y * width + x) * 4;\n data[i] = THREE.DataUtils.toHalfFloat(r);\n data[i + 1] = THREE.DataUtils.toHalfFloat(g);\n data[i + 2] = THREE.DataUtils.toHalfFloat(b);\n data[i + 3] = THREE.DataUtils.toHalfFloat(1);\n }\n }\n const tex = own(\n new THREE.DataTexture(\n data,\n width,\n height,\n THREE.RGBAFormat,\n THREE.HalfFloatType,\n ),\n );\n tex.magFilter = THREE.LinearFilter;\n tex.minFilter = THREE.LinearFilter;\n tex.repeat.set(1 / w, 1 / h);\n tex.offset.set(0.5, 0.5);\n tex.needsUpdate = true;\n return tex;\n}\n\n// Environment shader tweaks:\n// - boxProjected: the probe is parallax-corrected against the room box, so\n// the window reflects where it actually is.\n// - specularOnly: lightmapped surfaces already have their diffuse light, so\n// they only take reflections from the probe.\nfunction customizeEnvironment(\n material: THREE.MeshStandardMaterial,\n { boxProjected = false, specularOnly = false },\n) {\n let chunk = THREE.ShaderChunk.envmap_physical_pars_fragment;\n if (boxProjected) {\n // The world-space reflection line: `inverseTransformDirection` in current\n // three.js, `transformDirectionByInverseViewMatrix` in older versions.\n const patched = chunk.replace(\n /reflectVec = (?:inverseTransformDirection|transformDirectionByInverseViewMatrix)\\( reflectVec, viewMatrix \\);/,\n (line) => `${line}\n vec3 boxHit = mix( boxMin, boxMax, step( 0.0, reflectVec ) );\n vec3 boxT = ( boxHit - vBoxWorldPosition ) / reflectVec;\n float boxDistance = min( min( boxT.x, boxT.y ), boxT.z );\n reflectVec = normalize( vBoxWorldPosition + reflectVec * boxDistance - probePosition );`,\n );\n if (patched === chunk) {\n console.warn(\n 'Box-projected reflections are not supported by this three.js version',\n );\n }\n chunk = patched;\n }\n if (specularOnly) {\n chunk = chunk.replace(\n 'return PI * envMapColor.rgb * envMapIntensity;',\n 'return vec3( 0.0 );',\n );\n }\n material.onBeforeCompile = (shader) => {\n shader.uniforms.boxMin = { value: new THREE.Vector3(R.x0, 0, R.z0) };\n shader.uniforms.boxMax = { value: new THREE.Vector3(R.x1, R.h, R.z1) };\n shader.uniforms.probePosition = { value: R.probe };\n shader.vertexShader = shader.vertexShader\n .replace(\n '#include <common>',\n '#include <common>\\nvarying vec3 vBoxWorldPosition;',\n )\n .replace(\n '#include <worldpos_vertex>',\n '#include <worldpos_vertex>\\nvBoxWorldPosition = (modelMatrix * vec4(transformed, 1.0)).xyz;',\n );\n shader.fragmentShader = shader.fragmentShader\n .replace(\n '#include <common>',\n '#include <common>\\nvarying vec3 vBoxWorldPosition;\\nuniform vec3 boxMin;\\nuniform vec3 boxMax;\\nuniform vec3 probePosition;',\n )\n .replace('#include <envmap_physical_pars_fragment>', chunk);\n };\n material.customProgramCacheKey = () =>\n `environment:${boxProjected}:${specularOnly}`;\n return material;\n}\n\n// Room surfaces get their indirect light from baked lightmaps, so their\n// environment map only contributes reflections. One material per surface.\nfunction shellMaterial(params: THREE.MeshStandardMaterialParameters) {\n const material = standard({\n envMapIntensity: 0.5,\n lightMapIntensity: LIGHTMAP_INTENSITY,\n ...params,\n });\n material.shadowSide = THREE.DoubleSide;\n return customizeEnvironment(material, { specularOnly: true });\n}\n\nfunction floorMaterial() {\n switch (R.spec.floor ?? 'oak') {\n case 'carpet':\n return shellMaterial({\n map: carpetTexture(),\n roughness: 1,\n envMapIntensity: 0.1,\n });\n case 'concrete':\n return customizeEnvironment(\n shellMaterial({\n map: concreteTexture(),\n roughness: 0.55,\n envMapIntensity: 0.6,\n }),\n { boxProjected: true, specularOnly: true },\n );\n default:\n return customizeEnvironment(\n shellMaterial({\n ...oakTextures(),\n bumpScale: 0.15,\n roughness: 1,\n envMapIntensity: 0.5,\n }),\n { boxProjected: true, specularOnly: true },\n );\n }\n}\n\nfunction wallMaterial() {\n return shellMaterial({\n color: R.wallColor,\n roughness: 0.9,\n bumpMap: plasterBump(),\n bumpScale: 0.12,\n });\n}\n\n// ------------------------------------------------------------------ shell\n\nfunction buildShell() {\n const { x0, x1, z0, z1, h } = R;\n const W = x1 - x0;\n const D = z1 - z0;\n const zc = (z0 + z1) / 2;\n const SEAM = 0.004;\n\n const floor = mesh(panel(W, D), floorMaterial(), [0, 0, zc], scene, {\n cast: false,\n });\n floor.rotation.x = -Math.PI / 2;\n floor.userData.xrPlane = 'floor';\n litSurface(floor, W, D);\n const ceiling = mesh(\n panel(W, D),\n shellMaterial({ color: '#f7f4ef', roughness: 0.95 }),\n [0, h, zc],\n );\n ceiling.rotation.x = Math.PI / 2;\n ceiling.userData.xrPlane = 'ceiling';\n litSurface(ceiling, W, D);\n\n // Walls overlap the floor, ceiling and each other slightly so no seam\n // shows a hairline.\n for (const wall of WALLS) {\n const info = wallInfo(wall);\n const holes = R.windows\n .filter((w) => w.wall === wall)\n .map((w): [number, number, number, number] => {\n const lx = w.center.clone().sub(info.center).dot(info.u);\n return [\n lx - w.width / 2,\n w.sill - h / 2,\n lx + w.width / 2,\n w.head - h / 2,\n ];\n });\n const object = mesh(\n panel(info.length + SEAM, h + SEAM, holes),\n wallMaterial(),\n [info.center.x, info.center.y, info.center.z],\n );\n object.rotation.y = info.rotationY;\n object.userData.xrPlane = 'wall';\n litSurface(object, info.length + SEAM, h + SEAM);\n // Baseboard.\n const base = group(info.center.x, 0, info.center.z, info.rotationY);\n box([info.length, 0.09, 0.014], mats.trim(), [0, 0.045, 0.007], base);\n }\n\n buildShadowShell();\n for (const w of R.windows) buildWindow(w);\n for (const d of R.spec.doors ?? []) buildDoor(d);\n\n // Recessed downlights (off during the day): trim ring and lens.\n const ring = own(new THREE.RingGeometry(0.045, 0.062, 32));\n const lens = own(new THREE.CircleGeometry(0.045, 32));\n const lensMaterial = paintMaterial('#dcd7ce', 0.3);\n const lights =\n R.spec.downlights ??\n [x0 + W / 4, x1 - W / 4].flatMap((x) =>\n (D > 6 ? [z0 + D / 6, zc, z1 - D / 6] : [z0 + D / 4, z1 - D / 4]).map(\n (z): [number, number] => [x, z],\n ),\n );\n for (const [x, z] of lights) {\n mesh(ring, mats.trim(), [x, h - 0.002, z], scene, {\n cast: false,\n }).rotation.x = Math.PI / 2;\n mesh(lens, lensMaterial, [x, h - 0.004, z], scene, {\n cast: false,\n }).rotation.x = Math.PI / 2;\n }\n}\n\n// Shadow-only shell: thick boxes around the room (with the outside window\n// openings) so no sunlight leaks in where the thin wall and ceiling planes\n// meet. They write neither color nor depth and ignore hit-test rays.\nfunction buildShadowShell() {\n const { x0, x1, z0, z1, h } = R;\n const caster = own(\n new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false }),\n );\n caster.shadowSide = THREE.DoubleSide;\n const slab = (min: Vec3, max: Vec3) => {\n const object = box(\n [max[0] - min[0], max[1] - min[1], max[2] - min[2]],\n caster,\n [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2],\n );\n object.receiveShadow = false;\n object.userData.shadowOnly = true;\n };\n const t = 0.2;\n const inset = 0.03;\n const margin = 0.4;\n slab(\n [x0 - margin, h - inset, z0 - margin],\n [x1 + margin, h + t, z1 + margin],\n );\n for (const wall of WALLS) {\n const openings = R.windows.filter((w) => w.wall === wall && w.exterior);\n // Walls with openings sit outside the window reveals, so the reveals\n // catch the sun.\n const [near, far] = openings.length ? [0.2, 0.2 + t] : [-inset, t];\n const horizontal = wall === 'back' || wall === 'front';\n const [lo, hi] = horizontal\n ? [x0 - margin, x1 + margin]\n : [z0 - margin, z1 + margin];\n const cuts = [\n lo,\n hi,\n ...openings.flatMap((w) => [w.at - w.width / 2, w.at + w.width / 2]),\n ].sort((a, b) => a - b);\n for (let i = 0; i < cuts.length - 1; i++) {\n const [u0, u1] = [cuts[i], cuts[i + 1]];\n if (u1 - u0 < 1e-4) continue;\n const opening = openings.find(\n (w) =>\n (u0 + u1) / 2 > w.at - w.width / 2 &&\n (u0 + u1) / 2 < w.at + w.width / 2,\n );\n const spans: [number, number][] = opening\n ? [\n [-0.1, opening.sill],\n [opening.head, h + t],\n ]\n : [[-0.1, h + t]];\n for (const [y0, y1] of spans) {\n if (wall === 'back') slab([u0, y0, z0 - far], [u1, y1, z0 - near]);\n if (wall === 'front') slab([u0, y0, z1 + near], [u1, y1, z1 + far]);\n if (wall === 'left') slab([x0 - far, y0, u0], [x0 - near, y1, u1]);\n if (wall === 'right') slab([x1 + near, y0, u0], [x1 + far, y1, u1]);\n }\n }\n }\n}\n\nconst curtainMaterial = once(() =>\n standard({\n vertexColors: true,\n color: '#f5f2ea',\n roughness: 1,\n side: THREE.DoubleSide,\n transparent: true,\n opacity: 0.82,\n emissive: '#fff6e6',\n emissiveIntensity: 0.25,\n }),\n);\n\n// Window: reveal, frame, glass, the view outside, sheers or a blind. The\n// WebXR plane is flush with the wall, as a room scan reports it.\nfunction buildWindow(w: Win) {\n const info = wallInfo(w.wall);\n const base = info.point(w.at, 0);\n const win = group(base.x, 0, base.z, info.rotationY);\n const { width, sill, head } = w;\n const reveal = 0.16;\n // Reveals have no lightmap, so they take their diffuse light from the probe.\n const revealMaterial = standard({\n color: R.wallColor,\n roughness: 0.9,\n bumpMap: plasterBump(),\n bumpScale: 0.12,\n envMapIntensity: 1,\n });\n revealMaterial.shadowSide = THREE.DoubleSide;\n box(\n [0.02, head - sill, reveal],\n revealMaterial,\n [-width / 2 - 0.01, (sill + head) / 2, -reveal / 2],\n win,\n );\n box(\n [0.02, head - sill, reveal],\n revealMaterial,\n [width / 2 + 0.01, (sill + head) / 2, -reveal / 2],\n win,\n );\n box(\n [width, 0.02, reveal],\n revealMaterial,\n [0, head + 0.01, -reveal / 2],\n win,\n );\n box(\n [width + 0.12, 0.03, reveal + 0.06],\n mats.trim(),\n [0, sill - 0.015, -reveal / 2 + 0.03],\n win,\n );\n const frameZ = -reveal + 0.04;\n box([width, 0.05, 0.06], mats.trim(), [0, sill + 0.025, frameZ], win);\n box([width, 0.05, 0.06], mats.trim(), [0, head - 0.025, frameZ], win);\n box(\n [0.05, head - sill, 0.06],\n mats.trim(),\n [-width / 2 + 0.025, (sill + head) / 2, frameZ],\n win,\n );\n box(\n [0.05, head - sill, 0.06],\n mats.trim(),\n [width / 2 - 0.025, (sill + head) / 2, frameZ],\n win,\n );\n const mullions =\n w.spec.mullions ??\n (width > 1.4 ? Math.max(1, Math.round(width / 1.2) - 1) : 0);\n for (let i = 1; i <= mullions; i++) {\n box(\n [0.05, head - sill, 0.06],\n mats.trim(),\n [-width / 2 + (i * width) / (mullions + 1), (sill + head) / 2, frameZ],\n win,\n );\n }\n const glass = mesh(\n unitPlane,\n mats.glass(),\n [0, (sill + head) / 2, frameZ],\n win,\n { cast: false, receive: false },\n );\n glass.scale.set(width, head - sill, 1);\n const plane = mesh(\n unitPlane,\n mats.hidden(),\n [0, (sill + head) / 2, 0.002],\n win,\n { cast: false, receive: false },\n );\n plane.scale.set(width, head - sill, 1);\n plane.userData.xrPlane = 'window';\n\n if (w.exterior) {\n const view = own(new THREE.MeshBasicMaterial({ map: outsideTexture() }));\n view.color.setScalar(4); // overexposed, like a photo of a window\n const outside = mesh(unitPlane, view, [0, 1.3, -4], win, {\n cast: false,\n receive: false,\n });\n outside.scale.set(Math.max(12, width * 3), 6, 1);\n outside.userData.xrGlobalMesh = false; // outside the room, not scanned\n } else {\n const view = own(new THREE.MeshBasicMaterial({ map: corridorTexture() }));\n view.color.setScalar(1.25);\n const corridor = mesh(unitPlane, view, [0, R.h / 2, -1.6], win, {\n cast: false,\n receive: false,\n });\n corridor.scale.set(width + 2, R.h, 1);\n corridor.userData.xrGlobalMesh = false; // beyond the glass, not scanned\n const frosted = mesh(\n unitPlane,\n standard({\n color: '#ffffff',\n roughness: 0.9,\n transparent: true,\n opacity: 0.6,\n }),\n [0, 1.3, frameZ + 0.004],\n win,\n { cast: false, receive: false },\n );\n frosted.scale.set(width, 0.5, 1);\n }\n\n if (w.spec.blind) {\n const drop = (head - sill) * w.spec.blind;\n cylinder(\n 0.03,\n 0.03,\n width - 0.04,\n paintMaterial('#e8e1d4', 0.9),\n [0, head - 0.04, -0.03],\n win,\n 16,\n ).rotation.z = Math.PI / 2;\n const fabric = mesh(\n unitPlane,\n standard({\n color: '#e8e1d4',\n roughness: 1,\n side: THREE.DoubleSide,\n transparent: true,\n opacity: 0.92,\n emissive: '#fff4e2',\n emissiveIntensity: 0.3,\n }),\n [0, head - 0.04 - drop / 2, -0.01],\n win,\n { cast: true, receive: false },\n );\n fabric.scale.set(width - 0.06, drop, 1);\n } else if (w.exterior && w.spec.sheers !== false) {\n mesh(\n own(new THREE.CylinderGeometry(0.012, 0.012, width + 1, 12)),\n mats.brass(),\n [0, head + 0.15, 0.1],\n win,\n ).rotation.z = Math.PI / 2;\n for (const [x, seed] of [\n [-width / 2 - 0.22, 1],\n [width / 2 + 0.22, 4],\n ]) {\n const height = head + 0.13;\n const geometry = own(new THREE.PlaneGeometry(0.62, height, 48, 8));\n const position = geometry.getAttribute('position');\n const colors = new Float32Array(position.count * 3);\n for (let i = 0; i < position.count; i++) {\n const px = position.getX(i);\n const py = position.getY(i) / height + 0.5;\n const phase = (px / 0.11) * Math.PI * 2 + Math.sin(px * 9 + seed) * 1.2;\n const fold = Math.sin(phase);\n position.setZ(i, fold * 0.03 * (0.8 + 0.2 * py));\n colors.fill(0.85 + 0.15 * (fold * 0.5 + 0.5), i * 3, i * 3 + 3);\n }\n geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));\n geometry.computeVertexNormals();\n mesh(geometry, curtainMaterial(), [x, height / 2 + 0.02, 0.1], win, {\n cast: false,\n });\n }\n }\n}\n\n// Door: slab with a dark gap, trim and a lever handle.\nfunction buildDoor(d: DoorSpec) {\n const info = wallInfo(d.wall);\n const base = info.point(d.at, 0);\n const door = group(base.x, 0, base.z, info.rotationY);\n const width = d.width ?? 0.86;\n const height = d.height ?? 2.06;\n box(\n [width, height + 0.005, 0.01],\n paintMaterial('#3a3836', 1),\n [0, (height + 0.005) / 2, 0.005],\n door,\n );\n const slab = mesh(\n roundedBox(width - 0.006, height - 0.004, 0.04, 0.004, 0, 2),\n mats.trim(),\n [0, (height - 0.004) / 2, 0.022],\n door,\n );\n slab.userData.xrPlane = 'door';\n for (const [w, h, x, y] of [\n [0.07, height + 0.07, -width / 2 - 0.035, (height + 0.07) / 2],\n [0.07, height + 0.07, width / 2 + 0.035, (height + 0.07) / 2],\n [width + 0.14, 0.07, 0, height + 0.035],\n ]) {\n box([w, h, 0.022], mats.trim(), [x, y, 0.011], door);\n }\n box([0.025, 0.12, 0.012], mats.brass(), [width / 2 - 0.07, 1.0, 0.05], door);\n mesh(\n own(new THREE.CylinderGeometry(0.012, 0.012, 0.12, 12)),\n mats.brass(),\n [width / 2 - 0.11, 1.02, 0.07],\n door,\n ).rotation.z = Math.PI / 2;\n}\n\n// --------------------------------------------------------------- finishing\n\n// Bakes ambient occlusion into furniture as vertex colors (and instance\n// colors): darker near the floor and next to other furniture.\nfunction bakeFurnitureShading() {\n const p = new THREE.Vector3();\n const n = new THREE.Vector3();\n const normalMatrix = new THREE.Matrix3();\n const shade = (y: number) => {\n const ao = occlusion(\n p,\n n,\n R.occluders.filter((o) => !inside(p, o)),\n );\n const floor = n.y > 0.7 ? 1 : 1 - 0.35 * Math.exp(-y / 0.15);\n return THREE.MathUtils.clamp(0.55 + 0.45 * ao, 0.55, 1) * floor;\n };\n const skip = (material: THREE.Material) => {\n const m = material as THREE.MeshStandardMaterial;\n return (\n !m.isMeshStandardMaterial ||\n m === mats.trim() ||\n m.transparent ||\n !m.visible ||\n !!m.lightMap ||\n m.emissive.getHex() !== 0\n );\n };\n const seen = new Set<THREE.BufferGeometry>();\n const shaded = new Set<THREE.Material>();\n scene.updateMatrixWorld(true);\n scene.traverse((object) => {\n const target = object as THREE.Mesh;\n if (!target.isMesh || skip(target.material as THREE.Material)) return;\n shaded.add(target.material as THREE.Material);\n const instanced = object as THREE.InstancedMesh;\n if (instanced.isInstancedMesh) {\n const matrix = new THREE.Matrix4();\n const color = new THREE.Color();\n for (let i = 0; i < instanced.count; i++) {\n instanced.getMatrixAt(i, matrix);\n p.setFromMatrixPosition(matrix.premultiply(instanced.matrixWorld));\n n.set(0, 1, 0);\n const f = shade(p.y);\n if (instanced.instanceColor) instanced.getColorAt(i, color);\n else color.setRGB(1, 1, 1);\n instanced.setColorAt(i, color.multiplyScalar(f));\n }\n return;\n }\n if (seen.has(target.geometry))\n target.geometry = own(target.geometry.clone());\n seen.add(target.geometry);\n const position = target.geometry.getAttribute('position');\n const normal = target.geometry.getAttribute('normal');\n const colors = new Float32Array(position.count * 3);\n normalMatrix.getNormalMatrix(target.matrixWorld);\n for (let i = 0; i < position.count; i++) {\n p.fromBufferAttribute(position, i).applyMatrix4(target.matrixWorld);\n n.fromBufferAttribute(normal, i).applyMatrix3(normalMatrix).normalize();\n colors.fill(shade(p.y), i * 3, i * 3 + 3);\n }\n target.geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));\n });\n shaded.forEach((material) => (material.vertexColors = true));\n // Shared materials on meshes without a color attribute get plain white.\n scene.traverse((object) => {\n const target = object as THREE.Mesh;\n if (!target.isMesh || !(target.material as THREE.Material).vertexColors)\n return;\n if (target.geometry.getAttribute('color')) return;\n const count = target.geometry.getAttribute('position').count;\n target.geometry.setAttribute(\n 'color',\n new THREE.BufferAttribute(new Float32Array(count * 3).fill(1), 3),\n );\n });\n}\n\n// Merges static meshes that share a material into one draw call each.\n// Labelled meshes stay separate so they remain WebXR planes / meshes.\nfunction mergeStaticMeshes() {\n scene.updateMatrixWorld(true);\n // Objects tagged xrGlobalMesh = false (moving objects, views outside) stay\n // separate, so they keep their tag and can still move.\n const untracked = (object: THREE.Object3D | null) => {\n for (; object; object = object.parent) {\n if (object.userData.xrGlobalMesh === false) return true;\n }\n return false;\n };\n const buckets = new Map<string, THREE.Mesh[]>();\n scene.traverse((object) => {\n const target = object as THREE.Mesh;\n if (!target.isMesh || (target as THREE.InstancedMesh).isInstancedMesh)\n return;\n const material = target.material as THREE.Material;\n if (!material.visible || material.transparent) return;\n if (target.userData.xrPlane || target.userData.xrMesh) return;\n if (untracked(target)) return;\n const attributes = Object.keys(target.geometry.attributes).sort().join();\n const key = `${material.uuid}:${target.castShadow}:${target.receiveShadow}:${attributes}`;\n buckets.set(key, [...(buckets.get(key) ?? []), target]);\n });\n for (const meshes of buckets.values()) {\n if (meshes.length < 2) continue;\n const names = Object.keys(meshes[0].geometry.attributes);\n const vertexCount = meshes.reduce(\n (sum, m) => sum + m.geometry.getAttribute('position').count,\n 0,\n );\n const arrays = Object.fromEntries(\n names.map((name) => [\n name,\n new Float32Array(\n vertexCount * meshes[0].geometry.getAttribute(name).itemSize,\n ),\n ]),\n );\n const indices: number[] = [];\n let base = 0;\n for (const m of meshes) {\n const geometry = m.geometry.clone();\n geometry.applyMatrix4(m.matrixWorld);\n for (const name of names) {\n const attribute = geometry.getAttribute(name);\n arrays[name].set(\n attribute.array as Float32Array,\n base * attribute.itemSize,\n );\n }\n const index = geometry.getIndex();\n const count = geometry.getAttribute('position').count;\n if (index)\n for (let i = 0; i < index.count; i++)\n indices.push(index.getX(i) + base);\n else for (let i = 0; i < count; i++) indices.push(i + base);\n base += count;\n geometry.dispose();\n m.removeFromParent();\n }\n const merged = own(new THREE.BufferGeometry());\n for (const name of names) {\n merged.setAttribute(\n name,\n new THREE.BufferAttribute(\n arrays[name],\n meshes[0].geometry.getAttribute(name).itemSize,\n ),\n );\n }\n merged.setIndex(indices);\n const combined = new THREE.Mesh(merged, meshes[0].material);\n if (meshes[0].userData.shadowOnly) combined.raycast = () => {};\n combined.castShadow = meshes[0].castShadow;\n combined.receiveShadow = meshes[0].receiveShadow;\n scene.add(combined);\n }\n}\n\n// True if the ray from p back towards the sun leaves through an outside window.\nfunction sunThroughWindow(p: THREE.Vector3) {\n const toSun = R.sunDirection.clone().negate();\n for (const w of R.windows) {\n if (!w.exterior) continue;\n const denom = -w.normal.dot(toSun);\n if (denom <= 1e-4) continue;\n const t = w.normal.dot(toSample.subVectors(p, w.center)) / denom;\n if (t <= 0) continue;\n const q = p.clone().addScaledVector(toSun, t);\n if (\n q.y > w.sill &&\n q.y < w.head &&\n Math.abs(q.clone().sub(w.center).dot(w.u)) < w.width / 2\n )\n return true;\n }\n return false;\n}\n\n// Environment probe: an HDR equirect painted by ray casting the room from\n// its center and shading each hit with the same baked irradiance, so\n// reflections show the actual room, windows and sun patch.\nfunction roomEnvironment() {\n const width = 96;\n const height = 48;\n const data = new Float32Array(width * height * 4);\n const probe = R.probe;\n // Average linear albedo of each floor texture.\n const floorAlbedo = {\n oak: [0.4, 0.27, 0.15],\n carpet: [0.34, 0.32, 0.29],\n concrete: [0.48, 0.46, 0.43],\n }[R.spec.floor ?? 'oak'];\n const d = new THREE.Vector3();\n const hit = new THREE.Vector3();\n const n = new THREE.Vector3();\n const room = {\n min: new THREE.Vector3(R.x0, 0, R.z0),\n max: new THREE.Vector3(R.x1, R.h, R.z1),\n strength: 0,\n };\n const exit = (o: Occluder) => {\n let t = Infinity;\n for (const axis of ['x', 'y', 'z'] as const) {\n if (Math.abs(d[axis]) < 1e-6) continue;\n const bound = d[axis] > 0 ? o.max[axis] : o.min[axis];\n t = Math.min(t, (bound - probe[axis]) / d[axis]);\n }\n return t;\n };\n const entry = (o: Occluder) => {\n let near = -Infinity;\n let far = Infinity;\n for (const axis of ['x', 'y', 'z'] as const) {\n if (Math.abs(d[axis]) < 1e-6) {\n if (probe[axis] < o.min[axis] || probe[axis] > o.max[axis])\n return Infinity;\n continue;\n }\n const a = (o.min[axis] - probe[axis]) / d[axis];\n const b = (o.max[axis] - probe[axis]) / d[axis];\n near = Math.max(near, Math.min(a, b));\n far = Math.min(far, Math.max(a, b));\n }\n return near > 0 && near <= far ? near : Infinity;\n };\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const phi = ((x + 0.5) / width - 0.5) * Math.PI * 2;\n const theta = ((y + 0.5) / height - 0.5) * Math.PI;\n d.set(\n Math.cos(theta) * Math.cos(phi),\n Math.sin(theta),\n Math.cos(theta) * Math.sin(phi),\n );\n let t = exit(room);\n let furniture: Occluder | undefined;\n for (const o of R.occluders) {\n const te = entry(o);\n if (te < t) {\n t = te;\n furniture = o;\n }\n }\n hit.copy(probe).addScaledVector(d, t);\n const boxHit = furniture ?? room;\n const sign = furniture ? 1 : -1;\n if (Math.abs(hit.x - boxHit.min.x) < 1e-3) n.set(-sign, 0, 0);\n else if (Math.abs(hit.x - boxHit.max.x) < 1e-3) n.set(sign, 0, 0);\n else if (Math.abs(hit.y - boxHit.min.y) < 1e-3) n.set(0, -sign, 0);\n else if (Math.abs(hit.y - boxHit.max.y) < 1e-3) n.set(0, sign, 0);\n else if (Math.abs(hit.z - boxHit.min.z) < 1e-3) n.set(0, 0, -sign);\n else n.set(0, 0, sign);\n const window = furniture\n ? undefined\n : R.windows.find(\n (w) =>\n n.dot(w.normal) > 0.5 &&\n hit.y > w.sill &&\n hit.y < w.head &&\n Math.abs(hit.clone().sub(w.center).dot(w.u)) < w.width / 2,\n );\n let rgb: number[];\n if (window) {\n rgb = window.exterior ? [3.2, 3.4, 3.6] : [0.9, 0.88, 0.84];\n } else {\n const albedo = furniture\n ? [0.3, 0.28, 0.26]\n : n.y > 0.5\n ? floorAlbedo\n : n.y < -0.5\n ? [0.9, 0.87, 0.83]\n : [0.82, 0.77, 0.69];\n const e = irradiance(hit, n);\n rgb = albedo.map((a, i) => (a * e[i] * LIGHTMAP_INTENSITY) / Math.PI);\n if (R.hasSun && !furniture && n.y > 0.5 && sunThroughWindow(hit)) {\n const sun = (SUN_INTENSITY * -R.sunDirection.y * 0.45) / Math.PI;\n rgb = [rgb[0] + sun, rgb[1] + sun * 0.86, rgb[2] + sun * 0.67];\n }\n }\n data.set([rgb[0], rgb[1], rgb[2], 1], (y * width + x) * 4);\n }\n }\n const tex = own(\n new THREE.DataTexture(\n data,\n width,\n height,\n THREE.RGBAFormat,\n THREE.FloatType,\n ),\n );\n tex.mapping = THREE.EquirectangularReflectionMapping;\n tex.magFilter = THREE.LinearFilter;\n tex.needsUpdate = true;\n return tex;\n}\n\n// Afternoon sun through the window: a static shadow, rendered once.\nfunction addSun() {\n if (!R.hasSun) return;\n // Owned so its shadow map is freed when the room unloads.\n const sun = own(new THREE.DirectionalLight('#ffdcaa', SUN_INTENSITY));\n const position = R.sunTarget.clone().addScaledVector(R.sunDirection, -12);\n sun.position.copy(position);\n sun.target.position.copy(R.sunTarget);\n sun.castShadow = true;\n sun.shadow.mapSize.set(2048, 2048);\n // Fit the shadow frustum tightly around the room (outside it would be lit).\n const view = new THREE.Matrix4().lookAt(\n position,\n R.sunTarget,\n new THREE.Vector3(0, 1, 0),\n );\n view.setPosition(position).invert();\n const bounds = new THREE.Box3();\n for (const x of [R.x0 - 0.3, R.x1 + 0.3]) {\n for (const y of [0, R.h]) {\n for (const z of [R.z0 - 0.3, R.z1 + 0.3])\n bounds.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(view));\n }\n }\n Object.assign(sun.shadow.camera, {\n left: bounds.min.x - 0.05,\n right: bounds.max.x + 0.05,\n bottom: bounds.min.y - 0.05,\n top: bounds.max.y + 0.05,\n near: -bounds.max.z - 0.5,\n far: -bounds.min.z + 0.5,\n });\n sun.shadow.bias = -0.0002;\n sun.shadow.normalBias = 0.02;\n sun.shadow.radius = 0.8;\n sun.shadow.autoUpdate = false;\n sun.shadow.needsUpdate = true;\n scene.add(sun, sun.target);\n}\n\n// Robot vacuum: added after the bake and merge so it stays a separate,\n// movable object. Like on real devices it is not a tracked plane/mesh. Its\n// materials are its own, since the bake may have set vertexColors on shared\n// ones, and it casts no shadow into the sun's shadow map, which is rendered\n// once; the blob shadow follows it instead.\nfunction addRobot({\n center,\n radius,\n speed = 0.35,\n}: NonNullable<RoomSpec['robot']>) {\n const robot = new THREE.Group();\n robot.name = 'robot';\n // It moves, so it is not part of the room's global mesh.\n robot.userData.xrGlobalMesh = false;\n scene.add(robot);\n mesh(\n own(new THREE.CylinderGeometry(0.17, 0.17, 0.075, 48)),\n standard({ color: '#232325', roughness: 0.25, metalness: 0.1 }),\n [0, 0.045, 0],\n robot,\n { cast: false },\n );\n mesh(\n own(new THREE.TorusGeometry(0.17, 0.012, 8, 48)),\n standard({ color: '#4a4a4c', roughness: 0.6 }),\n [0, 0.03, 0],\n robot,\n { cast: false },\n ).rotation.x = Math.PI / 2;\n mesh(\n own(new THREE.CylinderGeometry(0.045, 0.045, 0.025, 32)),\n standard({ color: '#3a3a3c', roughness: 0.4 }),\n [0, 0.095, 0.06],\n robot,\n { cast: false },\n );\n mesh(\n own(new THREE.CircleGeometry(0.008, 12)),\n mats.bulb(),\n [0.05, 0.0835, -0.1],\n robot,\n { cast: false },\n ).rotation.x = -Math.PI / 2;\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = 64;\n const ctx = canvas.getContext('2d')!;\n const gradient = ctx.createRadialGradient(32, 32, 24, 32, 32, 32);\n gradient.addColorStop(0, 'rgba(255,255,255,1)');\n gradient.addColorStop(1, 'rgba(255,255,255,0)');\n ctx.fillStyle = gradient;\n ctx.fillRect(0, 0, 64, 64);\n const shadow = mesh(\n own(new THREE.PlaneGeometry(0.4, 0.4)),\n own(\n new THREE.MeshBasicMaterial({\n color: 'black',\n alphaMap: own(new THREE.CanvasTexture(canvas)),\n transparent: true,\n opacity: 0.45,\n depthWrite: false,\n }),\n ),\n [0, 0.008, 0],\n robot,\n { cast: false, receive: false },\n );\n shadow.rotation.x = -Math.PI / 2;\n let time = 0;\n const place = () => {\n const angle = time * speed;\n robot.position.set(\n center[0] + Math.cos(angle) * radius[0],\n 0,\n center[1] + Math.sin(angle) * radius[1],\n );\n robot.rotation.y = Math.atan2(\n Math.sin(angle) * radius[0],\n -Math.cos(angle) * radius[1],\n );\n };\n place();\n onFrame((delta) => {\n time += delta;\n place();\n });\n}\n\nfunction finish() {\n buildShell();\n for (const { object, w, h } of R.lit) {\n (object.material as THREE.MeshStandardMaterial).lightMap = bakeLightmap(\n object,\n w,\n h,\n );\n }\n bakeFurnitureShading();\n mergeStaticMeshes();\n scene.background = new THREE.Color('#e6e1d8');\n scene.environment = roomEnvironment();\n scene.environmentIntensity = 1.2;\n addSun();\n scene.rendering.shadows = true;\n scene.rendering.toneMapping = THREE.AgXToneMapping;\n scene.rendering.toneMappingExposure = 0.95;\n if (R.spec.robot) addRobot(R.spec.robot);\n\n let entities = 0;\n scene.traverse((object) => {\n if (object.userData.xrPlane) entities++;\n if (object.userData.xrMesh) entities++;\n });\n if (entities > MAX_ENTITIES) {\n console.warn(\n `${R.spec.name}: ${entities} planes and meshes; a scanned room usually reports at most ${MAX_ENTITIES}`,\n );\n }\n}\n\n// ---------------------------------------------------------------- seating\n\n// A room scan reports a couch as a volume plus a seat plane; the seat plane is\n// invisible (the cushions are what you see and hit).\nfunction couchSeat(\n g: THREE.Object3D,\n width: number,\n depth: number,\n height: number,\n z = 0,\n) {\n const seat = mesh(unitPlane, mats.hidden(), [0, height, z], g, {\n cast: false,\n receive: false,\n });\n seat.rotation.x = -Math.PI / 2;\n seat.scale.set(width, depth, 1);\n seat.userData.xrPlane = 'couch';\n return seat;\n}\n\n// Three-seat (or two-seat) sofa with seat and back cushions and two pillows.\nfunction sofa(\n g: THREE.Object3D,\n { width = 2.1, color = '#7f868b', pillows = ['#c79e68', '#e8e2d5'] } = {},\n) {\n const fabric = fabricMaterial(color, 51);\n mesh(roundedBox(width, 0.2, 0.92, 0.04), fabric, [0, 0.19, 0], g);\n mesh(roundedBox(width, 0.52, 0.2, 0.07), fabric, [0, 0.55, -0.36], g);\n for (const s of [-1, 1]) {\n mesh(\n roundedBox(0.2, 0.38, 0.92, 0.07, 0.008),\n fabric,\n [s * (width / 2 - 0.1), 0.45, 0],\n g,\n );\n for (const z of [-0.36, 0.36])\n cylinder(\n 0.016,\n 0.011,\n 0.09,\n mats.blackMetal(),\n [s * (width / 2 - 0.08), 0.045, z],\n g,\n 10,\n ).castShadow = false;\n }\n const seats = width > 1.7 ? 3 : 2;\n const seat = (width - 0.4) / seats;\n for (let i = 0; i < seats; i++) {\n const x = -width / 2 + 0.2 + seat * (i + 0.5);\n mesh(\n roundedBox(seat - 0.008, 0.16, 0.68, 0.06, 0.022, 6),\n fabric,\n [x, 0.37, 0.1],\n g,\n );\n mesh(\n roundedBox(seat - 0.015, 0.46, 0.2, 0.09, 0.025, 6),\n fabric,\n [x, 0.66, -0.2],\n g,\n ).rotation.x = -0.2;\n }\n pillows.forEach((pillow, i) => {\n const side = i === 0 ? -1 : 1;\n const object = mesh(\n roundedBox(0.46, 0.46, 0.13, 0.07, 0.04, 6),\n fabricMaterial(pillow, 52 + i),\n [side * (width / 2 - 0.38), 0.67, -0.07],\n g,\n );\n object.rotation.set(-0.3, -side * 0.3, side * 0.13);\n });\n couchSeat(g, width - 0.4, 0.66, 0.45, 0.1);\n volume('couch', [width, 0.86, 0.94], [0, 0.43, 0], g, 0.85);\n return g;\n}\n\n// Upholstered armchair with wooden legs.\nfunction armchair(g: THREE.Object3D, { color = '#b2643e' } = {}) {\n const fabric = fabricMaterial(color, 54);\n mesh(roundedBox(0.78, 0.28, 0.8, 0.06, 0.008), fabric, [0, 0.29, 0], g);\n mesh(\n roundedBox(0.66, 0.12, 0.62, 0.05, 0.022, 6),\n fabric,\n [0, 0.48, 0.06],\n g,\n );\n mesh(\n roundedBox(0.78, 0.5, 0.14, 0.06, 0.008),\n fabric,\n [0, 0.65, -0.33],\n g,\n ).rotation.x = -0.14;\n for (const s of [-1, 1]) {\n mesh(roundedBox(0.1, 0.22, 0.74, 0.045), fabric, [s * 0.36, 0.55, 0.02], g);\n for (const z of [-0.32, 0.32])\n mesh(\n roundedBox(0.035, 0.16, 0.035, 0.012),\n mats.walnut(),\n [s * 0.32, 0.08, z],\n g,\n ).rotation.z = s * 0.12;\n }\n couchSeat(g, 0.62, 0.58, 0.54, 0.06);\n volume('couch', [0.8, 0.9, 0.82], [0, 0.45, 0], g, 0.6);\n return g;\n}\n\n// Lounge chair: wooden side frames with seat and back cushions.\nfunction loungeChair(\n g: THREE.Object3D,\n { color = '#7d8a6a', wood = mats.walnut() } = {},\n) {\n const fabric = fabricMaterial(color, 57);\n for (const s of [-1, 1]) {\n mesh(roundedBox(0.04, 0.04, 0.78, 0.012), wood, [s * 0.34, 0.56, 0], g);\n const front = mesh(\n roundedBox(0.04, 0.58, 0.04, 0.012),\n wood,\n [s * 0.34, 0.28, 0.32],\n g,\n );\n front.rotation.x = 0.08;\n const back = mesh(\n roundedBox(0.04, 0.8, 0.04, 0.012),\n wood,\n [s * 0.34, 0.4, -0.3],\n g,\n );\n back.rotation.x = -0.32;\n }\n mesh(roundedBox(0.66, 0.11, 0.6, 0.04, 0.02, 6), fabric, [0, 0.4, 0.04], g);\n const back = mesh(\n roundedBox(0.62, 0.52, 0.11, 0.04, 0.015, 6),\n fabric,\n [0, 0.7, -0.24],\n g,\n );\n back.rotation.x = -0.32;\n couchSeat(g, 0.62, 0.56, 0.455, 0.04);\n volume('couch', [0.74, 0.88, 0.84], [0, 0.44, 0], g, 0.5);\n return g;\n}\n\n// Wooden dining chair.\nfunction woodChair(g: THREE.Object3D, { wood = mats.oak() } = {}) {\n mesh(roundedBox(0.44, 0.03, 0.42, 0.012), wood, [0, 0.45, 0], g);\n const back = mesh(\n roundedBox(0.42, 0.16, 0.025, 0.01),\n wood,\n [0, 0.76, -0.2],\n g,\n );\n back.rotation.x = 0.1;\n for (const x of [-0.19, 0.19]) {\n for (const z of [-0.18, 0.18]) {\n const height = z < 0 ? 0.84 : 0.44;\n mesh(\n roundedBox(0.025, height, 0.025, 0.008),\n wood,\n [x, height / 2, z],\n g,\n );\n }\n }\n volume('other', [0.44, 0.85, 0.42], [0, 0.425, 0], g, 0.4);\n return g;\n}\n\n// Office task chair on a five-star base.\nfunction taskChair(g: THREE.Object3D, { color = '#2f3033' } = {}) {\n const fabric = fabricMaterial(color, 58);\n const plastic = mats.charcoal();\n for (let i = 0; i < 5; i++) {\n const angle = (i / 5) * Math.PI * 2;\n const spoke = box(\n [0.03, 0.025, 0.3],\n plastic,\n [Math.sin(angle) * 0.15, 0.06, Math.cos(angle) * 0.15],\n g,\n );\n spoke.rotation.y = angle;\n mesh(\n own(new THREE.SphereGeometry(0.025, 10, 8)),\n plastic,\n [Math.sin(angle) * 0.29, 0.025, Math.cos(angle) * 0.29],\n g,\n );\n }\n cylinder(0.022, 0.022, 0.36, mats.steel(), [0, 0.24, 0], g, 12);\n mesh(roundedBox(0.5, 0.08, 0.48, 0.03, 0.012, 4), fabric, [0, 0.46, 0.02], g);\n const back = mesh(\n roundedBox(0.46, 0.56, 0.06, 0.03, 0, 4),\n fabric,\n [0, 0.82, -0.22],\n g,\n );\n back.rotation.x = -0.1;\n box([0.04, 0.3, 0.03], plastic, [0, 0.58, -0.24], g).rotation.x = -0.1;\n for (const s of [-1, 1]) {\n box([0.025, 0.18, 0.025], plastic, [s * 0.25, 0.56, 0.02], g);\n mesh(\n roundedBox(0.06, 0.025, 0.24, 0.01),\n plastic,\n [s * 0.25, 0.66, 0.02],\n g,\n );\n }\n volume('other', [0.62, 1.1, 0.62], [0, 0.55, 0], g, 0.35);\n return g;\n}\n\n// Upholstered shell chair on slim metal legs (meeting rooms).\nfunction shellChair(g: THREE.Object3D, { color = '#7d8a6a' } = {}) {\n const fabric = fabricMaterial(color, 59);\n mesh(roundedBox(0.5, 0.09, 0.48, 0.04, 0.012, 4), fabric, [0, 0.46, 0.02], g);\n const back = mesh(\n roundedBox(0.52, 0.36, 0.08, 0.04, 0, 4),\n fabric,\n [0, 0.7, -0.21],\n g,\n );\n back.rotation.x = -0.14;\n for (const s of [-1, 1])\n mesh(\n roundedBox(0.07, 0.2, 0.4, 0.03, 0, 4),\n fabric,\n [s * 0.24, 0.58, -0.02],\n g,\n );\n for (const x of [-0.2, 0.2]) {\n for (const z of [-0.18, 0.2]) {\n const leg = cylinder(\n 0.01,\n 0.008,\n 0.44,\n mats.blackMetal(),\n [x * 1.05, 0.22, z * 1.05],\n g,\n 8,\n );\n leg.rotation.set(z > 0 ? 0.08 : -0.08, 0, x > 0 ? -0.06 : 0.06);\n }\n }\n volume('other', [0.58, 0.88, 0.56], [0, 0.44, 0], g, 0.35);\n return g;\n}\n\n// Bar or counter stool with a round seat and a foot ring.\nfunction stool(g: THREE.Object3D, { height = 0.65, wood = mats.oak() } = {}) {\n cylinder(0.18, 0.17, 0.04, wood, [0, height - 0.02, 0], g, 32);\n for (let i = 0; i < 4; i++) {\n const angle = (i / 4) * Math.PI * 2 + Math.PI / 4;\n const leg = cylinder(\n 0.014,\n 0.016,\n height - 0.03,\n wood,\n [Math.sin(angle) * 0.14, (height - 0.03) / 2, Math.cos(angle) * 0.14],\n g,\n 8,\n );\n leg.rotation.set(Math.cos(angle) * 0.1, 0, -Math.sin(angle) * 0.1);\n }\n const ring = mesh(\n own(new THREE.TorusGeometry(0.15, 0.008, 6, 32)),\n mats.blackMetal(),\n [0, height * 0.35, 0],\n g,\n );\n ring.rotation.x = Math.PI / 2;\n volume('other', [0.4, height, 0.4], [0, height / 2, 0], g, 0.3);\n return g;\n}\n\n// ------------------------------------------------------------ tables, desks\n\ntype LegStyle = 'four' | 'frame' | 'pedestal';\n\n// Rectangular table: the top is a WebXR plane (`label`, default 'table').\nfunction table(\n g: THREE.Object3D,\n {\n width = 1.2,\n depth = 0.75,\n height = 0.74,\n top = mats.oak() as THREE.Material,\n legs = 'four' as LegStyle,\n legMaterial = mats.blackMetal() as THREE.Material,\n label = 'table',\n } = {},\n) {\n const surface = mesh(\n roundedBox(width, 0.03, depth, 0.01),\n top,\n [0, height - 0.015, 0],\n g,\n );\n surface.userData.xrPlane = label;\n const legHeight = height - 0.03;\n if (legs === 'pedestal') {\n cylinder(0.04, 0.05, legHeight, legMaterial, [0, legHeight / 2, 0], g, 16);\n cylinder(\n Math.min(width, depth) * 0.28,\n Math.min(width, depth) * 0.3,\n 0.02,\n legMaterial,\n [0, 0.01, 0],\n g,\n 32,\n );\n } else {\n const inset = 0.06;\n for (const x of [-width / 2 + inset, width / 2 - inset]) {\n for (const z of [-depth / 2 + inset, depth / 2 - inset]) {\n mesh(\n roundedBox(0.04, legHeight, 0.04, 0.008),\n legMaterial,\n [x, legHeight / 2, z],\n g,\n );\n }\n if (legs === 'frame')\n box([0.04, 0.03, depth - 2 * inset], legMaterial, [x, 0.04, 0], g);\n }\n }\n volume(label, [width, height, depth], [0, height / 2, 0], g, 0.45);\n return g;\n}\n\n// Round pedestal table: the top is a WebXR plane.\nfunction roundTable(\n g: THREE.Object3D,\n {\n radius = 0.45,\n height = 0.74,\n top = mats.oak() as THREE.Material,\n label = 'table',\n } = {},\n) {\n const surface = mesh(\n own(new THREE.CylinderGeometry(radius, radius, 0.03, 64)),\n top,\n [0, height - 0.015, 0],\n g,\n );\n surface.userData.xrPlane = label;\n cylinder(\n 0.04,\n 0.05,\n height - 0.03,\n mats.blackMetal(),\n [0, (height - 0.03) / 2, 0],\n g,\n 16,\n );\n cylinder(\n radius * 0.53,\n radius * 0.58,\n 0.02,\n mats.blackMetal(),\n [0, 0.01, 0],\n g,\n 48,\n );\n volume(label, [radius * 2, height, radius * 2], [0, height / 2, 0], g, 0.45);\n return g;\n}\n\n// Desk: a 'desk' table, optionally with a drawer pedestal on one side.\nfunction desk(\n g: THREE.Object3D,\n {\n width = 1.4,\n depth = 0.7,\n height = 0.74,\n top = mats.oak() as THREE.Material,\n drawers = 'right' as 'left' | 'right' | 'none',\n } = {},\n) {\n table(g, { width, depth, height, top, legs: 'four', label: 'desk' });\n if (drawers !== 'none') {\n const side = drawers === 'right' ? 1 : -1;\n const pedestal = group(side * (width / 2 - 0.26), 0, 0, 0, g);\n casegood(pedestal, {\n width: 0.4,\n height: height - 0.04,\n depth: depth - 0.12,\n fronts: 'drawers',\n count: 3,\n body: top,\n label: '',\n });\n }\n return g;\n}\n\n// ---------------------------------------------------------------- storage\n\n// Cabinet, sideboard, dresser, nightstand or wardrobe: a carcass with door\n// or drawer fronts (or open shelves), optional legs, reported as an XRMesh\n// (`label`, default 'shelf'; '' for none).\nfunction casegood(\n g: THREE.Object3D,\n {\n width = 1.2,\n height = 0.75,\n depth = 0.45,\n fronts = 'doors' as 'doors' | 'drawers' | 'open',\n count = 2,\n body = mats.walnut() as THREE.Material,\n front = undefined as THREE.Material | undefined,\n legs = 0,\n handles = 'bar' as 'bar' | 'knob' | 'none',\n label = 'shelf',\n } = {},\n) {\n const h = height - legs;\n const y0 = legs;\n const faces = front ?? body;\n if (fronts === 'open') {\n for (const x of [-width / 2 + 0.01, width / 2 - 0.01])\n box([0.02, h, depth], body, [x, y0 + h / 2, 0], g);\n box([width, h, 0.012], body, [0, y0 + h / 2, -depth / 2 + 0.006], g);\n for (let i = 0; i <= count; i++)\n box(\n [width - 0.04, 0.02, depth],\n body,\n [0, y0 + 0.01 + (i * (h - 0.02)) / count, 0],\n g,\n );\n } else {\n box([width, h, depth], body, [0, y0 + h / 2, 0], g);\n const columns = fronts === 'doors' ? count : 1;\n const rows = fronts === 'drawers' ? count : 1;\n const cw = width / columns;\n const ch = h / rows;\n for (let c = 0; c < columns; c++) {\n for (let r = 0; r < rows; r++) {\n const x = -width / 2 + cw * (c + 0.5);\n const y = y0 + ch * (r + 0.5);\n box(\n [cw - 0.006, ch - 0.006, 0.018],\n faces,\n [x, y, depth / 2 + 0.009],\n g,\n );\n if (handles === 'bar') {\n if (fronts === 'drawers')\n box(\n [Math.min(0.16, cw * 0.4), 0.012, 0.014],\n mats.blackMetal(),\n [x, y + ch * 0.25, depth / 2 + 0.025],\n g,\n );\n else\n box(\n [0.012, Math.min(0.18, ch * 0.3), 0.014],\n mats.blackMetal(),\n [x + (c % 2 ? -1 : 1) * (cw / 2 - 0.05), y, depth / 2 + 0.025],\n g,\n );\n } else if (handles === 'knob') {\n mesh(\n own(new THREE.SphereGeometry(0.014, 12, 8)),\n mats.brass(),\n [\n fronts === 'drawers' ? x : x + (c % 2 ? -1 : 1) * (cw / 2 - 0.05),\n y + (fronts === 'drawers' ? ch * 0.2 : 0),\n depth / 2 + 0.03,\n ],\n g,\n );\n }\n }\n }\n }\n if (legs > 0) {\n for (const x of [-width / 2 + 0.05, width / 2 - 0.05]) {\n for (const z of [-depth / 2 + 0.05, depth / 2 - 0.05])\n cylinder(0.016, 0.011, legs, mats.walnut(), [x, legs / 2, z], g, 8);\n }\n }\n if (label)\n volume(\n label,\n [width, height, depth + 0.03],\n [0, height / 2, 0.015],\n g,\n 0.7,\n );\n return g;\n}\n\n// Open bookshelf filled with instanced books.\nfunction bookshelf(\n g: THREE.Object3D,\n {\n width = 0.9,\n height = 1.9,\n depth = 0.34,\n levels = 5,\n wood = mats.walnut() as THREE.Material,\n seed = 0,\n } = {},\n) {\n for (const x of [-width / 2, width / 2])\n box([0.025, height, depth], wood, [x, height / 2, 0], g);\n box(\n [width, height, 0.012],\n wood === mats.walnut() ? mats.darkWalnut() : wood,\n [0, height / 2, -depth / 2 + 0.006],\n g,\n );\n const ys = Array.from(\n { length: levels + 1 },\n (_, i) => 0.05 + (i * (height - 0.06)) / levels,\n );\n for (const y of ys) box([width, 0.025, depth], wood, [0, y, 0], g);\n const palette = [\n '#2f3e46',\n '#b08d57',\n '#e3dccf',\n '#7a3b2e',\n '#55624a',\n '#cbb79a',\n '#3c3c3c',\n '#8c4f3b',\n ];\n const capacity = levels * 40;\n const books = own(\n new THREE.InstancedMesh(\n own(new THREE.BoxGeometry(1, 1, 1)),\n mats.book(),\n capacity,\n ),\n );\n books.castShadow = books.receiveShadow = true;\n const matrix = new THREE.Matrix4();\n const rotation = new THREE.Quaternion();\n const color = new THREE.Color();\n const spacing = (height - 0.06) / levels;\n let count = 0;\n for (let level = 0; level < levels; level++) {\n let x = -width / 2 + 0.02;\n const y = ys[level] + 0.0125;\n const end = (level + seed) % 2 ? width * 0.15 : width / 2 - 0.02;\n while (x < end - 0.03 && count < capacity) {\n const k = count + seed * 97;\n const thickness = 0.018 + hash(k, 5, 5) * 0.03;\n const tall = Math.min(spacing - 0.04, 0.19 + hash(k, 6, 6) * 0.11);\n const deep = Math.min(depth - 0.04, 0.17 + hash(k, 7, 7) * 0.07);\n rotation.setFromAxisAngle(\n new THREE.Vector3(0, 0, 1),\n x + thickness > end - 0.05 ? -0.18 : 0,\n );\n matrix.compose(\n new THREE.Vector3(x + thickness / 2, y + tall / 2, 0.02),\n rotation,\n new THREE.Vector3(thickness, tall, deep),\n );\n books.setMatrixAt(count, matrix);\n color.set(palette[Math.floor(hash(k, 8, 8) * palette.length)]);\n books.setColorAt(count, color.multiplyScalar(0.8 + hash(k, 9, 9) * 0.3));\n x += thickness + 0.0015;\n count++;\n }\n }\n books.count = count;\n g.add(books);\n volume('shelf', [width, height, depth], [0, height / 2, 0], g, 0.7);\n return g;\n}\n\n// ---------------------------------------------------------------- lighting\n\n// Table lamp; `lit` adds a warm point light (use at most two per room).\nfunction tableLamp(g: THREE.Object3D, { lit = false } = {}) {\n const base = mesh(\n own(new THREE.SphereGeometry(0.085, 24, 16)),\n mats.ceramic(),\n [0, 0.09, 0],\n g,\n );\n base.scale.y = 1.1;\n cylinder(0.009, 0.009, 0.18, mats.brass(), [0, 0.24, 0], g, 8);\n mesh(\n own(new THREE.CylinderGeometry(0.12, 0.16, 0.22, 40, 1, true)),\n lit ? mats.lampShade() : mats.linenShade(),\n [0, 0.38, 0],\n g,\n { cast: false },\n );\n if (lit) {\n mesh(\n own(new THREE.SphereGeometry(0.03, 12, 8)),\n mats.bulb(),\n [0, 0.33, 0],\n g,\n { cast: false, receive: false },\n );\n const glow = new THREE.PointLight('#ffc27a', 1.4, 3.5, 2);\n glow.position.set(0, 0.35, 0);\n g.add(glow);\n }\n volume('lamp', [0.32, 0.5, 0.32], [0, 0.25, 0], g, 0.3);\n return g;\n}\n\n// Floor lamp with a drum shade.\nfunction floorLamp(g: THREE.Object3D, { lit = false } = {}) {\n cylinder(0.14, 0.15, 0.02, mats.blackMetal(), [0, 0.01, 0], g, 40);\n cylinder(0.009, 0.009, 1.45, mats.blackMetal(), [0, 0.74, 0], g, 10);\n mesh(\n own(new THREE.CylinderGeometry(0.2, 0.2, 0.3, 48, 1, true)),\n lit ? mats.lampShade() : mats.linenShade(),\n [0, 1.55, 0],\n g,\n );\n const diffuser = mesh(\n own(new THREE.CircleGeometry(0.19, 40)),\n paintMaterial('#cfc7b8', 1),\n [0, 1.67, 0],\n g,\n { cast: false },\n );\n diffuser.rotation.x = Math.PI / 2;\n if (lit) {\n const glow = new THREE.PointLight('#ffc27a', 1.6, 4, 2);\n glow.position.set(0, 1.5, 0);\n g.add(glow);\n }\n volume('lamp', [0.4, 1.72, 0.4], [0, 0.86, 0], g, 0.4);\n return g;\n}\n\n// Pendant lamp hanging from a ceiling point (put `g` on the ceiling).\nfunction pendant(\n g: THREE.Object3D,\n { drop = 0.75, color = '#a65f40', radius = 0.2 } = {},\n) {\n cylinder(0.05, 0.05, 0.015, mats.blackMetal(), [0, -0.008, 0], g, 24);\n cylinder(0.003, 0.003, drop, mats.blackMetal(), [0, -drop / 2, 0], g, 6);\n const shade = mesh(\n own(\n new THREE.SphereGeometry(radius, 40, 16, 0, Math.PI * 2, 0, Math.PI / 2),\n ),\n standard({ color, roughness: 0.6, side: THREE.DoubleSide }),\n [0, -drop - radius * 0.55, 0],\n g,\n );\n shade.scale.y = 0.75;\n volume(\n 'lamp',\n [radius * 2, radius * 0.8, radius * 2],\n [0, -drop - radius * 0.35, 0],\n g,\n 0.2,\n );\n return g;\n}\n\n// Adjustable desk lamp (no volume: it sits on a desk volume).\nfunction deskLamp(g: THREE.Object3D) {\n cylinder(0.07, 0.08, 0.02, mats.blackMetal(), [0, 0.01, 0], g, 24);\n const lower = cylinder(\n 0.008,\n 0.008,\n 0.34,\n mats.blackMetal(),\n [0.05, 0.17, 0],\n g,\n 8,\n );\n lower.rotation.z = -0.3;\n const upper = cylinder(\n 0.008,\n 0.008,\n 0.3,\n mats.blackMetal(),\n [0.03, 0.42, 0],\n g,\n 8,\n );\n upper.rotation.z = 1.1;\n const head = mesh(\n own(new THREE.ConeGeometry(0.06, 0.12, 24, 1, true)),\n standard({ color: '#1f1f1f', roughness: 0.5, side: THREE.DoubleSide }),\n [-0.12, 0.47, 0],\n g,\n );\n head.rotation.z = 0.9;\n return g;\n}\n\n// ------------------------------------------------------------------ plants\n\n// Leafy floor plant (fiddle-leaf fig style) in a pot.\nfunction plant(\n g: THREE.Object3D,\n { height = 1.7, pot = mats.pot() as THREE.Material, seed = 0 } = {},\n) {\n const s = height / 1.95;\n const potRadius = 0.19 * Math.max(0.7, s);\n cylinder(potRadius, potRadius * 0.82, 0.38 * s, pot, [0, 0.19 * s, 0], g, 40);\n cylinder(\n potRadius * 0.94,\n potRadius * 0.94,\n 0.01,\n mats.soil(),\n [0, 0.37 * s, 0],\n g,\n 24,\n );\n mesh(\n own(\n new THREE.CylinderGeometry(0.014, 0.026, 1.5 * s, 8).translate(\n 0,\n 0.75 * s,\n 0,\n ),\n ),\n mats.bark(),\n [0, 0.36 * s, 0],\n g,\n );\n const leafGeometry = own(new THREE.PlaneGeometry(0.28, 0.38, 3, 4));\n const lp = leafGeometry.getAttribute('position');\n for (let i = 0; i < lp.count; i++) {\n const x = lp.getX(i);\n const y = lp.getY(i) + 0.19;\n lp.setXYZ(i, x, y + 0.04, Math.abs(x) * 0.3 - Math.pow(y / 0.38, 2) * 0.05);\n }\n leafGeometry.computeVertexNormals();\n const twig = own(\n new THREE.CylinderGeometry(0.007, 0.011, 1, 6).translate(0, 0.5, 0),\n );\n const anchors: { at: THREE.Vector3; yaw: number }[] = [];\n for (let b = 0; b < 4; b++) {\n const start = new THREE.Vector3(0, (1.05 + b * 0.19) * s, 0);\n const yaw = b * 2.1 + seed;\n const length = (0.42 - b * 0.05) * s;\n const direction = new THREE.Vector3(\n Math.sin(yaw) * 0.75,\n 0.66,\n Math.cos(yaw) * 0.75,\n ).normalize();\n const branch = mesh(twig, mats.bark(), [start.x, start.y, start.z], g);\n branch.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);\n branch.scale.set(1, length, 1);\n for (let k = 1; k <= 3; k++)\n anchors.push({\n at: start.clone().addScaledVector(direction, (length * k) / 3),\n yaw,\n });\n }\n for (let k = 0; k < 10; k++)\n anchors.push({\n at: new THREE.Vector3(0.02, (1.0 + k * 0.08) * s, 0.01),\n yaw: k * 2.39996 + seed,\n });\n const leaves = own(\n new THREE.InstancedMesh(leafGeometry, mats.leaf(), anchors.length * 2),\n );\n leaves.castShadow = leaves.receiveShadow = true;\n const matrix = new THREE.Matrix4();\n const rotation = new THREE.Quaternion();\n const euler = new THREE.Euler();\n const color = new THREE.Color();\n let index = 0;\n for (const [a, { at, yaw }] of anchors.entries()) {\n for (const side of [-1, 1]) {\n const k = a + seed * 13;\n const leafYaw = yaw + side * (0.5 + hash(k, side + 2, 3) * 0.6);\n const droop = hash(k, side + 2, 8) < 0.3;\n const pitch = droop\n ? -1.65 - hash(k, side + 2, 1) * 0.3\n : -0.85 - hash(k, side + 2, 1) * 0.55;\n euler.set(pitch, leafYaw, (hash(k, side + 2, 5) - 0.5) * 0.88, 'YXZ');\n rotation.setFromEuler(euler);\n const size = (0.6 + hash(k, side + 2, 2) * 0.6) * Math.max(0.75, s);\n matrix.compose(at, rotation, new THREE.Vector3(size, size, size));\n leaves.setMatrixAt(index, matrix);\n const lit = 0.65 + 0.35 * hash(k, side + 2, 6);\n color.setRGB(lit, lit, lit * 0.88);\n leaves.setColorAt(index, color);\n index++;\n }\n }\n g.add(leaves);\n volume('plant', [0.75 * s, height, 0.75 * s], [0, height / 2, 0], g, 0.4);\n return g;\n}\n\n// Small tabletop plant (no volume).\nfunction smallPlant(\n g: THREE.Object3D,\n { size = 0.22, pot = mats.terracotta() as THREE.Material, seed = 0 } = {},\n) {\n const r = size * 0.32;\n cylinder(r, r * 0.8, size * 0.45, pot, [0, size * 0.225, 0], g, 24);\n const leafGeometry = own(\n new THREE.PlaneGeometry(0.28, 0.38, 2, 3).translate(0, 0.21, 0),\n );\n const leaves = own(new THREE.InstancedMesh(leafGeometry, mats.leaf(), 12));\n leaves.castShadow = true;\n const matrix = new THREE.Matrix4();\n const euler = new THREE.Euler();\n for (let i = 0; i < 12; i++) {\n euler.set(\n -0.4 - hash(i, 1, seed) * 0.8,\n (i / 12) * Math.PI * 2 + seed,\n 0,\n 'YXZ',\n );\n const scale = size * (0.7 + hash(i, 2, seed) * 0.5);\n matrix.compose(\n new THREE.Vector3(0, size * 0.42, 0),\n new THREE.Quaternion().setFromEuler(euler),\n new THREE.Vector3(scale, scale, scale),\n );\n leaves.setMatrixAt(i, matrix);\n }\n g.add(leaves);\n return g;\n}\n\n// ---------------------------------------------------------- floor and walls\n\n// Rug lying on the floor, lit like the floor beneath it.\nfunction rug(\n g: THREE.Object3D,\n {\n width = 2.4,\n depth = 1.7,\n style = 'lattice' as RugStyle,\n field = '#e6ddcc',\n accent = '#5a524a',\n } = {},\n) {\n const material = shellMaterial({\n map: fitted(rugCanvas(width, depth, style, field, accent), width, depth),\n roughness: 1,\n });\n const object = mesh(panel(width, depth), material, [0, 0.006, 0], g, {\n cast: false,\n });\n object.rotation.x = -Math.PI / 2;\n litSurface(object, width, depth);\n return g;\n}\n\ntype ArtStyle = 'abstract' | 'botanical' | 'landscape';\n\n// Framed picture on a wall group (local +Z into the room). The whole frame\n// is the WebXR 'wall art' plane, as a room scan would label it.\nfunction picture(\n g: THREE.Object3D,\n {\n width = 0.9,\n height = 0.65,\n art = 'abstract' as ArtStyle,\n seed = 1,\n frame = mats.blackMetal() as THREE.Material,\n palette = ['#b9673f', '#2c4547', '#d7a24b', '#8d9b85'],\n } = {},\n) {\n box([width, height, 0.03], frame, [0, 0, 0.015], g).userData.xrPlane =\n 'wall art';\n const matBorder = Math.min(width, height) * 0.1;\n mesh(unitPlane, mats.trim(), [0, 0, 0.0305], g, { cast: false }).scale.set(\n width - 0.04,\n height - 0.04,\n 1,\n );\n const w = width - 2 * matBorder;\n const h = height - 2 * matBorder;\n const map =\n art === 'botanical'\n ? botanicalTexture(seed)\n : art === 'landscape'\n ? landscapeTexture(seed, w / h)\n : paintingTexture(seed, palette, w / h);\n mesh(unitPlane, standard({ map, roughness: 0.85 }), [0, 0, 0.031], g, {\n cast: false,\n }).scale.set(w, h, 1);\n return g;\n}\n\n// Mirror on a wall group: round with a brass ring, or rectangular with a\n// wooden frame. A 'wall art' plane.\nfunction mirror(\n g: THREE.Object3D,\n {\n radius = 0.36,\n width = 0,\n height = 0,\n frame = mats.oak() as THREE.Material,\n } = {},\n) {\n if (width && height) {\n box([width, height, 0.03], frame, [0, 0, 0.015], g).userData.xrPlane =\n 'wall art';\n mesh(unitPlane, mats.mirror(), [0, 0, 0.031], g, { cast: false }).scale.set(\n width - 0.08,\n height - 0.08,\n 1,\n );\n } else {\n const glass = mesh(\n own(new THREE.CircleGeometry(radius, 64)),\n mats.mirror(),\n [0, 0, 0.012],\n g,\n { cast: false },\n );\n glass.userData.xrPlane = 'wall art';\n mesh(\n own(new THREE.TorusGeometry(radius + 0.01, 0.012, 12, 96)),\n mats.brass(),\n [0, 0, 0.014],\n g,\n );\n }\n return g;\n}\n\n// Wall-mounted display (screen off). A room scan reports screens as volumes\n// only (no plane).\nfunction wallScreen(g: THREE.Object3D, { width = 1.46, height = 0.84 } = {}) {\n box(\n [width, height, 0.028],\n paintMaterial('#0a0a0a', 0.35, 0.5),\n [0, 0, 0.014],\n g,\n );\n const screen = mesh(unitPlane, mats.screen(), [0, 0, 0.0285], g, {\n cast: false,\n });\n screen.scale.set(width - 0.03, height - 0.03, 1);\n volume('screen', [width, height, 0.04], [0, 0, 0.02], g, 0.3);\n return g;\n}\n\n// Desk monitor on a stand (put `g` on the desk top); a 'screen' volume, as a\n// room scan reports screens.\n// A desk monitor; `tracked: false` leaves out its 'screen' volume (rooms with\n// many monitors stay within the objects a room scan reports).\nfunction monitor(\n g: THREE.Object3D,\n { width = 0.62, height = 0.37, tracked = true } = {},\n) {\n box([0.22, 0.012, 0.16], mats.charcoal(), [0, 0.006, 0], g);\n box([0.04, 0.16, 0.025], mats.charcoal(), [0, 0.09, -0.04], g);\n box(\n [width, height, 0.025],\n paintMaterial('#141414', 0.4),\n [0, 0.12 + height / 2, -0.02],\n g,\n );\n const screen = mesh(\n unitPlane,\n mats.screen(),\n [0, 0.12 + height / 2, -0.007],\n g,\n { cast: false },\n );\n screen.scale.set(width - 0.02, height - 0.03, 1);\n (tracked ? volume : occluder)(\n 'screen',\n [width, height + 0.12, 0.16],\n [0, (height + 0.12) / 2, -0.02],\n g,\n 0.2,\n );\n return g;\n}\n\n// Whiteboard or cork pinboard on a wall group; a 'wall art' plane.\nfunction board(\n g: THREE.Object3D,\n {\n width = 1.2,\n height = 0.9,\n kind = 'white' as 'white' | 'cork',\n seed = 0,\n } = {},\n) {\n box(\n [width, height, 0.02],\n kind === 'white' ? mats.steel() : mats.oak(),\n [0, 0, 0.01],\n g,\n ).userData.xrPlane = 'wall art';\n const surface = mesh(\n unitPlane,\n kind === 'white'\n ? paintMaterial('#f6f6f3', 0.25)\n : standard({ map: corkTexture(), roughness: 0.95 }),\n [0, 0, 0.0205],\n g,\n { cast: false },\n );\n surface.scale.set(width - 0.04, height - 0.04, 1);\n if (kind === 'cork') {\n const papers = ['#f3efe6', '#e7d9c4', '#d9e3d6', '#efe2d4'];\n for (let i = 0; i < 4; i++) {\n const sheet = mesh(\n unitPlane,\n paintMaterial(papers[i], 0.9),\n [\n (hash(i, 1, seed) - 0.5) * (width - 0.35),\n (hash(i, 2, seed) - 0.5) * (height - 0.35),\n 0.022 + i * 0.0005,\n ],\n g,\n { cast: false },\n );\n sheet.scale.set(0.21, 0.28, 1);\n sheet.rotation.z = (hash(i, 3, seed) - 0.5) * 0.15;\n }\n }\n return g;\n}\n\n// Felt acoustic panel on a wall group (no WebXR label).\nfunction acousticPanel(\n g: THREE.Object3D,\n { width = 0.6, height = 1.2, color = '#7d8a6a' } = {},\n) {\n mesh(\n roundedBox(width, height, 0.04, 0.01),\n fabricMaterial(color, 60),\n [0, 0, 0.02],\n g,\n );\n return g;\n}\n\n// ---------------------------------------------------------------------- room\n\n// Open office: a team office area, 8 x 7 m with a 3 m ceiling. Replaces the\n// office_large capture. A Quest room scan covers at most 10 x 10 m, so this\n// is one team's corner of a floor, not a whole open-plan floor.\n//\n// Layout (the viewer starts at the origin facing -Z):\n// back wall (-Z) wall art behind the bench desk; sofa in the lounge\n// left wall (-X) whiteboard\n// right wall (+X) three tall windows along the lounge\n// front wall (+Z) door\n// centre-left double-sided bench desk for six with monitors, a felt\n// privacy screen and hanging acoustic baffles above\n// centre planter cabinet run and a structural column\n// right lounge: sofa, two lounge chairs, coffee table, rug\n// A robot vacuum loops across the open floor at the front.\nconst room = createRoom({\n name: 'open_office',\n width: 8,\n depth: 7,\n height: 3,\n z0: -4.5,\n wall: '#eee9e1',\n windows: [\n {\n wall: 'right',\n at: -3.3,\n width: 1.5,\n sill: 0.6,\n head: 2.6,\n sheers: false,\n },\n {\n wall: 'right',\n at: -1.3,\n width: 1.5,\n sill: 0.6,\n head: 2.6,\n sheers: false,\n },\n { wall: 'right', at: 0.7, width: 1.5, sill: 0.6, head: 2.6, sheers: false },\n ],\n doors: [{ wall: 'front', at: -2.8 }],\n sun: { window: 1, elevation: 38, azimuth: 20 },\n texelsPerMeter: 12,\n robot: { center: [0, 1.25], radius: [2.1, 0.55], speed: 0.3 },\n});\n\n// Double-sided bench desk along local X with seats on both long sides: a\n// 'desk' plane, a felt privacy screen, monitors and keyboards per seat.\nfunction officeBench(\n g: THREE.Object3D,\n { length = 3.0, depth = 1.5, seatsPerSide = 3 } = {},\n) {\n const height = 0.74;\n const top = mesh(\n roundedBox(length, 0.03, depth, 0.008),\n mats.oak(),\n [0, height - 0.015, 0],\n g,\n );\n top.userData.xrPlane = 'desk';\n const frame = paintMaterial('#e9e6e0', 0.5, 0.3);\n for (const x of [-length / 2 + 0.06, 0, length / 2 - 0.06]) {\n for (const z of [-depth / 2 + 0.08, depth / 2 - 0.08])\n box([0.05, height - 0.03, 0.05], frame, [x, (height - 0.03) / 2, z], g);\n box([0.05, 0.05, depth - 0.16], frame, [x, height - 0.055, 0], g);\n }\n box(\n [length - 0.1, 0.4, 0.03],\n fabricMaterial('#7d8a72', 60),\n [0, height + 0.2, 0],\n g,\n );\n const spacing = length / seatsPerSide;\n for (const side of [-1, 1]) {\n for (let i = 0; i < seatsPerSide; i++) {\n const x = -length / 2 + spacing * (i + 0.5);\n // Untracked, to stay within the objects a room scan reports.\n monitor(group(x, height, side * 0.3, side > 0 ? 0 : Math.PI, g), {\n width: 0.6,\n height: 0.35,\n tracked: false,\n });\n mesh(\n roundedBox(0.42, 0.015, 0.13, 0.004),\n mats.charcoal(),\n [x, height + 0.008, side * 0.55],\n g,\n );\n }\n }\n volume('desk', [length, height, depth], [0, height / 2, 0], g, 0.45);\n return g;\n}\n\n// Low storage run along local X topped with a planter of leafy plants.\nfunction officePlanterCabinet(g: THREE.Object3D, length: number) {\n casegood(g, {\n width: length,\n height: 0.72,\n depth: 0.45,\n count: 4,\n body: mats.white(),\n front: mats.oak(),\n handles: 'none',\n });\n box([length - 0.1, 0.16, 0.32], mats.charcoal(), [0, 0.8, 0], g);\n const plants = Math.round(length / 0.45);\n for (let i = 0; i < plants; i++) {\n smallPlant(\n group(\n -length / 2 + 0.2 + (i * (length - 0.4)) / (plants - 1),\n 0.8,\n 0,\n i,\n g,\n ),\n { size: 0.42, pot: mats.charcoal(), seed: i },\n );\n }\n return g;\n}\n\n// Hanging felt baffles running along X, hung on thin cables.\nfunction officeBaffles(\n x: number,\n z0: number,\n z1: number,\n count: number,\n length: number,\n) {\n const felt = fabricMaterial('#a3ad94', 61);\n for (let i = 0; i < count; i++) {\n const z = z0 + ((z1 - z0) * i) / Math.max(1, count - 1);\n const baffle = group(x, 2.55, z);\n box([length, 0.32, 0.05], felt, [0, 0, 0], baffle);\n for (const dx of [-length / 2 + 0.2, length / 2 - 0.2])\n cylinder(0.002, 0.002, 0.29, mats.steel(), [dx, 0.305, 0], baffle, 4);\n }\n}\n\n// Work zone: bench desk for six, task chairs, baffles above, art and a\n// whiteboard on the walls.\nofficeBench(room.place(-1.6, -2.4), { length: 3.0, depth: 1.5 });\nfor (const x of [-2.6, -1.6, -0.6]) {\n taskChair(room.place(x, -3.5, 0.06 * x));\n taskChair(room.place(x, -1.28, Math.PI - 0.06 * x));\n}\nofficeBaffles(-1.6, -3.5, -1.3, 5, 2.8);\npicture(room.onWall('back', -1.6, 1.75), {\n width: 1.4,\n height: 0.95,\n palette: ['#7d8a72', '#b9673f', '#e2d5bf', '#3e4a46'],\n seed: 11,\n frame: mats.oak(),\n});\nboard(room.onWall('left', -2.4, 1.45), {\n width: 1.6,\n height: 1.0,\n kind: 'white',\n});\nplant(room.place(-3.55, -4.05), { height: 1.6, seed: 4 });\n\n// Zone divider: planter cabinet run and a structural column.\nofficePlanterCabinet(room.place(0.6, -2.4, Math.PI / 2), 2.4);\n{\n const column = room.place(0.6, -0.55);\n box([0.5, 3.0, 0.5], paintMaterial('#ece7df', 0.9), [0, 1.5, 0], column);\n volume('other', [0.5, 3.0, 0.5], [0, 1.5, 0], column, 0.6);\n}\n\n// Lounge by the windows: sofa, two lounge chairs, coffee table on a rug.\nsofa(room.against('back', 2.45, 0.94), {\n width: 2.1,\n color: '#b2643e',\n pillows: ['#7d8a72', '#e8e2d5'],\n});\nloungeChair(room.place(3.44, -2.45, -1.86), { color: '#7d8a72' });\nloungeChair(room.place(1.44, -2.35, 1.95), { color: '#7d8a72' });\nconst coffee = roundTable(room.place(2.45, -2.7), {\n radius: 0.45,\n height: 0.42,\n top: mats.walnut(),\n});\nsmallPlant(group(0.1, 0.42, 0.05, 0, coffee), {\n size: 0.2,\n pot: mats.ceramic(),\n seed: 9,\n});\nbox(\n [0.24, 0.03, 0.18],\n paintMaterial('#e2dacb', 0.8),\n [-0.15, 0.435, -0.05],\n coffee,\n).rotation.y = 0.3;\nrug(room.place(2.45, -2.95), {\n width: 2.8,\n depth: 2.3,\n style: 'border',\n field: '#d8cdb9',\n accent: '#9e927d',\n});\nofficeBaffles(2.45, -3.6, -2.2, 3, 2.4);\nplant(room.place(3.5, 1.95), { height: 1.5, seed: 6 });\n\nroom.finish();\n";export{n as default};
@@ -0,0 +1 @@
1
+ var n="// Generated by @iwer/sem rooms/build.mjs from rooms/src/kit.ts and rooms/src/open_studio.ts; edit those and rebuild.\nimport * as THREE from 'three';\nimport { onDispose, onFrame, scene } from '@drawcall/glts';\n\n// IWER room kit: shared building blocks for procedural GLTS rooms.\n// The builders are used by the room scripts this file is concatenated with.\n/* eslint-disable @typescript-eslint/no-unused-vars */\n//\n// A room script calls createRoom(spec) once, builds its furniture with the\n// builders below, then calls room.finish(). Builders tag WebXR planes\n// (userData.xrPlane) and add invisible volumes (userData.xrMesh) that also\n// shape the baked lighting. finish() adds the shell (floor, ceiling, walls\n// with window openings, windows, doors, baseboards, downlights), bakes\n// lightmaps and furniture ambient occlusion, merges static meshes per\n// material, paints the reflection probe and adds the sun.\n//\n// Conventions (meters): +Y up; the viewer starts at the origin facing -Z, so\n// keep the origin on open floor. The room spans x in [-width/2, width/2] and\n// z in [z0, z0 + depth]. Walls: back (-Z), front (+Z), left (-X), right (+X).\n// A position \"at\" along a wall is world x for back/front walls and world z\n// for left/right walls. Builders face +Z (their back is at local -Z), so\n// room.against(wall, ...) turns them to face into the room.\n//\n// SEM reports the scene's static geometry as the room's 'global mesh' (a\n// Quest behavior); objects that move or lie outside the room are tagged\n// userData.xrGlobalMesh = false. finish() merges untagged static meshes, so\n// an animated object must be tagged or added after finish().\n//\n// Realism limits: a Quest room scan covers at most 10 x 10 m, and a scanned\n// room holds a few dozen detected objects (the office_large capture has 38).\n// createRoom rejects larger rooms and finish() warns above 40 planes and\n// meshes.\n\ntype Vec3 = [number, number, number];\ntype Wall = 'back' | 'front' | 'left' | 'right';\nconst WALLS: Wall[] = ['back', 'front', 'left', 'right'];\nconst MAX_ROOM_SIZE = 10;\nconst MAX_ENTITIES = 40;\n\nconst owned: { dispose(): void }[] = [];\nfunction own<T extends { dispose(): void }>(value: T): T {\n owned.push(value);\n return value;\n}\nonDispose(() => owned.forEach((value) => value.dispose()));\n\nfunction once<T>(make: () => T): () => T {\n let value: T | undefined;\n return () => (value ??= make());\n}\n\n// ------------------------------------------------------------------ noise\n\nfunction hash(x: number, y: number, seed: number) {\n let h =\n Math.imul(x | 0, 374761393) ^\n Math.imul(y | 0, 668265263) ^\n Math.imul(seed | 0, 982451653);\n h = Math.imul(h ^ (h >>> 13), 1274126177);\n return ((h ^ (h >>> 16)) >>> 0) / 4294967295;\n}\n\nconst mod = (a: number, n: number) => ((a % n) + n) % n;\nconst clamp01 = (v: number) => Math.min(1, Math.max(0, v));\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\n\n// Value noise, tileable with integer periods px / py.\nfunction noise(x: number, y: number, seed: number, px: number, py: number) {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const fx = x - ix;\n const fy = y - iy;\n const ux = fx * fx * (3 - 2 * fx);\n const uy = fy * fy * (3 - 2 * fy);\n const x0 = mod(ix, px);\n const x1 = mod(ix + 1, px);\n const y0 = mod(iy, py);\n const y1 = mod(iy + 1, py);\n const a = hash(x0, y0, seed);\n const b = hash(x1, y0, seed);\n const c = hash(x0, y1, seed);\n const d = hash(x1, y1, seed);\n return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy;\n}\n\nfunction fbm(\n x: number,\n y: number,\n seed: number,\n octaves: number,\n px = 1 << 16,\n py = 1 << 16,\n) {\n let sum = 0;\n let amp = 0.5;\n let norm = 0;\n for (let o = 0; o < octaves; o++) {\n sum += amp * noise(x, y, seed + o * 17, px, py);\n norm += amp;\n x *= 2;\n y *= 2;\n px *= 2;\n py *= 2;\n amp *= 0.5;\n }\n return sum / norm;\n}\n\n// --------------------------------------------------------------- textures\n\ntype RGBA = [number, number, number, number?];\n\n// Fills `count` canvases in one pass; `pixel` returns one color per canvas.\n// u, v are in [0, 1) with v = 0 at the bottom (texture convention).\nfunction paint(\n width: number,\n height: number,\n count: number,\n pixel: (u: number, v: number) => RGBA[],\n) {\n const canvases = Array.from({ length: count }, () => {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n });\n const images = canvases.map((canvas) =>\n canvas.getContext('2d')!.createImageData(width, height),\n );\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const colors = pixel((x + 0.5) / width, 1 - (y + 0.5) / height);\n const i = (y * width + x) * 4;\n for (let c = 0; c < count; c++) {\n const [r, g, b, a = 1] = colors[c];\n const data = images[c].data;\n data[i] = clamp01(r) * 255;\n data[i + 1] = clamp01(g) * 255;\n data[i + 2] = clamp01(b) * 255;\n data[i + 3] = clamp01(a) * 255;\n }\n }\n }\n canvases.forEach((canvas, c) =>\n canvas.getContext('2d')!.putImageData(images[c], 0, 0),\n );\n return canvases;\n}\n\n// A repeating texture; geometry UVs are in meters, so `meters` is the tile.\nfunction tiled(\n canvas: HTMLCanvasElement,\n color: boolean,\n metersU: number,\n metersV = metersU,\n) {\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = color ? THREE.SRGBColorSpace : THREE.NoColorSpace;\n tex.wrapS = tex.wrapT = THREE.RepeatWrapping;\n tex.repeat.set(1 / metersU, 1 / metersV);\n tex.anisotropy = 8;\n return tex;\n}\n\n// A texture covering a centered w x h panel (UVs in meters).\nfunction fitted(canvas: HTMLCanvasElement, w: number, h: number) {\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n tex.repeat.set(1 / w, 1 / h);\n tex.offset.set(0.5, 0.5);\n tex.anisotropy = 8;\n return tex;\n}\n\nfunction canvasTexture(canvas: HTMLCanvasElement) {\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n return tex;\n}\n\n// Engineered oak: a 2 m x 4 m tile of 20 cm planks, 1-2 m long.\nconst oakTextures = once(() => {\n const planks = 10;\n const lengths = [2, 4 / 3, 2, 1, 4 / 3, 2, 1, 4 / 3, 2, 4 / 3];\n const shifts = lengths.map((_, i) => hash(i, 3, 7) * 4);\n const [color, rough, bump] = paint(512, 1024, 3, (u, v) => {\n const column = Math.floor(u * planks);\n const across = u * planks - column;\n const along = mod(v * 4 + shifts[column], 4);\n const row = Math.floor(along / lengths[column]);\n const end = along - row * lengths[column];\n const seed = column * 31 + row * 7 + 1;\n const gap =\n Math.min(across, 1 - across) * 0.2 < 0.0012 ||\n Math.min(end, lengths[column] - end) < 0.0015;\n const offset = hash(seed, 1, 2) * 50;\n const warp = fbm(across * 2 + offset, along * 0.8, seed, 3) * 9;\n const grain = 0.5 + 0.5 * Math.sin(across * 26 + warp);\n const fine = fbm(across * 40, along * 2 + offset, seed + 3, 2);\n const tone = 0.94 + (hash(seed, 2, 9) - 0.5) * 0.12;\n const t = tone * (0.9 + 0.07 * grain + 0.06 * fine);\n const shade = gap ? 0.55 : 1;\n const r = gap ? 0.9 : 0.45 + 0.1 * hash(seed, 4, 4);\n const b = gap ? 0 : 0.7 + 0.12 * grain + 0.05 * fine;\n return [\n [0.8 * t * shade, 0.65 * t * shade, 0.48 * t * shade],\n [r, r, r],\n [b, b, b],\n ];\n });\n return {\n map: tiled(color, true, 2, 4),\n roughnessMap: tiled(rough, false, 2, 4),\n bumpMap: tiled(bump, false, 2, 4),\n };\n});\n\n// Fine plaster bump, 1 m tile.\nconst plasterBump = once(() => {\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const b = 0.45 + 0.4 * fbm(u * 16, v * 16, 3, 4, 16, 16);\n return [[b, b, b]];\n });\n return tiled(canvas, false, 1);\n});\n\n// Woven fabric color + bump, 10 cm tile.\nconst fabricTextures = new Map<\n number,\n { map: THREE.Texture; bumpMap: THREE.Texture }\n>();\nfunction fabricTexture(seed: number) {\n let textures = fabricTextures.get(seed);\n if (!textures) {\n const threads = 48;\n const [color, bump] = paint(128, 128, 2, (u, v) => {\n const cell = (Math.floor(u * threads) + Math.floor(v * threads)) % 2;\n const warp = Math.sin(mod(u * threads, 1) * Math.PI);\n const weft = Math.sin(mod(v * threads, 1) * Math.PI);\n const thread = cell ? warp : weft;\n const slub = fbm(u * 6, v * 48, seed, 3, 6, 48);\n const t = 0.86 + 0.08 * thread + 0.1 * slub;\n return [\n [t, t, t],\n [thread, thread, thread],\n ];\n });\n textures = {\n map: tiled(color, true, 0.1),\n bumpMap: tiled(bump, false, 0.1),\n };\n fabricTextures.set(seed, textures);\n }\n return textures;\n}\n\n// Walnut veneer, 1 m tile, grain along U.\nconst walnutTexture = once(() => {\n const [canvas] = paint(512, 512, 1, (u, v) => {\n const warp = fbm(u * 3, v * 8, 11, 4, 3, 8) * 5;\n const ring = 0.5 + 0.5 * Math.sin((v * 90 + warp) * Math.PI);\n const pores = fbm(u * 160, v * 24, 12, 2, 160, 24);\n const t = 0.8 + 0.12 * ring + 0.1 * pores;\n return [[0.33 * t, 0.2 * t, 0.12 * t]];\n });\n return tiled(canvas, true, 1);\n});\n\n// Light oak veneer for furniture, 1 m tile, grain along U.\nconst oakVeneerTexture = once(() => {\n const [canvas] = paint(512, 512, 1, (u, v) => {\n const warp = fbm(u * 2, v * 6, 13, 4, 2, 6) * 6;\n const ring = 0.5 + 0.5 * Math.sin((v * 60 + warp) * Math.PI);\n const pores = fbm(u * 140, v * 20, 14, 2, 140, 20);\n const t = 0.88 + 0.07 * ring + 0.07 * pores;\n return [[0.78 * t, 0.62 * t, 0.44 * t]];\n });\n return tiled(canvas, true, 1);\n});\n\n// Short-pile carpet tiles, 50 cm tile with a faint seam.\nconst carpetTexture = once(() => {\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const fiber =\n (fbm(u * 120, v * 120, 61, 2) - 0.5) * 0.12 +\n (fbm(u * 6, v * 6, 62, 3) - 0.5) * 0.06;\n const seam = Math.min(u, 1 - u, v, 1 - v) < 0.006 ? 0.92 : 1;\n const t = (0.62 + fiber) * seam;\n return [[t, t * 0.97, t * 0.92]];\n });\n return tiled(canvas, true, 0.5);\n});\n\n// Polished concrete, 2 m tile.\nconst concreteTexture = once(() => {\n const [canvas] = paint(512, 512, 1, (u, v) => {\n const cloud = fbm(u * 6, v * 6, 71, 5, 6, 6);\n const speck =\n hash(Math.floor(u * 512), Math.floor(v * 512), 72) > 0.985 ? 0.9 : 1;\n const t = (0.72 + 0.12 * cloud) * speck;\n return [[t, t * 0.98, t * 0.95]];\n });\n return tiled(canvas, true, 2);\n});\n\n// Square glazed tiles with grout; `color` is the tile color.\nconst tileTextures = new Map<string, THREE.Texture>();\nfunction tileTexture(color: string, tile = 0.1) {\n const key = `${color}:${tile}`;\n let tex = tileTextures.get(key);\n if (!tex) {\n const c = new THREE.Color(color);\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const gu = mod(u * 4, 1);\n const gv = mod(v * 4, 1);\n if (Math.min(gu, 1 - gu, gv, 1 - gv) < 0.03) return [[0.86, 0.84, 0.8]];\n const cell = hash(Math.floor(u * 4), Math.floor(v * 4), 81);\n const t = 0.92 + 0.12 * cell + 0.04 * fbm(u * 20, v * 20, 82, 2);\n return [[c.r * t, c.g * t, c.b * t]];\n });\n tex = tiled(canvas, true, tile * 4);\n tileTextures.set(key, tex);\n }\n return tex;\n}\n\n// Cork board, 50 cm tile.\nconst corkTexture = once(() => {\n const [canvas] = paint(256, 256, 1, (u, v) => {\n const grain = fbm(u * 60, v * 60, 91, 3);\n const t = 0.7 + 0.35 * grain;\n return [[0.72 * t, 0.53 * t, 0.36 * t]];\n });\n return tiled(canvas, true, 0.5);\n});\n\n// Rugs: 'lattice' (ivory field, charcoal lattice), 'border' (plain field with\n// a band), 'stripe' (woven stripes) or 'plain'.\ntype RugStyle = 'lattice' | 'border' | 'stripe' | 'plain';\nfunction rugCanvas(\n w: number,\n h: number,\n style: RugStyle,\n field: string,\n accent: string,\n) {\n const f = new THREE.Color(field);\n const a = new THREE.Color(accent);\n const [canvas] = paint(512, Math.round((512 * h) / w), 1, (u, v) => {\n const x = u * w;\n const y = v * h;\n const fiber =\n (fbm(x * 140, y * 140, 21, 2) - 0.5) * 0.14 +\n (fbm(x * 3, y * 3, 22, 3) - 0.5) * 0.08;\n const border = Math.min(x, w - x, y, h - y);\n let accentHere = false;\n if (style === 'lattice') {\n const dx = Math.abs(mod(x / 0.32, 1) - 0.5);\n const dy = Math.abs(mod(y / 0.32, 1) - 0.5);\n accentHere =\n (border > 0.1 && border < 0.13) ||\n (border > 0.2 && Math.abs(dx + dy - 0.5) < 0.025);\n } else if (style === 'border') {\n accentHere = border > 0.08 && border < 0.16;\n } else if (style === 'stripe') {\n accentHere = mod(y / 0.24, 1) < 0.18;\n }\n const c = accentHere ? a : f;\n const t = 1 + fiber;\n return [[c.r * t, c.g * t, c.b * t]];\n });\n return canvas;\n}\n\n// Abstract painting with soft overlapping discs and a line.\nfunction paintingTexture(seed: number, palette: string[], aspect: number) {\n const width = 512;\n const height = Math.round(width / aspect);\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.fillStyle = '#e9e2d4';\n ctx.fillRect(0, 0, width, height);\n ctx.filter = 'blur(1.2px)';\n for (let i = 0; i < 4; i++) {\n ctx.globalAlpha = 0.88;\n ctx.fillStyle = palette[i % palette.length];\n ctx.beginPath();\n const r = (0.14 + hash(i, 1, seed) * 0.16) * Math.min(width, height) * 1.4;\n ctx.arc(\n (0.2 + hash(i, 2, seed) * 0.6) * width,\n (0.25 + hash(i, 3, seed) * 0.5) * height,\n r,\n 0,\n Math.PI * 2,\n );\n ctx.fill();\n }\n ctx.globalAlpha = 0.85;\n ctx.strokeStyle = '#1d1d1d';\n ctx.lineWidth = 4;\n ctx.beginPath();\n ctx.moveTo(width * 0.12, height * 0.8);\n ctx.bezierCurveTo(\n width * 0.35,\n height * 0.2,\n width * 0.65,\n height,\n width * 0.9,\n height * 0.2,\n );\n ctx.stroke();\n return canvasTexture(canvas);\n}\n\n// Line-drawn botanical print on paper.\nfunction botanicalTexture(seed: number) {\n const canvas = document.createElement('canvas');\n canvas.width = 400;\n canvas.height = 600;\n const ctx = canvas.getContext('2d')!;\n ctx.fillStyle = '#efe9de';\n ctx.fillRect(0, 0, 400, 600);\n ctx.strokeStyle = '#3d4a3a';\n ctx.lineWidth = 3;\n ctx.lineCap = 'round';\n ctx.beginPath();\n ctx.moveTo(200, 560);\n ctx.bezierCurveTo(190, 420, 230, 260, 205, 60);\n ctx.stroke();\n for (let i = 0; i < 7; i++) {\n const y = 500 - i * 62;\n const side = (i + seed) % 2 ? 1 : -1;\n const x = 200 + Math.sin(i + seed) * 8;\n ctx.beginPath();\n ctx.moveTo(x, y);\n ctx.quadraticCurveTo(x + side * 90, y - 70, x + side * 120, y - 20);\n ctx.quadraticCurveTo(x + side * 70, y + 10, x, y);\n ctx.stroke();\n }\n return canvasTexture(canvas);\n}\n\n// Minimal landscape: layered hills under a sun disc.\nfunction landscapeTexture(seed: number, aspect: number) {\n const width = 512;\n const height = Math.round(width / aspect);\n const hills = ['#c9b79c', '#9aa58a', '#6f7f62', '#556349'];\n const [canvas] = paint(width, height, 1, (u, v) => {\n const sun = Math.hypot(u - 0.62, (v - 0.72) / aspect) < 0.07;\n let c = new THREE.Color(sun ? '#c96f3e' : '#efe6d6');\n for (let i = 0; i < hills.length; i++) {\n const ridge =\n 0.55 -\n i * 0.12 +\n 0.06 * Math.sin(u * (3 + i) + seed + i * 2) +\n 0.02 * fbm(u * 8, i, seed + i, 2);\n if (v < ridge) c = new THREE.Color(hills[i]);\n }\n return [[c.r, c.g, c.b]];\n });\n return canvasTexture(canvas);\n}\n\n// Bright, hazy view out of a window: sky, a tree line, a hedge.\nconst outsideTexture = once(() => {\n const [canvas] = paint(1024, 512, 1, (u, v) => {\n const sky: Vec3 = [\n mix(0.97, 0.9, v),\n mix(0.98, 0.94, v),\n mix(0.99, 0.98, v),\n ];\n const ridge =\n 0.33 + 0.05 * fbm(u * 4, 0, 31, 3) + 0.02 * fbm(u * 40, v * 20, 32, 2);\n const foliage = clamp01((ridge - v) / 0.04);\n const leaf = fbm(u * 60, v * 40, 33, 4);\n const t = (0.45 + 0.6 * leaf) * mix(0.7, 1, v / 0.35);\n const haze = 0.2 * (v / 0.35);\n const green = [\n mix(0.42 * t, sky[0], haze),\n mix(0.52 * t, sky[1], haze),\n mix(0.36 * t, sky[2], haze),\n ];\n return [\n [\n mix(sky[0], green[0], foliage),\n mix(sky[1], green[1], foliage),\n mix(sky[2], green[2], foliage),\n ],\n ];\n });\n return canvasTexture(canvas);\n});\n\n// Softly lit corridor seen through interior glazing.\nconst corridorTexture = once(() => {\n const [canvas] = paint(512, 256, 1, (u, v) => {\n const wall = 0.8 + 0.06 * fbm(u * 4, v * 4, 101, 3);\n const floor = v < 0.22 ? 0.55 + 0.05 * fbm(u * 20, v * 20, 102, 2) : 0;\n const door =\n mod(u * 3, 1) > 0.42 && mod(u * 3, 1) < 0.58 && v < 0.75 && v >= 0.22;\n const light =\n Math.exp(-Math.pow((mod(u * 3, 1) - 0.5) / 0.25, 2)) * 0.08 * v;\n if (floor) return [[floor * 0.9, floor * 0.8, floor * 0.68]];\n if (door) return [[0.62, 0.5, 0.38]];\n const t = wall + light;\n return [[t, t * 0.98, t * 0.94]];\n });\n return canvasTexture(canvas);\n});\n\n// Broad leaf with veins; alpha cut-out.\nconst leafTextures = once(() => {\n const [color, bump] = paint(256, 256, 2, (u, v) => {\n const x = (u - 0.5) * 2;\n const waist = 1 - 0.12 * Math.exp(-Math.pow((v - 0.42) / 0.12, 2));\n const width =\n 0.96 *\n Math.pow(Math.sin(Math.PI * Math.pow(Math.min(v, 0.999), 0.5)), 0.6) *\n (0.5 + 0.5 * v) *\n waist;\n const inside = Math.abs(x) < width ? 1 : 0;\n const midrib = Math.abs(x) < 0.025 ? 1 : 0;\n const vein =\n Math.abs(mod(v * 5 - Math.abs(x) * 1.3, 1) - 0.5) < 0.03 ? 1 : 0;\n const shade = 0.82 + 0.18 * fbm(u * 6, v * 6, 41, 3);\n const edge =\n 1 - 0.2 * clamp01((Math.abs(x) / Math.max(width, 0.01) - 0.8) * 5);\n const light = (midrib ? 1.5 : vein ? 1.18 : 1) * edge;\n const height = midrib || vein ? 0.35 : 0.6;\n return [\n [\n 0.19 * shade * light,\n 0.31 * shade * light,\n 0.12 * shade * light,\n inside,\n ],\n [height, height, height],\n ];\n });\n const map = canvasTexture(color);\n return { map, bumpMap: own(new THREE.CanvasTexture(bump)) };\n});\n\n// ---------------------------------------------------------------- geometry\n\n// Scales BoxGeometry UVs (0..1 per face) to meters so tiled textures keep\n// their real-world size on any box.\nfunction meterUVs(\n geometry: THREE.BoxGeometry,\n w: number,\n h: number,\n d: number,\n) {\n const uv = geometry.getAttribute('uv');\n const perFace = uv.count / 6;\n const sizes = [\n [d, h],\n [d, h],\n [w, d],\n [w, d],\n [w, h],\n [w, h],\n ];\n for (let i = 0; i < uv.count; i++) {\n const [su, sv] = sizes[Math.floor(i / perFace)];\n uv.setXY(i, uv.getX(i) * su, uv.getY(i) * sv);\n }\n return geometry;\n}\n\n// Box with rounded edges; `puff` bulges the top/bottom faces like a cushion.\nfunction roundedBox(\n w: number,\n h: number,\n d: number,\n r: number,\n puff = 0,\n segments = 4,\n) {\n const geometry = own(\n meterUVs(\n new THREE.BoxGeometry(w, h, d, segments, segments, segments),\n w,\n h,\n d,\n ),\n );\n const position = geometry.getAttribute('position');\n const normal = geometry.getAttribute('normal');\n const p = new THREE.Vector3();\n const inner = new THREE.Vector3();\n const n = new THREE.Vector3();\n const hx = w / 2 - r;\n const hy = h / 2 - r;\n const hz = d / 2 - r;\n for (let i = 0; i < position.count; i++) {\n p.fromBufferAttribute(position, i);\n inner.set(\n THREE.MathUtils.clamp(p.x, -hx, hx),\n THREE.MathUtils.clamp(p.y, -hy, hy),\n THREE.MathUtils.clamp(p.z, -hz, hz),\n );\n n.subVectors(p, inner).normalize();\n p.copy(inner).addScaledVector(n, r);\n if (puff) {\n const fx = Math.max(0, 1 - Math.pow(p.x / (w / 2), 2));\n const fz = Math.max(0, 1 - Math.pow(p.z / (d / 2), 2));\n p.y += Math.sign(p.y) * puff * Math.sqrt(fx * fz);\n }\n position.setXYZ(i, p.x, p.y, p.z);\n normal.setXYZ(i, n.x, n.y, n.z);\n }\n if (puff) geometry.computeVertexNormals();\n return geometry;\n}\n\n// Rectangle in the XY plane, UVs in meters, with optional rectangular holes.\nfunction panel(\n w: number,\n h: number,\n holes: [number, number, number, number][] = [],\n) {\n const shape = new THREE.Shape();\n shape.moveTo(-w / 2, -h / 2);\n shape.lineTo(w / 2, -h / 2);\n shape.lineTo(w / 2, h / 2);\n shape.lineTo(-w / 2, h / 2);\n for (const [x0, y0, x1, y1] of holes) {\n const hole = new THREE.Path();\n hole.moveTo(x0, y0);\n hole.lineTo(x0, y1);\n hole.lineTo(x1, y1);\n hole.lineTo(x1, y0);\n shape.holes.push(hole);\n }\n return own(new THREE.ShapeGeometry(shape));\n}\n\nconst unitPlane = own(new THREE.PlaneGeometry(1, 1));\n\n// --------------------------------------------------------------- materials\n\nconst standard = (params: THREE.MeshStandardMaterialParameters) =>\n own(new THREE.MeshStandardMaterial(params));\n\nconst mats = {\n trim: once(() => standard({ color: '#f3f1ec', roughness: 0.5 })),\n walnut: once(() => standard({ map: walnutTexture(), roughness: 0.5 })),\n darkWalnut: once(() =>\n standard({ map: walnutTexture(), color: '#8a7a70', roughness: 0.55 }),\n ),\n oak: once(() => standard({ map: oakVeneerTexture(), roughness: 0.55 })),\n blackMetal: once(() =>\n standard({ color: '#1a1a1a', roughness: 0.4, metalness: 0.85 }),\n ),\n steel: once(() =>\n standard({ color: '#b8b8b4', roughness: 0.3, metalness: 1 }),\n ),\n brass: once(() =>\n standard({ color: '#c6a062', roughness: 0.28, metalness: 1 }),\n ),\n ceramic: once(() => standard({ color: '#ebe6dc', roughness: 0.3 })),\n stoneware: once(() => standard({ color: '#4a4844', roughness: 0.55 })),\n terracotta: once(() => standard({ color: '#a65f40', roughness: 0.85 })),\n soil: once(() => standard({ color: '#2a2019', roughness: 1 })),\n white: once(() => standard({ color: '#f2efe9', roughness: 0.6 })),\n charcoal: once(() => standard({ color: '#2b2b2d', roughness: 0.75 })),\n stone: once(() => standard({ color: '#e4e0d8', roughness: 0.35 })),\n book: once(() => standard({ roughness: 0.8 })),\n pot: once(() => standard({ color: '#e4ded3', roughness: 0.85 })),\n glass: once(() =>\n standard({\n color: '#e6f0f5',\n roughness: 0.03,\n transparent: true,\n opacity: 0.12,\n }),\n ),\n hidden: once(() => own(new THREE.MeshBasicMaterial({ visible: false }))),\n bulb: once(() => {\n const material = own(new THREE.MeshBasicMaterial({ color: '#fff1dc' }));\n material.color.setScalar(5);\n return material;\n }),\n lampShade: once(() =>\n standard({\n color: '#efe4cf',\n roughness: 1,\n side: THREE.DoubleSide,\n emissive: '#ffc985',\n emissiveIntensity: 1.1,\n }),\n ),\n linenShade: once(() =>\n standard({ color: '#d8d0c2', roughness: 0.9, side: THREE.DoubleSide }),\n ),\n screen: once(() =>\n customizeEnvironment(\n standard({\n color: '#050506',\n roughness: 0.05,\n metalness: 0.2,\n envMapIntensity: 0.3,\n }),\n { boxProjected: true },\n ),\n ),\n mirror: once(() =>\n customizeEnvironment(\n standard({ color: '#d8dcdc', roughness: 0.15, metalness: 1 }),\n { boxProjected: true },\n ),\n ),\n leaf: once(() =>\n standard({\n ...leafTextures(),\n bumpScale: 0.6,\n alphaTest: 0.5,\n side: THREE.DoubleSide,\n roughness: 0.45,\n envMapIntensity: 0.12,\n }),\n ),\n bark: once(() => standard({ color: '#5b4835', roughness: 0.9 })),\n};\n\nconst coloredMaterials = new Map<string, THREE.MeshStandardMaterial>();\n// A plain material by color, shared per (color, roughness, metalness).\nfunction paintMaterial(color: string, roughness = 0.7, metalness = 0) {\n const key = `${color}:${roughness}:${metalness}`;\n let material = coloredMaterials.get(key);\n if (!material) {\n material = standard({ color, roughness, metalness });\n coloredMaterials.set(key, material);\n }\n return material;\n}\n\nconst fabricMaterials = new Map<string, THREE.MeshStandardMaterial>();\n// Woven upholstery in `color`.\nfunction fabricMaterial(color: string, seed = 51) {\n const key = `${color}:${seed}`;\n let material = fabricMaterials.get(key);\n if (!material) {\n material = standard({\n color,\n roughness: 0.95,\n ...fabricTexture(seed),\n bumpScale: 0.5,\n });\n fabricMaterials.set(key, material);\n }\n return material;\n}\n\n// --------------------------------------------------------------- the room\n\ntype Occluder = { min: THREE.Vector3; max: THREE.Vector3; strength: number };\n\ninterface WindowSpec {\n wall: Wall;\n at: number;\n width: number;\n sill?: number;\n head?: number;\n // 'outside' (default) lets in daylight and sun; 'corridor' is interior\n // glazing onto a softly lit corridor, with a frosted band.\n view?: 'outside' | 'corridor';\n sheers?: boolean;\n mullions?: number;\n // Fraction (0..1) a roller blind is lowered.\n blind?: number;\n}\n\ninterface DoorSpec {\n wall: Wall;\n at: number;\n width?: number;\n height?: number;\n}\n\ninterface RoomSpec {\n name: string;\n width: number;\n depth: number;\n height?: number;\n // Back wall z; the default puts the origin 60% of the way to the front.\n z0?: number;\n windows: WindowSpec[];\n doors?: DoorSpec[];\n floor?: 'oak' | 'carpet' | 'concrete';\n wall?: string;\n // Sun through one outside window (`window` indexes the outside windows\n // only, skipping corridor glazing): elevation and azimuth in degrees\n // (azimuth turns it along the wall).\n sun?: { window?: number; elevation?: number; azimuth?: number };\n downlights?: [number, number][];\n texelsPerMeter?: number;\n // A robot vacuum driving an elliptical loop: visible, hit-testable and in\n // depth, but not a tracked plane/mesh.\n robot?: {\n center: [number, number];\n radius: [number, number];\n speed?: number;\n };\n}\n\ninterface Win {\n wall: Wall;\n at: number;\n width: number;\n sill: number;\n head: number;\n exterior: boolean;\n light: number;\n normal: THREE.Vector3;\n u: THREE.Vector3;\n center: THREE.Vector3;\n samples: THREE.Vector3[];\n sampleArea: number;\n spec: WindowSpec;\n}\n\ninterface RoomState {\n spec: RoomSpec;\n x0: number;\n x1: number;\n z0: number;\n z1: number;\n h: number;\n windows: Win[];\n sunDirection: THREE.Vector3;\n sunTarget: THREE.Vector3;\n hasSun: boolean;\n patchSamples: THREE.Vector3[];\n patchSampleArea: number[];\n bounceScale: number;\n probe: THREE.Vector3;\n occluders: Occluder[];\n lit: { object: THREE.Mesh; w: number; h: number }[];\n wallColor: string;\n}\n\nlet R: RoomState;\n// Baked lightmap values are irradiance / LIGHTMAP_INTENSITY.\nconst LIGHTMAP_INTENSITY = 2.4;\nconst SUN_INTENSITY = 22;\n\nfunction wallInfo(wall: Wall) {\n const { x0, x1, z0, z1, h } = R;\n const zc = (z0 + z1) / 2;\n const V = THREE.Vector3;\n switch (wall) {\n case 'back':\n return {\n normal: new V(0, 0, 1),\n u: new V(1, 0, 0),\n rotationY: 0,\n length: x1 - x0,\n center: new V(0, h / 2, z0),\n point: (at: number, y: number) => new V(at, y, z0),\n };\n case 'front':\n return {\n normal: new V(0, 0, -1),\n u: new V(-1, 0, 0),\n rotationY: Math.PI,\n length: x1 - x0,\n center: new V(0, h / 2, z1),\n point: (at: number, y: number) => new V(at, y, z1),\n };\n case 'left':\n return {\n normal: new V(1, 0, 0),\n u: new V(0, 0, -1),\n rotationY: Math.PI / 2,\n length: z1 - z0,\n center: new V(x0, h / 2, zc),\n point: (at: number, y: number) => new V(x0, y, at),\n };\n case 'right':\n return {\n normal: new V(-1, 0, 0),\n u: new V(0, 0, 1),\n rotationY: -Math.PI / 2,\n length: z1 - z0,\n center: new V(x1, h / 2, zc),\n point: (at: number, y: number) => new V(x1, y, at),\n };\n }\n}\n\n// Windows (with their sheers and rods) and doors must fit their wall and not\n// overlap, or the wall holes and window geometry break.\nfunction checkOpenings(spec: RoomSpec, h: number, z0: number) {\n // `owner` is the opening a span belongs to (a window and its sheers).\n const spans: {\n wall: Wall;\n from: number;\n to: number;\n name: string;\n owner: string;\n }[] = [];\n const add = (\n name: string,\n owner: string,\n wall: Wall,\n at: number,\n halfWidth: number,\n top: number,\n ) => {\n const [min, max] =\n wall === 'back' || wall === 'front'\n ? [-spec.width / 2, spec.width / 2]\n : [z0, z0 + spec.depth];\n if (at - halfWidth < min || at + halfWidth > max || top > h) {\n throw new Error(`${spec.name}: ${name} does not fit the ${wall} wall`);\n }\n spans.push({ wall, from: at - halfWidth, to: at + halfWidth, name, owner });\n };\n spec.windows.forEach((w, i) => {\n const sill = w.sill ?? 0.55;\n const head = w.head ?? Math.min(h - 0.35, 2.35);\n if (sill < 0 || sill >= head) {\n throw new Error(`${spec.name}: window ${i} needs 0 <= sill < head`);\n }\n add(`window ${i}`, `window ${i}`, w.wall, w.at, w.width / 2, head);\n const sheers = (w.view ?? 'outside') === 'outside' && !w.blind;\n if (sheers && w.sheers !== false) {\n add(\n `window ${i}'s sheers`,\n `window ${i}`,\n w.wall,\n w.at,\n w.width / 2 + 0.53,\n head + 0.17,\n );\n }\n });\n (spec.doors ?? []).forEach((d, i) =>\n add(\n `door ${i}`,\n `door ${i}`,\n d.wall,\n d.at,\n (d.width ?? 0.86) / 2,\n d.height ?? 2.06,\n ),\n );\n for (const a of spans) {\n for (const b of spans) {\n if (a.owner === b.owner || a.wall !== b.wall) continue;\n if (a.from < b.to && b.from < a.to) {\n throw new Error(`${spec.name}: ${a.name} overlaps ${b.name}`);\n }\n }\n }\n}\n\nfunction createRoom(spec: RoomSpec) {\n if (spec.width > MAX_ROOM_SIZE || spec.depth > MAX_ROOM_SIZE) {\n throw new Error(\n `${spec.name}: ${spec.width} x ${spec.depth} m exceeds the ${MAX_ROOM_SIZE} x ${MAX_ROOM_SIZE} m a Quest room scan supports`,\n );\n }\n const h = spec.height ?? 2.7;\n const z0 = spec.z0 ?? -spec.depth * 0.6;\n checkOpenings(spec, h, z0);\n R = {\n spec,\n x0: -spec.width / 2,\n x1: spec.width / 2,\n z0,\n z1: z0 + spec.depth,\n h,\n windows: [],\n sunDirection: new THREE.Vector3(0, -1, 0),\n sunTarget: new THREE.Vector3(),\n hasSun: false,\n patchSamples: [],\n patchSampleArea: [],\n bounceScale: 1,\n probe: new THREE.Vector3(0, 1.3, z0 + spec.depth / 2),\n occluders: [],\n lit: [],\n wallColor: spec.wall ?? '#eeeae3',\n };\n\n for (const w of spec.windows) {\n const info = wallInfo(w.wall);\n const sill = w.sill ?? 0.55;\n const head = w.head ?? Math.min(h - 0.35, 2.35);\n const exterior = (w.view ?? 'outside') === 'outside';\n const center = info.point(w.at, (sill + head) / 2);\n const samples: THREE.Vector3[] = [];\n const columns = Math.max(2, Math.round(w.width / 0.45));\n for (let i = 0; i < columns; i++) {\n for (let j = 0; j < 3; j++) {\n const along = -w.width / 2 + ((i + 0.5) / columns) * w.width;\n samples.push(\n info\n .point(w.at, sill + ((j + 0.5) / 3) * (head - sill))\n .addScaledVector(info.u, along),\n );\n }\n }\n R.windows.push({\n wall: w.wall,\n at: w.at,\n width: w.width,\n sill,\n head,\n exterior,\n light: exterior ? 1 : 0.3,\n normal: info.normal,\n u: info.u,\n center,\n samples,\n sampleArea: (w.width * (head - sill)) / samples.length,\n spec: w,\n });\n }\n\n // Sun through an outside window, landing on the floor.\n const outside = R.windows.filter((w) => w.exterior);\n const sunWindow = outside[spec.sun?.window ?? 0];\n if (sunWindow) {\n const elevation = THREE.MathUtils.degToRad(spec.sun?.elevation ?? 39);\n const azimuth = THREE.MathUtils.degToRad(spec.sun?.azimuth ?? 15);\n R.sunDirection = sunWindow.normal\n .clone()\n .multiplyScalar(Math.cos(elevation) * Math.cos(azimuth))\n .addScaledVector(sunWindow.u, Math.cos(elevation) * Math.sin(azimuth))\n .add(new THREE.Vector3(0, -Math.sin(elevation), 0))\n .normalize();\n R.sunTarget = sunWindow.center\n .clone()\n .addScaledVector(R.sunDirection, -sunWindow.center.y / R.sunDirection.y);\n R.hasSun = true;\n const d = R.sunDirection;\n for (const w of outside) {\n const facing = d.dot(w.normal);\n if (facing <= 0.05) continue;\n for (const s of w.samples) {\n const f = s.clone().addScaledVector(d, -s.y / d.y);\n if (f.x > R.x0 && f.x < R.x1 && f.z > R.z0 && f.z < R.z1) {\n R.patchSamples.push(f);\n R.patchSampleArea.push((w.sampleArea * facing) / -d.y);\n }\n }\n }\n }\n\n // Indirect light scales with how much window the room has for its size,\n // relative to the reference living room (a 2.1 x 1.8 m window, 116 m2).\n const surface =\n 2 * spec.width * spec.depth + 2 * (spec.width + spec.depth) * h;\n const opening = R.windows.reduce(\n (sum, w) => sum + w.width * (w.head - w.sill) * w.light,\n 0,\n );\n R.bounceScale = THREE.MathUtils.clamp(opening / surface / 0.0325, 0.6, 1.5);\n\n // A group on a wall at height y, `out` meters into the room, facing in.\n const onWall = (wall: Wall, at: number, y = 0, out = 0) => {\n const info = wallInfo(wall);\n const p = info.point(at, y).addScaledVector(info.normal, out);\n return group(p.x, p.y, p.z, info.rotationY);\n };\n\n return {\n bounds: { x0: R.x0, x1: R.x1, z0: R.z0, z1: R.z1, height: h },\n // A group at floor position (x, z), turned by rotationY.\n place(x: number, z: number, rotationY = 0, y = 0) {\n return group(x, y, z, rotationY);\n },\n onWall,\n // A group for furniture of the given depth standing against a wall.\n against(wall: Wall, at: number, depth: number, gap = 0.02) {\n return onWall(wall, at, 0, depth / 2 + gap);\n },\n finish,\n };\n}\n\n// --------------------------------------------------------------- helpers\n\nfunction mesh(\n geometry: THREE.BufferGeometry,\n material: THREE.Material,\n [x, y, z]: Vec3,\n parent: THREE.Object3D = scene,\n { cast = true, receive = true } = {},\n) {\n const object = new THREE.Mesh(geometry, material);\n object.position.set(x, y, z);\n object.castShadow = cast;\n object.receiveShadow = receive;\n parent.add(object);\n return object;\n}\n\nfunction box(\n [w, h, d]: Vec3,\n material: THREE.Material,\n position: Vec3,\n parent: THREE.Object3D = scene,\n) {\n return mesh(\n own(meterUVs(new THREE.BoxGeometry(w, h, d), w, h, d)),\n material,\n position,\n parent,\n );\n}\n\nfunction cylinder(\n radiusTop: number,\n radiusBottom: number,\n height: number,\n material: THREE.Material,\n position: Vec3,\n parent: THREE.Object3D,\n segments = 24,\n) {\n return mesh(\n own(new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments)),\n material,\n position,\n parent,\n );\n}\n\nfunction group(\n x: number,\n y: number,\n z: number,\n rotationY = 0,\n parent: THREE.Object3D = scene,\n) {\n const object = new THREE.Group();\n object.position.set(x, y, z);\n object.rotation.y = rotationY;\n parent.add(object);\n return object;\n}\n\n// Invisible furniture volume, reported as an XRMesh and used as an occluder\n// for the baked lighting.\nfunction volume(\n label: string,\n [w, h, d]: Vec3,\n position: Vec3,\n parent: THREE.Object3D,\n strength = 0.7,\n) {\n const object = mesh(\n own(new THREE.BoxGeometry(w, h, d)),\n mats.hidden(),\n position,\n parent,\n { cast: false, receive: false },\n );\n object.userData.xrMesh = label;\n object.updateWorldMatrix(true, false);\n const bounds = new THREE.Box3().setFromObject(object);\n R.occluders.push({ min: bounds.min, max: bounds.max, strength });\n return object;\n}\n\n// Like volume(), but only occludes the baked lighting: nothing is added to\n// the scene or reported.\nfunction occluder(\n _label: string,\n [w, h, d]: Vec3,\n [x, y, z]: Vec3,\n parent: THREE.Object3D,\n strength = 0.7,\n) {\n parent.updateWorldMatrix(true, false);\n const bounds = new THREE.Box3(\n new THREE.Vector3(x - w / 2, y - h / 2, z - d / 2),\n new THREE.Vector3(x + w / 2, y + h / 2, z + d / 2),\n ).applyMatrix4(parent.matrixWorld);\n R.occluders.push({ min: bounds.min, max: bounds.max, strength });\n}\n\n// Registers a flat mesh (UVs = local XY in meters over a centered w x h\n// rectangle) for a baked lightmap. Its material must not be shared.\nfunction litSurface(object: THREE.Mesh, w: number, h: number) {\n R.lit.push({ object, w, h });\n return object;\n}\n\n// --------------------------------------------------------- baked lighting\n\nconst toSample = new THREE.Vector3();\nconst closest = new THREE.Vector3();\nconst center = new THREE.Vector3();\n\n// True if the segment a -> b passes through the box (slab test).\nfunction blocks(a: THREE.Vector3, b: THREE.Vector3, o: Occluder) {\n let t0 = 0.0001;\n let t1 = 0.9999;\n for (const axis of ['x', 'y', 'z'] as const) {\n const delta = b[axis] - a[axis];\n if (Math.abs(delta) < 1e-9) {\n if (a[axis] < o.min[axis] || a[axis] > o.max[axis]) return false;\n continue;\n }\n let near = (o.min[axis] - a[axis]) / delta;\n let far = (o.max[axis] - a[axis]) / delta;\n if (near > far) [near, far] = [far, near];\n t0 = Math.max(t0, near);\n t1 = Math.min(t1, far);\n if (t0 > t1) return false;\n }\n return true;\n}\n\nconst inside = (p: THREE.Vector3, o: Occluder) =>\n p.x > o.min.x - 0.02 &&\n p.x < o.max.x + 0.02 &&\n p.y > o.min.y - 0.02 &&\n p.y < o.max.y + 0.02 &&\n p.z > o.min.z - 0.02 &&\n p.z < o.max.z + 0.02;\n\n// Ambient occlusion from room corners and nearby furniture.\nfunction occlusion(p: THREE.Vector3, n: THREE.Vector3, active: Occluder[]) {\n const planes: [THREE.Vector3, number][] = [\n [new THREE.Vector3(1, 0, 0), -R.x0],\n [new THREE.Vector3(-1, 0, 0), R.x1],\n [new THREE.Vector3(0, 1, 0), 0],\n [new THREE.Vector3(0, -1, 0), R.h],\n [new THREE.Vector3(0, 0, 1), -R.z0],\n [new THREE.Vector3(0, 0, -1), R.z1],\n ];\n let ao = 1;\n for (const [normal, d] of planes) {\n if (Math.abs(normal.dot(n)) > 0.5) continue;\n const distance = Math.max(0, normal.dot(p) + d);\n ao *=\n (1 - 0.45 * Math.exp(-distance / 0.3)) *\n (1 - 0.2 * Math.exp(-distance / 0.04));\n }\n for (const o of active) {\n center.addVectors(o.min, o.max).multiplyScalar(0.5);\n if (n.dot(toSample.subVectors(center, p)) < 0) continue;\n closest.copy(p).clamp(o.min, o.max);\n const distance = closest.distanceTo(p);\n ao *=\n (1 - o.strength * Math.exp(-distance / 0.25)) *\n (1 - 0.5 * Math.exp(-distance / 0.04));\n }\n return ao;\n}\n\n// Diffuse irradiance (relative units) at p with normal n: skylight through\n// the windows (area lights shadowed by furniture), bounce from the sun patch\n// and a warm multi-bounce ambient. `self` ignores the volume containing p.\nfunction irradiance(\n p: THREE.Vector3,\n n: THREE.Vector3,\n self = false,\n): [number, number, number] {\n const active = self ? R.occluders.filter((o) => !inside(p, o)) : R.occluders;\n let sky = 0;\n for (const w of R.windows) {\n for (const s of w.samples) {\n toSample.subVectors(s, p);\n const d2 = Math.max(toSample.lengthSq(), 0.05);\n toSample.normalize();\n const cosP = n.dot(toSample);\n const cosW = -w.normal.dot(toSample);\n if (cosP <= 0 || cosW <= 0) continue;\n if (active.some((o) => blocks(p, s, o))) continue;\n sky += (w.light * cosP * cosW * w.sampleArea) / (Math.PI * d2);\n }\n }\n let patch = 0;\n for (let i = 0; i < R.patchSamples.length; i++) {\n toSample.subVectors(R.patchSamples[i], p);\n const d2 = Math.max(toSample.lengthSq(), 0.1);\n toSample.normalize();\n const cosP = n.dot(toSample);\n const cosE = -toSample.y;\n if (cosP > 0 && cosE > 0)\n patch += (cosP * cosE * R.patchSampleArea[i]) / (Math.PI * d2);\n }\n const ao = occlusion(p, n, active);\n const bounce =\n ((1.2 * R.bounceScale) / LIGHTMAP_INTENSITY) * ao * (n.y < -0.5 ? 0.7 : 1);\n const direct = sky * (0.6 + 0.4 * ao) * 1.6;\n // Floor exitance in the patch: sun x cos(elevation) x albedo (0.45).\n const warm =\n ((SUN_INTENSITY * -R.sunDirection.y * 0.45) / LIGHTMAP_INTENSITY) *\n patch *\n (Math.abs(n.y) < 0.5 && p.y < R.h / 2 ? 1.25 : 1);\n return [\n bounce * 1.0 + direct * 0.93 + warm,\n bounce * 0.9 + direct * 0.95 + warm * 0.85,\n bounce * 0.78 + direct * 1.0 + warm * 0.66,\n ];\n}\n\n// Bakes a half-float lightmap for a registered lit surface.\nfunction bakeLightmap(object: THREE.Object3D, w: number, h: number) {\n object.updateWorldMatrix(true, false);\n // Keep textures modest in large rooms.\n const texelsPerMeter = Math.min(\n R.spec.texelsPerMeter ?? 24,\n 256 / Math.max(w, h),\n );\n const width = Math.max(8, Math.round(w * texelsPerMeter));\n const height = Math.max(8, Math.round(h * texelsPerMeter));\n const data = new Uint16Array(width * height * 4);\n const normal = new THREE.Vector3(0, 0, 1).transformDirection(\n object.matrixWorld,\n );\n const p = new THREE.Vector3();\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n p.set(((x + 0.5) / width - 0.5) * w, ((y + 0.5) / height - 0.5) * h, 0);\n p.applyMatrix4(object.matrixWorld);\n const [r, g, b] = irradiance(p, normal);\n const i = (y * width + x) * 4;\n data[i] = THREE.DataUtils.toHalfFloat(r);\n data[i + 1] = THREE.DataUtils.toHalfFloat(g);\n data[i + 2] = THREE.DataUtils.toHalfFloat(b);\n data[i + 3] = THREE.DataUtils.toHalfFloat(1);\n }\n }\n const tex = own(\n new THREE.DataTexture(\n data,\n width,\n height,\n THREE.RGBAFormat,\n THREE.HalfFloatType,\n ),\n );\n tex.magFilter = THREE.LinearFilter;\n tex.minFilter = THREE.LinearFilter;\n tex.repeat.set(1 / w, 1 / h);\n tex.offset.set(0.5, 0.5);\n tex.needsUpdate = true;\n return tex;\n}\n\n// Environment shader tweaks:\n// - boxProjected: the probe is parallax-corrected against the room box, so\n// the window reflects where it actually is.\n// - specularOnly: lightmapped surfaces already have their diffuse light, so\n// they only take reflections from the probe.\nfunction customizeEnvironment(\n material: THREE.MeshStandardMaterial,\n { boxProjected = false, specularOnly = false },\n) {\n let chunk = THREE.ShaderChunk.envmap_physical_pars_fragment;\n if (boxProjected) {\n // The world-space reflection line: `inverseTransformDirection` in current\n // three.js, `transformDirectionByInverseViewMatrix` in older versions.\n const patched = chunk.replace(\n /reflectVec = (?:inverseTransformDirection|transformDirectionByInverseViewMatrix)\\( reflectVec, viewMatrix \\);/,\n (line) => `${line}\n vec3 boxHit = mix( boxMin, boxMax, step( 0.0, reflectVec ) );\n vec3 boxT = ( boxHit - vBoxWorldPosition ) / reflectVec;\n float boxDistance = min( min( boxT.x, boxT.y ), boxT.z );\n reflectVec = normalize( vBoxWorldPosition + reflectVec * boxDistance - probePosition );`,\n );\n if (patched === chunk) {\n console.warn(\n 'Box-projected reflections are not supported by this three.js version',\n );\n }\n chunk = patched;\n }\n if (specularOnly) {\n chunk = chunk.replace(\n 'return PI * envMapColor.rgb * envMapIntensity;',\n 'return vec3( 0.0 );',\n );\n }\n material.onBeforeCompile = (shader) => {\n shader.uniforms.boxMin = { value: new THREE.Vector3(R.x0, 0, R.z0) };\n shader.uniforms.boxMax = { value: new THREE.Vector3(R.x1, R.h, R.z1) };\n shader.uniforms.probePosition = { value: R.probe };\n shader.vertexShader = shader.vertexShader\n .replace(\n '#include <common>',\n '#include <common>\\nvarying vec3 vBoxWorldPosition;',\n )\n .replace(\n '#include <worldpos_vertex>',\n '#include <worldpos_vertex>\\nvBoxWorldPosition = (modelMatrix * vec4(transformed, 1.0)).xyz;',\n );\n shader.fragmentShader = shader.fragmentShader\n .replace(\n '#include <common>',\n '#include <common>\\nvarying vec3 vBoxWorldPosition;\\nuniform vec3 boxMin;\\nuniform vec3 boxMax;\\nuniform vec3 probePosition;',\n )\n .replace('#include <envmap_physical_pars_fragment>', chunk);\n };\n material.customProgramCacheKey = () =>\n `environment:${boxProjected}:${specularOnly}`;\n return material;\n}\n\n// Room surfaces get their indirect light from baked lightmaps, so their\n// environment map only contributes reflections. One material per surface.\nfunction shellMaterial(params: THREE.MeshStandardMaterialParameters) {\n const material = standard({\n envMapIntensity: 0.5,\n lightMapIntensity: LIGHTMAP_INTENSITY,\n ...params,\n });\n material.shadowSide = THREE.DoubleSide;\n return customizeEnvironment(material, { specularOnly: true });\n}\n\nfunction floorMaterial() {\n switch (R.spec.floor ?? 'oak') {\n case 'carpet':\n return shellMaterial({\n map: carpetTexture(),\n roughness: 1,\n envMapIntensity: 0.1,\n });\n case 'concrete':\n return customizeEnvironment(\n shellMaterial({\n map: concreteTexture(),\n roughness: 0.55,\n envMapIntensity: 0.6,\n }),\n { boxProjected: true, specularOnly: true },\n );\n default:\n return customizeEnvironment(\n shellMaterial({\n ...oakTextures(),\n bumpScale: 0.15,\n roughness: 1,\n envMapIntensity: 0.5,\n }),\n { boxProjected: true, specularOnly: true },\n );\n }\n}\n\nfunction wallMaterial() {\n return shellMaterial({\n color: R.wallColor,\n roughness: 0.9,\n bumpMap: plasterBump(),\n bumpScale: 0.12,\n });\n}\n\n// ------------------------------------------------------------------ shell\n\nfunction buildShell() {\n const { x0, x1, z0, z1, h } = R;\n const W = x1 - x0;\n const D = z1 - z0;\n const zc = (z0 + z1) / 2;\n const SEAM = 0.004;\n\n const floor = mesh(panel(W, D), floorMaterial(), [0, 0, zc], scene, {\n cast: false,\n });\n floor.rotation.x = -Math.PI / 2;\n floor.userData.xrPlane = 'floor';\n litSurface(floor, W, D);\n const ceiling = mesh(\n panel(W, D),\n shellMaterial({ color: '#f7f4ef', roughness: 0.95 }),\n [0, h, zc],\n );\n ceiling.rotation.x = Math.PI / 2;\n ceiling.userData.xrPlane = 'ceiling';\n litSurface(ceiling, W, D);\n\n // Walls overlap the floor, ceiling and each other slightly so no seam\n // shows a hairline.\n for (const wall of WALLS) {\n const info = wallInfo(wall);\n const holes = R.windows\n .filter((w) => w.wall === wall)\n .map((w): [number, number, number, number] => {\n const lx = w.center.clone().sub(info.center).dot(info.u);\n return [\n lx - w.width / 2,\n w.sill - h / 2,\n lx + w.width / 2,\n w.head - h / 2,\n ];\n });\n const object = mesh(\n panel(info.length + SEAM, h + SEAM, holes),\n wallMaterial(),\n [info.center.x, info.center.y, info.center.z],\n );\n object.rotation.y = info.rotationY;\n object.userData.xrPlane = 'wall';\n litSurface(object, info.length + SEAM, h + SEAM);\n // Baseboard.\n const base = group(info.center.x, 0, info.center.z, info.rotationY);\n box([info.length, 0.09, 0.014], mats.trim(), [0, 0.045, 0.007], base);\n }\n\n buildShadowShell();\n for (const w of R.windows) buildWindow(w);\n for (const d of R.spec.doors ?? []) buildDoor(d);\n\n // Recessed downlights (off during the day): trim ring and lens.\n const ring = own(new THREE.RingGeometry(0.045, 0.062, 32));\n const lens = own(new THREE.CircleGeometry(0.045, 32));\n const lensMaterial = paintMaterial('#dcd7ce', 0.3);\n const lights =\n R.spec.downlights ??\n [x0 + W / 4, x1 - W / 4].flatMap((x) =>\n (D > 6 ? [z0 + D / 6, zc, z1 - D / 6] : [z0 + D / 4, z1 - D / 4]).map(\n (z): [number, number] => [x, z],\n ),\n );\n for (const [x, z] of lights) {\n mesh(ring, mats.trim(), [x, h - 0.002, z], scene, {\n cast: false,\n }).rotation.x = Math.PI / 2;\n mesh(lens, lensMaterial, [x, h - 0.004, z], scene, {\n cast: false,\n }).rotation.x = Math.PI / 2;\n }\n}\n\n// Shadow-only shell: thick boxes around the room (with the outside window\n// openings) so no sunlight leaks in where the thin wall and ceiling planes\n// meet. They write neither color nor depth and ignore hit-test rays.\nfunction buildShadowShell() {\n const { x0, x1, z0, z1, h } = R;\n const caster = own(\n new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false }),\n );\n caster.shadowSide = THREE.DoubleSide;\n const slab = (min: Vec3, max: Vec3) => {\n const object = box(\n [max[0] - min[0], max[1] - min[1], max[2] - min[2]],\n caster,\n [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2],\n );\n object.receiveShadow = false;\n object.userData.shadowOnly = true;\n };\n const t = 0.2;\n const inset = 0.03;\n const margin = 0.4;\n slab(\n [x0 - margin, h - inset, z0 - margin],\n [x1 + margin, h + t, z1 + margin],\n );\n for (const wall of WALLS) {\n const openings = R.windows.filter((w) => w.wall === wall && w.exterior);\n // Walls with openings sit outside the window reveals, so the reveals\n // catch the sun.\n const [near, far] = openings.length ? [0.2, 0.2 + t] : [-inset, t];\n const horizontal = wall === 'back' || wall === 'front';\n const [lo, hi] = horizontal\n ? [x0 - margin, x1 + margin]\n : [z0 - margin, z1 + margin];\n const cuts = [\n lo,\n hi,\n ...openings.flatMap((w) => [w.at - w.width / 2, w.at + w.width / 2]),\n ].sort((a, b) => a - b);\n for (let i = 0; i < cuts.length - 1; i++) {\n const [u0, u1] = [cuts[i], cuts[i + 1]];\n if (u1 - u0 < 1e-4) continue;\n const opening = openings.find(\n (w) =>\n (u0 + u1) / 2 > w.at - w.width / 2 &&\n (u0 + u1) / 2 < w.at + w.width / 2,\n );\n const spans: [number, number][] = opening\n ? [\n [-0.1, opening.sill],\n [opening.head, h + t],\n ]\n : [[-0.1, h + t]];\n for (const [y0, y1] of spans) {\n if (wall === 'back') slab([u0, y0, z0 - far], [u1, y1, z0 - near]);\n if (wall === 'front') slab([u0, y0, z1 + near], [u1, y1, z1 + far]);\n if (wall === 'left') slab([x0 - far, y0, u0], [x0 - near, y1, u1]);\n if (wall === 'right') slab([x1 + near, y0, u0], [x1 + far, y1, u1]);\n }\n }\n }\n}\n\nconst curtainMaterial = once(() =>\n standard({\n vertexColors: true,\n color: '#f5f2ea',\n roughness: 1,\n side: THREE.DoubleSide,\n transparent: true,\n opacity: 0.82,\n emissive: '#fff6e6',\n emissiveIntensity: 0.25,\n }),\n);\n\n// Window: reveal, frame, glass, the view outside, sheers or a blind. The\n// WebXR plane is flush with the wall, as a room scan reports it.\nfunction buildWindow(w: Win) {\n const info = wallInfo(w.wall);\n const base = info.point(w.at, 0);\n const win = group(base.x, 0, base.z, info.rotationY);\n const { width, sill, head } = w;\n const reveal = 0.16;\n // Reveals have no lightmap, so they take their diffuse light from the probe.\n const revealMaterial = standard({\n color: R.wallColor,\n roughness: 0.9,\n bumpMap: plasterBump(),\n bumpScale: 0.12,\n envMapIntensity: 1,\n });\n revealMaterial.shadowSide = THREE.DoubleSide;\n box(\n [0.02, head - sill, reveal],\n revealMaterial,\n [-width / 2 - 0.01, (sill + head) / 2, -reveal / 2],\n win,\n );\n box(\n [0.02, head - sill, reveal],\n revealMaterial,\n [width / 2 + 0.01, (sill + head) / 2, -reveal / 2],\n win,\n );\n box(\n [width, 0.02, reveal],\n revealMaterial,\n [0, head + 0.01, -reveal / 2],\n win,\n );\n box(\n [width + 0.12, 0.03, reveal + 0.06],\n mats.trim(),\n [0, sill - 0.015, -reveal / 2 + 0.03],\n win,\n );\n const frameZ = -reveal + 0.04;\n box([width, 0.05, 0.06], mats.trim(), [0, sill + 0.025, frameZ], win);\n box([width, 0.05, 0.06], mats.trim(), [0, head - 0.025, frameZ], win);\n box(\n [0.05, head - sill, 0.06],\n mats.trim(),\n [-width / 2 + 0.025, (sill + head) / 2, frameZ],\n win,\n );\n box(\n [0.05, head - sill, 0.06],\n mats.trim(),\n [width / 2 - 0.025, (sill + head) / 2, frameZ],\n win,\n );\n const mullions =\n w.spec.mullions ??\n (width > 1.4 ? Math.max(1, Math.round(width / 1.2) - 1) : 0);\n for (let i = 1; i <= mullions; i++) {\n box(\n [0.05, head - sill, 0.06],\n mats.trim(),\n [-width / 2 + (i * width) / (mullions + 1), (sill + head) / 2, frameZ],\n win,\n );\n }\n const glass = mesh(\n unitPlane,\n mats.glass(),\n [0, (sill + head) / 2, frameZ],\n win,\n { cast: false, receive: false },\n );\n glass.scale.set(width, head - sill, 1);\n const plane = mesh(\n unitPlane,\n mats.hidden(),\n [0, (sill + head) / 2, 0.002],\n win,\n { cast: false, receive: false },\n );\n plane.scale.set(width, head - sill, 1);\n plane.userData.xrPlane = 'window';\n\n if (w.exterior) {\n const view = own(new THREE.MeshBasicMaterial({ map: outsideTexture() }));\n view.color.setScalar(4); // overexposed, like a photo of a window\n const outside = mesh(unitPlane, view, [0, 1.3, -4], win, {\n cast: false,\n receive: false,\n });\n outside.scale.set(Math.max(12, width * 3), 6, 1);\n outside.userData.xrGlobalMesh = false; // outside the room, not scanned\n } else {\n const view = own(new THREE.MeshBasicMaterial({ map: corridorTexture() }));\n view.color.setScalar(1.25);\n const corridor = mesh(unitPlane, view, [0, R.h / 2, -1.6], win, {\n cast: false,\n receive: false,\n });\n corridor.scale.set(width + 2, R.h, 1);\n corridor.userData.xrGlobalMesh = false; // beyond the glass, not scanned\n const frosted = mesh(\n unitPlane,\n standard({\n color: '#ffffff',\n roughness: 0.9,\n transparent: true,\n opacity: 0.6,\n }),\n [0, 1.3, frameZ + 0.004],\n win,\n { cast: false, receive: false },\n );\n frosted.scale.set(width, 0.5, 1);\n }\n\n if (w.spec.blind) {\n const drop = (head - sill) * w.spec.blind;\n cylinder(\n 0.03,\n 0.03,\n width - 0.04,\n paintMaterial('#e8e1d4', 0.9),\n [0, head - 0.04, -0.03],\n win,\n 16,\n ).rotation.z = Math.PI / 2;\n const fabric = mesh(\n unitPlane,\n standard({\n color: '#e8e1d4',\n roughness: 1,\n side: THREE.DoubleSide,\n transparent: true,\n opacity: 0.92,\n emissive: '#fff4e2',\n emissiveIntensity: 0.3,\n }),\n [0, head - 0.04 - drop / 2, -0.01],\n win,\n { cast: true, receive: false },\n );\n fabric.scale.set(width - 0.06, drop, 1);\n } else if (w.exterior && w.spec.sheers !== false) {\n mesh(\n own(new THREE.CylinderGeometry(0.012, 0.012, width + 1, 12)),\n mats.brass(),\n [0, head + 0.15, 0.1],\n win,\n ).rotation.z = Math.PI / 2;\n for (const [x, seed] of [\n [-width / 2 - 0.22, 1],\n [width / 2 + 0.22, 4],\n ]) {\n const height = head + 0.13;\n const geometry = own(new THREE.PlaneGeometry(0.62, height, 48, 8));\n const position = geometry.getAttribute('position');\n const colors = new Float32Array(position.count * 3);\n for (let i = 0; i < position.count; i++) {\n const px = position.getX(i);\n const py = position.getY(i) / height + 0.5;\n const phase = (px / 0.11) * Math.PI * 2 + Math.sin(px * 9 + seed) * 1.2;\n const fold = Math.sin(phase);\n position.setZ(i, fold * 0.03 * (0.8 + 0.2 * py));\n colors.fill(0.85 + 0.15 * (fold * 0.5 + 0.5), i * 3, i * 3 + 3);\n }\n geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));\n geometry.computeVertexNormals();\n mesh(geometry, curtainMaterial(), [x, height / 2 + 0.02, 0.1], win, {\n cast: false,\n });\n }\n }\n}\n\n// Door: slab with a dark gap, trim and a lever handle.\nfunction buildDoor(d: DoorSpec) {\n const info = wallInfo(d.wall);\n const base = info.point(d.at, 0);\n const door = group(base.x, 0, base.z, info.rotationY);\n const width = d.width ?? 0.86;\n const height = d.height ?? 2.06;\n box(\n [width, height + 0.005, 0.01],\n paintMaterial('#3a3836', 1),\n [0, (height + 0.005) / 2, 0.005],\n door,\n );\n const slab = mesh(\n roundedBox(width - 0.006, height - 0.004, 0.04, 0.004, 0, 2),\n mats.trim(),\n [0, (height - 0.004) / 2, 0.022],\n door,\n );\n slab.userData.xrPlane = 'door';\n for (const [w, h, x, y] of [\n [0.07, height + 0.07, -width / 2 - 0.035, (height + 0.07) / 2],\n [0.07, height + 0.07, width / 2 + 0.035, (height + 0.07) / 2],\n [width + 0.14, 0.07, 0, height + 0.035],\n ]) {\n box([w, h, 0.022], mats.trim(), [x, y, 0.011], door);\n }\n box([0.025, 0.12, 0.012], mats.brass(), [width / 2 - 0.07, 1.0, 0.05], door);\n mesh(\n own(new THREE.CylinderGeometry(0.012, 0.012, 0.12, 12)),\n mats.brass(),\n [width / 2 - 0.11, 1.02, 0.07],\n door,\n ).rotation.z = Math.PI / 2;\n}\n\n// --------------------------------------------------------------- finishing\n\n// Bakes ambient occlusion into furniture as vertex colors (and instance\n// colors): darker near the floor and next to other furniture.\nfunction bakeFurnitureShading() {\n const p = new THREE.Vector3();\n const n = new THREE.Vector3();\n const normalMatrix = new THREE.Matrix3();\n const shade = (y: number) => {\n const ao = occlusion(\n p,\n n,\n R.occluders.filter((o) => !inside(p, o)),\n );\n const floor = n.y > 0.7 ? 1 : 1 - 0.35 * Math.exp(-y / 0.15);\n return THREE.MathUtils.clamp(0.55 + 0.45 * ao, 0.55, 1) * floor;\n };\n const skip = (material: THREE.Material) => {\n const m = material as THREE.MeshStandardMaterial;\n return (\n !m.isMeshStandardMaterial ||\n m === mats.trim() ||\n m.transparent ||\n !m.visible ||\n !!m.lightMap ||\n m.emissive.getHex() !== 0\n );\n };\n const seen = new Set<THREE.BufferGeometry>();\n const shaded = new Set<THREE.Material>();\n scene.updateMatrixWorld(true);\n scene.traverse((object) => {\n const target = object as THREE.Mesh;\n if (!target.isMesh || skip(target.material as THREE.Material)) return;\n shaded.add(target.material as THREE.Material);\n const instanced = object as THREE.InstancedMesh;\n if (instanced.isInstancedMesh) {\n const matrix = new THREE.Matrix4();\n const color = new THREE.Color();\n for (let i = 0; i < instanced.count; i++) {\n instanced.getMatrixAt(i, matrix);\n p.setFromMatrixPosition(matrix.premultiply(instanced.matrixWorld));\n n.set(0, 1, 0);\n const f = shade(p.y);\n if (instanced.instanceColor) instanced.getColorAt(i, color);\n else color.setRGB(1, 1, 1);\n instanced.setColorAt(i, color.multiplyScalar(f));\n }\n return;\n }\n if (seen.has(target.geometry))\n target.geometry = own(target.geometry.clone());\n seen.add(target.geometry);\n const position = target.geometry.getAttribute('position');\n const normal = target.geometry.getAttribute('normal');\n const colors = new Float32Array(position.count * 3);\n normalMatrix.getNormalMatrix(target.matrixWorld);\n for (let i = 0; i < position.count; i++) {\n p.fromBufferAttribute(position, i).applyMatrix4(target.matrixWorld);\n n.fromBufferAttribute(normal, i).applyMatrix3(normalMatrix).normalize();\n colors.fill(shade(p.y), i * 3, i * 3 + 3);\n }\n target.geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));\n });\n shaded.forEach((material) => (material.vertexColors = true));\n // Shared materials on meshes without a color attribute get plain white.\n scene.traverse((object) => {\n const target = object as THREE.Mesh;\n if (!target.isMesh || !(target.material as THREE.Material).vertexColors)\n return;\n if (target.geometry.getAttribute('color')) return;\n const count = target.geometry.getAttribute('position').count;\n target.geometry.setAttribute(\n 'color',\n new THREE.BufferAttribute(new Float32Array(count * 3).fill(1), 3),\n );\n });\n}\n\n// Merges static meshes that share a material into one draw call each.\n// Labelled meshes stay separate so they remain WebXR planes / meshes.\nfunction mergeStaticMeshes() {\n scene.updateMatrixWorld(true);\n // Objects tagged xrGlobalMesh = false (moving objects, views outside) stay\n // separate, so they keep their tag and can still move.\n const untracked = (object: THREE.Object3D | null) => {\n for (; object; object = object.parent) {\n if (object.userData.xrGlobalMesh === false) return true;\n }\n return false;\n };\n const buckets = new Map<string, THREE.Mesh[]>();\n scene.traverse((object) => {\n const target = object as THREE.Mesh;\n if (!target.isMesh || (target as THREE.InstancedMesh).isInstancedMesh)\n return;\n const material = target.material as THREE.Material;\n if (!material.visible || material.transparent) return;\n if (target.userData.xrPlane || target.userData.xrMesh) return;\n if (untracked(target)) return;\n const attributes = Object.keys(target.geometry.attributes).sort().join();\n const key = `${material.uuid}:${target.castShadow}:${target.receiveShadow}:${attributes}`;\n buckets.set(key, [...(buckets.get(key) ?? []), target]);\n });\n for (const meshes of buckets.values()) {\n if (meshes.length < 2) continue;\n const names = Object.keys(meshes[0].geometry.attributes);\n const vertexCount = meshes.reduce(\n (sum, m) => sum + m.geometry.getAttribute('position').count,\n 0,\n );\n const arrays = Object.fromEntries(\n names.map((name) => [\n name,\n new Float32Array(\n vertexCount * meshes[0].geometry.getAttribute(name).itemSize,\n ),\n ]),\n );\n const indices: number[] = [];\n let base = 0;\n for (const m of meshes) {\n const geometry = m.geometry.clone();\n geometry.applyMatrix4(m.matrixWorld);\n for (const name of names) {\n const attribute = geometry.getAttribute(name);\n arrays[name].set(\n attribute.array as Float32Array,\n base * attribute.itemSize,\n );\n }\n const index = geometry.getIndex();\n const count = geometry.getAttribute('position').count;\n if (index)\n for (let i = 0; i < index.count; i++)\n indices.push(index.getX(i) + base);\n else for (let i = 0; i < count; i++) indices.push(i + base);\n base += count;\n geometry.dispose();\n m.removeFromParent();\n }\n const merged = own(new THREE.BufferGeometry());\n for (const name of names) {\n merged.setAttribute(\n name,\n new THREE.BufferAttribute(\n arrays[name],\n meshes[0].geometry.getAttribute(name).itemSize,\n ),\n );\n }\n merged.setIndex(indices);\n const combined = new THREE.Mesh(merged, meshes[0].material);\n if (meshes[0].userData.shadowOnly) combined.raycast = () => {};\n combined.castShadow = meshes[0].castShadow;\n combined.receiveShadow = meshes[0].receiveShadow;\n scene.add(combined);\n }\n}\n\n// True if the ray from p back towards the sun leaves through an outside window.\nfunction sunThroughWindow(p: THREE.Vector3) {\n const toSun = R.sunDirection.clone().negate();\n for (const w of R.windows) {\n if (!w.exterior) continue;\n const denom = -w.normal.dot(toSun);\n if (denom <= 1e-4) continue;\n const t = w.normal.dot(toSample.subVectors(p, w.center)) / denom;\n if (t <= 0) continue;\n const q = p.clone().addScaledVector(toSun, t);\n if (\n q.y > w.sill &&\n q.y < w.head &&\n Math.abs(q.clone().sub(w.center).dot(w.u)) < w.width / 2\n )\n return true;\n }\n return false;\n}\n\n// Environment probe: an HDR equirect painted by ray casting the room from\n// its center and shading each hit with the same baked irradiance, so\n// reflections show the actual room, windows and sun patch.\nfunction roomEnvironment() {\n const width = 96;\n const height = 48;\n const data = new Float32Array(width * height * 4);\n const probe = R.probe;\n // Average linear albedo of each floor texture.\n const floorAlbedo = {\n oak: [0.4, 0.27, 0.15],\n carpet: [0.34, 0.32, 0.29],\n concrete: [0.48, 0.46, 0.43],\n }[R.spec.floor ?? 'oak'];\n const d = new THREE.Vector3();\n const hit = new THREE.Vector3();\n const n = new THREE.Vector3();\n const room = {\n min: new THREE.Vector3(R.x0, 0, R.z0),\n max: new THREE.Vector3(R.x1, R.h, R.z1),\n strength: 0,\n };\n const exit = (o: Occluder) => {\n let t = Infinity;\n for (const axis of ['x', 'y', 'z'] as const) {\n if (Math.abs(d[axis]) < 1e-6) continue;\n const bound = d[axis] > 0 ? o.max[axis] : o.min[axis];\n t = Math.min(t, (bound - probe[axis]) / d[axis]);\n }\n return t;\n };\n const entry = (o: Occluder) => {\n let near = -Infinity;\n let far = Infinity;\n for (const axis of ['x', 'y', 'z'] as const) {\n if (Math.abs(d[axis]) < 1e-6) {\n if (probe[axis] < o.min[axis] || probe[axis] > o.max[axis])\n return Infinity;\n continue;\n }\n const a = (o.min[axis] - probe[axis]) / d[axis];\n const b = (o.max[axis] - probe[axis]) / d[axis];\n near = Math.max(near, Math.min(a, b));\n far = Math.min(far, Math.max(a, b));\n }\n return near > 0 && near <= far ? near : Infinity;\n };\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const phi = ((x + 0.5) / width - 0.5) * Math.PI * 2;\n const theta = ((y + 0.5) / height - 0.5) * Math.PI;\n d.set(\n Math.cos(theta) * Math.cos(phi),\n Math.sin(theta),\n Math.cos(theta) * Math.sin(phi),\n );\n let t = exit(room);\n let furniture: Occluder | undefined;\n for (const o of R.occluders) {\n const te = entry(o);\n if (te < t) {\n t = te;\n furniture = o;\n }\n }\n hit.copy(probe).addScaledVector(d, t);\n const boxHit = furniture ?? room;\n const sign = furniture ? 1 : -1;\n if (Math.abs(hit.x - boxHit.min.x) < 1e-3) n.set(-sign, 0, 0);\n else if (Math.abs(hit.x - boxHit.max.x) < 1e-3) n.set(sign, 0, 0);\n else if (Math.abs(hit.y - boxHit.min.y) < 1e-3) n.set(0, -sign, 0);\n else if (Math.abs(hit.y - boxHit.max.y) < 1e-3) n.set(0, sign, 0);\n else if (Math.abs(hit.z - boxHit.min.z) < 1e-3) n.set(0, 0, -sign);\n else n.set(0, 0, sign);\n const window = furniture\n ? undefined\n : R.windows.find(\n (w) =>\n n.dot(w.normal) > 0.5 &&\n hit.y > w.sill &&\n hit.y < w.head &&\n Math.abs(hit.clone().sub(w.center).dot(w.u)) < w.width / 2,\n );\n let rgb: number[];\n if (window) {\n rgb = window.exterior ? [3.2, 3.4, 3.6] : [0.9, 0.88, 0.84];\n } else {\n const albedo = furniture\n ? [0.3, 0.28, 0.26]\n : n.y > 0.5\n ? floorAlbedo\n : n.y < -0.5\n ? [0.9, 0.87, 0.83]\n : [0.82, 0.77, 0.69];\n const e = irradiance(hit, n);\n rgb = albedo.map((a, i) => (a * e[i] * LIGHTMAP_INTENSITY) / Math.PI);\n if (R.hasSun && !furniture && n.y > 0.5 && sunThroughWindow(hit)) {\n const sun = (SUN_INTENSITY * -R.sunDirection.y * 0.45) / Math.PI;\n rgb = [rgb[0] + sun, rgb[1] + sun * 0.86, rgb[2] + sun * 0.67];\n }\n }\n data.set([rgb[0], rgb[1], rgb[2], 1], (y * width + x) * 4);\n }\n }\n const tex = own(\n new THREE.DataTexture(\n data,\n width,\n height,\n THREE.RGBAFormat,\n THREE.FloatType,\n ),\n );\n tex.mapping = THREE.EquirectangularReflectionMapping;\n tex.magFilter = THREE.LinearFilter;\n tex.needsUpdate = true;\n return tex;\n}\n\n// Afternoon sun through the window: a static shadow, rendered once.\nfunction addSun() {\n if (!R.hasSun) return;\n // Owned so its shadow map is freed when the room unloads.\n const sun = own(new THREE.DirectionalLight('#ffdcaa', SUN_INTENSITY));\n const position = R.sunTarget.clone().addScaledVector(R.sunDirection, -12);\n sun.position.copy(position);\n sun.target.position.copy(R.sunTarget);\n sun.castShadow = true;\n sun.shadow.mapSize.set(2048, 2048);\n // Fit the shadow frustum tightly around the room (outside it would be lit).\n const view = new THREE.Matrix4().lookAt(\n position,\n R.sunTarget,\n new THREE.Vector3(0, 1, 0),\n );\n view.setPosition(position).invert();\n const bounds = new THREE.Box3();\n for (const x of [R.x0 - 0.3, R.x1 + 0.3]) {\n for (const y of [0, R.h]) {\n for (const z of [R.z0 - 0.3, R.z1 + 0.3])\n bounds.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(view));\n }\n }\n Object.assign(sun.shadow.camera, {\n left: bounds.min.x - 0.05,\n right: bounds.max.x + 0.05,\n bottom: bounds.min.y - 0.05,\n top: bounds.max.y + 0.05,\n near: -bounds.max.z - 0.5,\n far: -bounds.min.z + 0.5,\n });\n sun.shadow.bias = -0.0002;\n sun.shadow.normalBias = 0.02;\n sun.shadow.radius = 0.8;\n sun.shadow.autoUpdate = false;\n sun.shadow.needsUpdate = true;\n scene.add(sun, sun.target);\n}\n\n// Robot vacuum: added after the bake and merge so it stays a separate,\n// movable object. Like on real devices it is not a tracked plane/mesh. Its\n// materials are its own, since the bake may have set vertexColors on shared\n// ones, and it casts no shadow into the sun's shadow map, which is rendered\n// once; the blob shadow follows it instead.\nfunction addRobot({\n center,\n radius,\n speed = 0.35,\n}: NonNullable<RoomSpec['robot']>) {\n const robot = new THREE.Group();\n robot.name = 'robot';\n // It moves, so it is not part of the room's global mesh.\n robot.userData.xrGlobalMesh = false;\n scene.add(robot);\n mesh(\n own(new THREE.CylinderGeometry(0.17, 0.17, 0.075, 48)),\n standard({ color: '#232325', roughness: 0.25, metalness: 0.1 }),\n [0, 0.045, 0],\n robot,\n { cast: false },\n );\n mesh(\n own(new THREE.TorusGeometry(0.17, 0.012, 8, 48)),\n standard({ color: '#4a4a4c', roughness: 0.6 }),\n [0, 0.03, 0],\n robot,\n { cast: false },\n ).rotation.x = Math.PI / 2;\n mesh(\n own(new THREE.CylinderGeometry(0.045, 0.045, 0.025, 32)),\n standard({ color: '#3a3a3c', roughness: 0.4 }),\n [0, 0.095, 0.06],\n robot,\n { cast: false },\n );\n mesh(\n own(new THREE.CircleGeometry(0.008, 12)),\n mats.bulb(),\n [0.05, 0.0835, -0.1],\n robot,\n { cast: false },\n ).rotation.x = -Math.PI / 2;\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = 64;\n const ctx = canvas.getContext('2d')!;\n const gradient = ctx.createRadialGradient(32, 32, 24, 32, 32, 32);\n gradient.addColorStop(0, 'rgba(255,255,255,1)');\n gradient.addColorStop(1, 'rgba(255,255,255,0)');\n ctx.fillStyle = gradient;\n ctx.fillRect(0, 0, 64, 64);\n const shadow = mesh(\n own(new THREE.PlaneGeometry(0.4, 0.4)),\n own(\n new THREE.MeshBasicMaterial({\n color: 'black',\n alphaMap: own(new THREE.CanvasTexture(canvas)),\n transparent: true,\n opacity: 0.45,\n depthWrite: false,\n }),\n ),\n [0, 0.008, 0],\n robot,\n { cast: false, receive: false },\n );\n shadow.rotation.x = -Math.PI / 2;\n let time = 0;\n const place = () => {\n const angle = time * speed;\n robot.position.set(\n center[0] + Math.cos(angle) * radius[0],\n 0,\n center[1] + Math.sin(angle) * radius[1],\n );\n robot.rotation.y = Math.atan2(\n Math.sin(angle) * radius[0],\n -Math.cos(angle) * radius[1],\n );\n };\n place();\n onFrame((delta) => {\n time += delta;\n place();\n });\n}\n\nfunction finish() {\n buildShell();\n for (const { object, w, h } of R.lit) {\n (object.material as THREE.MeshStandardMaterial).lightMap = bakeLightmap(\n object,\n w,\n h,\n );\n }\n bakeFurnitureShading();\n mergeStaticMeshes();\n scene.background = new THREE.Color('#e6e1d8');\n scene.environment = roomEnvironment();\n scene.environmentIntensity = 1.2;\n addSun();\n scene.rendering.shadows = true;\n scene.rendering.toneMapping = THREE.AgXToneMapping;\n scene.rendering.toneMappingExposure = 0.95;\n if (R.spec.robot) addRobot(R.spec.robot);\n\n let entities = 0;\n scene.traverse((object) => {\n if (object.userData.xrPlane) entities++;\n if (object.userData.xrMesh) entities++;\n });\n if (entities > MAX_ENTITIES) {\n console.warn(\n `${R.spec.name}: ${entities} planes and meshes; a scanned room usually reports at most ${MAX_ENTITIES}`,\n );\n }\n}\n\n// ---------------------------------------------------------------- seating\n\n// A room scan reports a couch as a volume plus a seat plane; the seat plane is\n// invisible (the cushions are what you see and hit).\nfunction couchSeat(\n g: THREE.Object3D,\n width: number,\n depth: number,\n height: number,\n z = 0,\n) {\n const seat = mesh(unitPlane, mats.hidden(), [0, height, z], g, {\n cast: false,\n receive: false,\n });\n seat.rotation.x = -Math.PI / 2;\n seat.scale.set(width, depth, 1);\n seat.userData.xrPlane = 'couch';\n return seat;\n}\n\n// Three-seat (or two-seat) sofa with seat and back cushions and two pillows.\nfunction sofa(\n g: THREE.Object3D,\n { width = 2.1, color = '#7f868b', pillows = ['#c79e68', '#e8e2d5'] } = {},\n) {\n const fabric = fabricMaterial(color, 51);\n mesh(roundedBox(width, 0.2, 0.92, 0.04), fabric, [0, 0.19, 0], g);\n mesh(roundedBox(width, 0.52, 0.2, 0.07), fabric, [0, 0.55, -0.36], g);\n for (const s of [-1, 1]) {\n mesh(\n roundedBox(0.2, 0.38, 0.92, 0.07, 0.008),\n fabric,\n [s * (width / 2 - 0.1), 0.45, 0],\n g,\n );\n for (const z of [-0.36, 0.36])\n cylinder(\n 0.016,\n 0.011,\n 0.09,\n mats.blackMetal(),\n [s * (width / 2 - 0.08), 0.045, z],\n g,\n 10,\n ).castShadow = false;\n }\n const seats = width > 1.7 ? 3 : 2;\n const seat = (width - 0.4) / seats;\n for (let i = 0; i < seats; i++) {\n const x = -width / 2 + 0.2 + seat * (i + 0.5);\n mesh(\n roundedBox(seat - 0.008, 0.16, 0.68, 0.06, 0.022, 6),\n fabric,\n [x, 0.37, 0.1],\n g,\n );\n mesh(\n roundedBox(seat - 0.015, 0.46, 0.2, 0.09, 0.025, 6),\n fabric,\n [x, 0.66, -0.2],\n g,\n ).rotation.x = -0.2;\n }\n pillows.forEach((pillow, i) => {\n const side = i === 0 ? -1 : 1;\n const object = mesh(\n roundedBox(0.46, 0.46, 0.13, 0.07, 0.04, 6),\n fabricMaterial(pillow, 52 + i),\n [side * (width / 2 - 0.38), 0.67, -0.07],\n g,\n );\n object.rotation.set(-0.3, -side * 0.3, side * 0.13);\n });\n couchSeat(g, width - 0.4, 0.66, 0.45, 0.1);\n volume('couch', [width, 0.86, 0.94], [0, 0.43, 0], g, 0.85);\n return g;\n}\n\n// Upholstered armchair with wooden legs.\nfunction armchair(g: THREE.Object3D, { color = '#b2643e' } = {}) {\n const fabric = fabricMaterial(color, 54);\n mesh(roundedBox(0.78, 0.28, 0.8, 0.06, 0.008), fabric, [0, 0.29, 0], g);\n mesh(\n roundedBox(0.66, 0.12, 0.62, 0.05, 0.022, 6),\n fabric,\n [0, 0.48, 0.06],\n g,\n );\n mesh(\n roundedBox(0.78, 0.5, 0.14, 0.06, 0.008),\n fabric,\n [0, 0.65, -0.33],\n g,\n ).rotation.x = -0.14;\n for (const s of [-1, 1]) {\n mesh(roundedBox(0.1, 0.22, 0.74, 0.045), fabric, [s * 0.36, 0.55, 0.02], g);\n for (const z of [-0.32, 0.32])\n mesh(\n roundedBox(0.035, 0.16, 0.035, 0.012),\n mats.walnut(),\n [s * 0.32, 0.08, z],\n g,\n ).rotation.z = s * 0.12;\n }\n couchSeat(g, 0.62, 0.58, 0.54, 0.06);\n volume('couch', [0.8, 0.9, 0.82], [0, 0.45, 0], g, 0.6);\n return g;\n}\n\n// Lounge chair: wooden side frames with seat and back cushions.\nfunction loungeChair(\n g: THREE.Object3D,\n { color = '#7d8a6a', wood = mats.walnut() } = {},\n) {\n const fabric = fabricMaterial(color, 57);\n for (const s of [-1, 1]) {\n mesh(roundedBox(0.04, 0.04, 0.78, 0.012), wood, [s * 0.34, 0.56, 0], g);\n const front = mesh(\n roundedBox(0.04, 0.58, 0.04, 0.012),\n wood,\n [s * 0.34, 0.28, 0.32],\n g,\n );\n front.rotation.x = 0.08;\n const back = mesh(\n roundedBox(0.04, 0.8, 0.04, 0.012),\n wood,\n [s * 0.34, 0.4, -0.3],\n g,\n );\n back.rotation.x = -0.32;\n }\n mesh(roundedBox(0.66, 0.11, 0.6, 0.04, 0.02, 6), fabric, [0, 0.4, 0.04], g);\n const back = mesh(\n roundedBox(0.62, 0.52, 0.11, 0.04, 0.015, 6),\n fabric,\n [0, 0.7, -0.24],\n g,\n );\n back.rotation.x = -0.32;\n couchSeat(g, 0.62, 0.56, 0.455, 0.04);\n volume('couch', [0.74, 0.88, 0.84], [0, 0.44, 0], g, 0.5);\n return g;\n}\n\n// Wooden dining chair.\nfunction woodChair(g: THREE.Object3D, { wood = mats.oak() } = {}) {\n mesh(roundedBox(0.44, 0.03, 0.42, 0.012), wood, [0, 0.45, 0], g);\n const back = mesh(\n roundedBox(0.42, 0.16, 0.025, 0.01),\n wood,\n [0, 0.76, -0.2],\n g,\n );\n back.rotation.x = 0.1;\n for (const x of [-0.19, 0.19]) {\n for (const z of [-0.18, 0.18]) {\n const height = z < 0 ? 0.84 : 0.44;\n mesh(\n roundedBox(0.025, height, 0.025, 0.008),\n wood,\n [x, height / 2, z],\n g,\n );\n }\n }\n volume('other', [0.44, 0.85, 0.42], [0, 0.425, 0], g, 0.4);\n return g;\n}\n\n// Office task chair on a five-star base.\nfunction taskChair(g: THREE.Object3D, { color = '#2f3033' } = {}) {\n const fabric = fabricMaterial(color, 58);\n const plastic = mats.charcoal();\n for (let i = 0; i < 5; i++) {\n const angle = (i / 5) * Math.PI * 2;\n const spoke = box(\n [0.03, 0.025, 0.3],\n plastic,\n [Math.sin(angle) * 0.15, 0.06, Math.cos(angle) * 0.15],\n g,\n );\n spoke.rotation.y = angle;\n mesh(\n own(new THREE.SphereGeometry(0.025, 10, 8)),\n plastic,\n [Math.sin(angle) * 0.29, 0.025, Math.cos(angle) * 0.29],\n g,\n );\n }\n cylinder(0.022, 0.022, 0.36, mats.steel(), [0, 0.24, 0], g, 12);\n mesh(roundedBox(0.5, 0.08, 0.48, 0.03, 0.012, 4), fabric, [0, 0.46, 0.02], g);\n const back = mesh(\n roundedBox(0.46, 0.56, 0.06, 0.03, 0, 4),\n fabric,\n [0, 0.82, -0.22],\n g,\n );\n back.rotation.x = -0.1;\n box([0.04, 0.3, 0.03], plastic, [0, 0.58, -0.24], g).rotation.x = -0.1;\n for (const s of [-1, 1]) {\n box([0.025, 0.18, 0.025], plastic, [s * 0.25, 0.56, 0.02], g);\n mesh(\n roundedBox(0.06, 0.025, 0.24, 0.01),\n plastic,\n [s * 0.25, 0.66, 0.02],\n g,\n );\n }\n volume('other', [0.62, 1.1, 0.62], [0, 0.55, 0], g, 0.35);\n return g;\n}\n\n// Upholstered shell chair on slim metal legs (meeting rooms).\nfunction shellChair(g: THREE.Object3D, { color = '#7d8a6a' } = {}) {\n const fabric = fabricMaterial(color, 59);\n mesh(roundedBox(0.5, 0.09, 0.48, 0.04, 0.012, 4), fabric, [0, 0.46, 0.02], g);\n const back = mesh(\n roundedBox(0.52, 0.36, 0.08, 0.04, 0, 4),\n fabric,\n [0, 0.7, -0.21],\n g,\n );\n back.rotation.x = -0.14;\n for (const s of [-1, 1])\n mesh(\n roundedBox(0.07, 0.2, 0.4, 0.03, 0, 4),\n fabric,\n [s * 0.24, 0.58, -0.02],\n g,\n );\n for (const x of [-0.2, 0.2]) {\n for (const z of [-0.18, 0.2]) {\n const leg = cylinder(\n 0.01,\n 0.008,\n 0.44,\n mats.blackMetal(),\n [x * 1.05, 0.22, z * 1.05],\n g,\n 8,\n );\n leg.rotation.set(z > 0 ? 0.08 : -0.08, 0, x > 0 ? -0.06 : 0.06);\n }\n }\n volume('other', [0.58, 0.88, 0.56], [0, 0.44, 0], g, 0.35);\n return g;\n}\n\n// Bar or counter stool with a round seat and a foot ring.\nfunction stool(g: THREE.Object3D, { height = 0.65, wood = mats.oak() } = {}) {\n cylinder(0.18, 0.17, 0.04, wood, [0, height - 0.02, 0], g, 32);\n for (let i = 0; i < 4; i++) {\n const angle = (i / 4) * Math.PI * 2 + Math.PI / 4;\n const leg = cylinder(\n 0.014,\n 0.016,\n height - 0.03,\n wood,\n [Math.sin(angle) * 0.14, (height - 0.03) / 2, Math.cos(angle) * 0.14],\n g,\n 8,\n );\n leg.rotation.set(Math.cos(angle) * 0.1, 0, -Math.sin(angle) * 0.1);\n }\n const ring = mesh(\n own(new THREE.TorusGeometry(0.15, 0.008, 6, 32)),\n mats.blackMetal(),\n [0, height * 0.35, 0],\n g,\n );\n ring.rotation.x = Math.PI / 2;\n volume('other', [0.4, height, 0.4], [0, height / 2, 0], g, 0.3);\n return g;\n}\n\n// ------------------------------------------------------------ tables, desks\n\ntype LegStyle = 'four' | 'frame' | 'pedestal';\n\n// Rectangular table: the top is a WebXR plane (`label`, default 'table').\nfunction table(\n g: THREE.Object3D,\n {\n width = 1.2,\n depth = 0.75,\n height = 0.74,\n top = mats.oak() as THREE.Material,\n legs = 'four' as LegStyle,\n legMaterial = mats.blackMetal() as THREE.Material,\n label = 'table',\n } = {},\n) {\n const surface = mesh(\n roundedBox(width, 0.03, depth, 0.01),\n top,\n [0, height - 0.015, 0],\n g,\n );\n surface.userData.xrPlane = label;\n const legHeight = height - 0.03;\n if (legs === 'pedestal') {\n cylinder(0.04, 0.05, legHeight, legMaterial, [0, legHeight / 2, 0], g, 16);\n cylinder(\n Math.min(width, depth) * 0.28,\n Math.min(width, depth) * 0.3,\n 0.02,\n legMaterial,\n [0, 0.01, 0],\n g,\n 32,\n );\n } else {\n const inset = 0.06;\n for (const x of [-width / 2 + inset, width / 2 - inset]) {\n for (const z of [-depth / 2 + inset, depth / 2 - inset]) {\n mesh(\n roundedBox(0.04, legHeight, 0.04, 0.008),\n legMaterial,\n [x, legHeight / 2, z],\n g,\n );\n }\n if (legs === 'frame')\n box([0.04, 0.03, depth - 2 * inset], legMaterial, [x, 0.04, 0], g);\n }\n }\n volume(label, [width, height, depth], [0, height / 2, 0], g, 0.45);\n return g;\n}\n\n// Round pedestal table: the top is a WebXR plane.\nfunction roundTable(\n g: THREE.Object3D,\n {\n radius = 0.45,\n height = 0.74,\n top = mats.oak() as THREE.Material,\n label = 'table',\n } = {},\n) {\n const surface = mesh(\n own(new THREE.CylinderGeometry(radius, radius, 0.03, 64)),\n top,\n [0, height - 0.015, 0],\n g,\n );\n surface.userData.xrPlane = label;\n cylinder(\n 0.04,\n 0.05,\n height - 0.03,\n mats.blackMetal(),\n [0, (height - 0.03) / 2, 0],\n g,\n 16,\n );\n cylinder(\n radius * 0.53,\n radius * 0.58,\n 0.02,\n mats.blackMetal(),\n [0, 0.01, 0],\n g,\n 48,\n );\n volume(label, [radius * 2, height, radius * 2], [0, height / 2, 0], g, 0.45);\n return g;\n}\n\n// Desk: a 'desk' table, optionally with a drawer pedestal on one side.\nfunction desk(\n g: THREE.Object3D,\n {\n width = 1.4,\n depth = 0.7,\n height = 0.74,\n top = mats.oak() as THREE.Material,\n drawers = 'right' as 'left' | 'right' | 'none',\n } = {},\n) {\n table(g, { width, depth, height, top, legs: 'four', label: 'desk' });\n if (drawers !== 'none') {\n const side = drawers === 'right' ? 1 : -1;\n const pedestal = group(side * (width / 2 - 0.26), 0, 0, 0, g);\n casegood(pedestal, {\n width: 0.4,\n height: height - 0.04,\n depth: depth - 0.12,\n fronts: 'drawers',\n count: 3,\n body: top,\n label: '',\n });\n }\n return g;\n}\n\n// ---------------------------------------------------------------- storage\n\n// Cabinet, sideboard, dresser, nightstand or wardrobe: a carcass with door\n// or drawer fronts (or open shelves), optional legs, reported as an XRMesh\n// (`label`, default 'shelf'; '' for none).\nfunction casegood(\n g: THREE.Object3D,\n {\n width = 1.2,\n height = 0.75,\n depth = 0.45,\n fronts = 'doors' as 'doors' | 'drawers' | 'open',\n count = 2,\n body = mats.walnut() as THREE.Material,\n front = undefined as THREE.Material | undefined,\n legs = 0,\n handles = 'bar' as 'bar' | 'knob' | 'none',\n label = 'shelf',\n } = {},\n) {\n const h = height - legs;\n const y0 = legs;\n const faces = front ?? body;\n if (fronts === 'open') {\n for (const x of [-width / 2 + 0.01, width / 2 - 0.01])\n box([0.02, h, depth], body, [x, y0 + h / 2, 0], g);\n box([width, h, 0.012], body, [0, y0 + h / 2, -depth / 2 + 0.006], g);\n for (let i = 0; i <= count; i++)\n box(\n [width - 0.04, 0.02, depth],\n body,\n [0, y0 + 0.01 + (i * (h - 0.02)) / count, 0],\n g,\n );\n } else {\n box([width, h, depth], body, [0, y0 + h / 2, 0], g);\n const columns = fronts === 'doors' ? count : 1;\n const rows = fronts === 'drawers' ? count : 1;\n const cw = width / columns;\n const ch = h / rows;\n for (let c = 0; c < columns; c++) {\n for (let r = 0; r < rows; r++) {\n const x = -width / 2 + cw * (c + 0.5);\n const y = y0 + ch * (r + 0.5);\n box(\n [cw - 0.006, ch - 0.006, 0.018],\n faces,\n [x, y, depth / 2 + 0.009],\n g,\n );\n if (handles === 'bar') {\n if (fronts === 'drawers')\n box(\n [Math.min(0.16, cw * 0.4), 0.012, 0.014],\n mats.blackMetal(),\n [x, y + ch * 0.25, depth / 2 + 0.025],\n g,\n );\n else\n box(\n [0.012, Math.min(0.18, ch * 0.3), 0.014],\n mats.blackMetal(),\n [x + (c % 2 ? -1 : 1) * (cw / 2 - 0.05), y, depth / 2 + 0.025],\n g,\n );\n } else if (handles === 'knob') {\n mesh(\n own(new THREE.SphereGeometry(0.014, 12, 8)),\n mats.brass(),\n [\n fronts === 'drawers' ? x : x + (c % 2 ? -1 : 1) * (cw / 2 - 0.05),\n y + (fronts === 'drawers' ? ch * 0.2 : 0),\n depth / 2 + 0.03,\n ],\n g,\n );\n }\n }\n }\n }\n if (legs > 0) {\n for (const x of [-width / 2 + 0.05, width / 2 - 0.05]) {\n for (const z of [-depth / 2 + 0.05, depth / 2 - 0.05])\n cylinder(0.016, 0.011, legs, mats.walnut(), [x, legs / 2, z], g, 8);\n }\n }\n if (label)\n volume(\n label,\n [width, height, depth + 0.03],\n [0, height / 2, 0.015],\n g,\n 0.7,\n );\n return g;\n}\n\n// Open bookshelf filled with instanced books.\nfunction bookshelf(\n g: THREE.Object3D,\n {\n width = 0.9,\n height = 1.9,\n depth = 0.34,\n levels = 5,\n wood = mats.walnut() as THREE.Material,\n seed = 0,\n } = {},\n) {\n for (const x of [-width / 2, width / 2])\n box([0.025, height, depth], wood, [x, height / 2, 0], g);\n box(\n [width, height, 0.012],\n wood === mats.walnut() ? mats.darkWalnut() : wood,\n [0, height / 2, -depth / 2 + 0.006],\n g,\n );\n const ys = Array.from(\n { length: levels + 1 },\n (_, i) => 0.05 + (i * (height - 0.06)) / levels,\n );\n for (const y of ys) box([width, 0.025, depth], wood, [0, y, 0], g);\n const palette = [\n '#2f3e46',\n '#b08d57',\n '#e3dccf',\n '#7a3b2e',\n '#55624a',\n '#cbb79a',\n '#3c3c3c',\n '#8c4f3b',\n ];\n const capacity = levels * 40;\n const books = own(\n new THREE.InstancedMesh(\n own(new THREE.BoxGeometry(1, 1, 1)),\n mats.book(),\n capacity,\n ),\n );\n books.castShadow = books.receiveShadow = true;\n const matrix = new THREE.Matrix4();\n const rotation = new THREE.Quaternion();\n const color = new THREE.Color();\n const spacing = (height - 0.06) / levels;\n let count = 0;\n for (let level = 0; level < levels; level++) {\n let x = -width / 2 + 0.02;\n const y = ys[level] + 0.0125;\n const end = (level + seed) % 2 ? width * 0.15 : width / 2 - 0.02;\n while (x < end - 0.03 && count < capacity) {\n const k = count + seed * 97;\n const thickness = 0.018 + hash(k, 5, 5) * 0.03;\n const tall = Math.min(spacing - 0.04, 0.19 + hash(k, 6, 6) * 0.11);\n const deep = Math.min(depth - 0.04, 0.17 + hash(k, 7, 7) * 0.07);\n rotation.setFromAxisAngle(\n new THREE.Vector3(0, 0, 1),\n x + thickness > end - 0.05 ? -0.18 : 0,\n );\n matrix.compose(\n new THREE.Vector3(x + thickness / 2, y + tall / 2, 0.02),\n rotation,\n new THREE.Vector3(thickness, tall, deep),\n );\n books.setMatrixAt(count, matrix);\n color.set(palette[Math.floor(hash(k, 8, 8) * palette.length)]);\n books.setColorAt(count, color.multiplyScalar(0.8 + hash(k, 9, 9) * 0.3));\n x += thickness + 0.0015;\n count++;\n }\n }\n books.count = count;\n g.add(books);\n volume('shelf', [width, height, depth], [0, height / 2, 0], g, 0.7);\n return g;\n}\n\n// ---------------------------------------------------------------- lighting\n\n// Table lamp; `lit` adds a warm point light (use at most two per room).\nfunction tableLamp(g: THREE.Object3D, { lit = false } = {}) {\n const base = mesh(\n own(new THREE.SphereGeometry(0.085, 24, 16)),\n mats.ceramic(),\n [0, 0.09, 0],\n g,\n );\n base.scale.y = 1.1;\n cylinder(0.009, 0.009, 0.18, mats.brass(), [0, 0.24, 0], g, 8);\n mesh(\n own(new THREE.CylinderGeometry(0.12, 0.16, 0.22, 40, 1, true)),\n lit ? mats.lampShade() : mats.linenShade(),\n [0, 0.38, 0],\n g,\n { cast: false },\n );\n if (lit) {\n mesh(\n own(new THREE.SphereGeometry(0.03, 12, 8)),\n mats.bulb(),\n [0, 0.33, 0],\n g,\n { cast: false, receive: false },\n );\n const glow = new THREE.PointLight('#ffc27a', 1.4, 3.5, 2);\n glow.position.set(0, 0.35, 0);\n g.add(glow);\n }\n volume('lamp', [0.32, 0.5, 0.32], [0, 0.25, 0], g, 0.3);\n return g;\n}\n\n// Floor lamp with a drum shade.\nfunction floorLamp(g: THREE.Object3D, { lit = false } = {}) {\n cylinder(0.14, 0.15, 0.02, mats.blackMetal(), [0, 0.01, 0], g, 40);\n cylinder(0.009, 0.009, 1.45, mats.blackMetal(), [0, 0.74, 0], g, 10);\n mesh(\n own(new THREE.CylinderGeometry(0.2, 0.2, 0.3, 48, 1, true)),\n lit ? mats.lampShade() : mats.linenShade(),\n [0, 1.55, 0],\n g,\n );\n const diffuser = mesh(\n own(new THREE.CircleGeometry(0.19, 40)),\n paintMaterial('#cfc7b8', 1),\n [0, 1.67, 0],\n g,\n { cast: false },\n );\n diffuser.rotation.x = Math.PI / 2;\n if (lit) {\n const glow = new THREE.PointLight('#ffc27a', 1.6, 4, 2);\n glow.position.set(0, 1.5, 0);\n g.add(glow);\n }\n volume('lamp', [0.4, 1.72, 0.4], [0, 0.86, 0], g, 0.4);\n return g;\n}\n\n// Pendant lamp hanging from a ceiling point (put `g` on the ceiling).\nfunction pendant(\n g: THREE.Object3D,\n { drop = 0.75, color = '#a65f40', radius = 0.2 } = {},\n) {\n cylinder(0.05, 0.05, 0.015, mats.blackMetal(), [0, -0.008, 0], g, 24);\n cylinder(0.003, 0.003, drop, mats.blackMetal(), [0, -drop / 2, 0], g, 6);\n const shade = mesh(\n own(\n new THREE.SphereGeometry(radius, 40, 16, 0, Math.PI * 2, 0, Math.PI / 2),\n ),\n standard({ color, roughness: 0.6, side: THREE.DoubleSide }),\n [0, -drop - radius * 0.55, 0],\n g,\n );\n shade.scale.y = 0.75;\n volume(\n 'lamp',\n [radius * 2, radius * 0.8, radius * 2],\n [0, -drop - radius * 0.35, 0],\n g,\n 0.2,\n );\n return g;\n}\n\n// Adjustable desk lamp (no volume: it sits on a desk volume).\nfunction deskLamp(g: THREE.Object3D) {\n cylinder(0.07, 0.08, 0.02, mats.blackMetal(), [0, 0.01, 0], g, 24);\n const lower = cylinder(\n 0.008,\n 0.008,\n 0.34,\n mats.blackMetal(),\n [0.05, 0.17, 0],\n g,\n 8,\n );\n lower.rotation.z = -0.3;\n const upper = cylinder(\n 0.008,\n 0.008,\n 0.3,\n mats.blackMetal(),\n [0.03, 0.42, 0],\n g,\n 8,\n );\n upper.rotation.z = 1.1;\n const head = mesh(\n own(new THREE.ConeGeometry(0.06, 0.12, 24, 1, true)),\n standard({ color: '#1f1f1f', roughness: 0.5, side: THREE.DoubleSide }),\n [-0.12, 0.47, 0],\n g,\n );\n head.rotation.z = 0.9;\n return g;\n}\n\n// ------------------------------------------------------------------ plants\n\n// Leafy floor plant (fiddle-leaf fig style) in a pot.\nfunction plant(\n g: THREE.Object3D,\n { height = 1.7, pot = mats.pot() as THREE.Material, seed = 0 } = {},\n) {\n const s = height / 1.95;\n const potRadius = 0.19 * Math.max(0.7, s);\n cylinder(potRadius, potRadius * 0.82, 0.38 * s, pot, [0, 0.19 * s, 0], g, 40);\n cylinder(\n potRadius * 0.94,\n potRadius * 0.94,\n 0.01,\n mats.soil(),\n [0, 0.37 * s, 0],\n g,\n 24,\n );\n mesh(\n own(\n new THREE.CylinderGeometry(0.014, 0.026, 1.5 * s, 8).translate(\n 0,\n 0.75 * s,\n 0,\n ),\n ),\n mats.bark(),\n [0, 0.36 * s, 0],\n g,\n );\n const leafGeometry = own(new THREE.PlaneGeometry(0.28, 0.38, 3, 4));\n const lp = leafGeometry.getAttribute('position');\n for (let i = 0; i < lp.count; i++) {\n const x = lp.getX(i);\n const y = lp.getY(i) + 0.19;\n lp.setXYZ(i, x, y + 0.04, Math.abs(x) * 0.3 - Math.pow(y / 0.38, 2) * 0.05);\n }\n leafGeometry.computeVertexNormals();\n const twig = own(\n new THREE.CylinderGeometry(0.007, 0.011, 1, 6).translate(0, 0.5, 0),\n );\n const anchors: { at: THREE.Vector3; yaw: number }[] = [];\n for (let b = 0; b < 4; b++) {\n const start = new THREE.Vector3(0, (1.05 + b * 0.19) * s, 0);\n const yaw = b * 2.1 + seed;\n const length = (0.42 - b * 0.05) * s;\n const direction = new THREE.Vector3(\n Math.sin(yaw) * 0.75,\n 0.66,\n Math.cos(yaw) * 0.75,\n ).normalize();\n const branch = mesh(twig, mats.bark(), [start.x, start.y, start.z], g);\n branch.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);\n branch.scale.set(1, length, 1);\n for (let k = 1; k <= 3; k++)\n anchors.push({\n at: start.clone().addScaledVector(direction, (length * k) / 3),\n yaw,\n });\n }\n for (let k = 0; k < 10; k++)\n anchors.push({\n at: new THREE.Vector3(0.02, (1.0 + k * 0.08) * s, 0.01),\n yaw: k * 2.39996 + seed,\n });\n const leaves = own(\n new THREE.InstancedMesh(leafGeometry, mats.leaf(), anchors.length * 2),\n );\n leaves.castShadow = leaves.receiveShadow = true;\n const matrix = new THREE.Matrix4();\n const rotation = new THREE.Quaternion();\n const euler = new THREE.Euler();\n const color = new THREE.Color();\n let index = 0;\n for (const [a, { at, yaw }] of anchors.entries()) {\n for (const side of [-1, 1]) {\n const k = a + seed * 13;\n const leafYaw = yaw + side * (0.5 + hash(k, side + 2, 3) * 0.6);\n const droop = hash(k, side + 2, 8) < 0.3;\n const pitch = droop\n ? -1.65 - hash(k, side + 2, 1) * 0.3\n : -0.85 - hash(k, side + 2, 1) * 0.55;\n euler.set(pitch, leafYaw, (hash(k, side + 2, 5) - 0.5) * 0.88, 'YXZ');\n rotation.setFromEuler(euler);\n const size = (0.6 + hash(k, side + 2, 2) * 0.6) * Math.max(0.75, s);\n matrix.compose(at, rotation, new THREE.Vector3(size, size, size));\n leaves.setMatrixAt(index, matrix);\n const lit = 0.65 + 0.35 * hash(k, side + 2, 6);\n color.setRGB(lit, lit, lit * 0.88);\n leaves.setColorAt(index, color);\n index++;\n }\n }\n g.add(leaves);\n volume('plant', [0.75 * s, height, 0.75 * s], [0, height / 2, 0], g, 0.4);\n return g;\n}\n\n// Small tabletop plant (no volume).\nfunction smallPlant(\n g: THREE.Object3D,\n { size = 0.22, pot = mats.terracotta() as THREE.Material, seed = 0 } = {},\n) {\n const r = size * 0.32;\n cylinder(r, r * 0.8, size * 0.45, pot, [0, size * 0.225, 0], g, 24);\n const leafGeometry = own(\n new THREE.PlaneGeometry(0.28, 0.38, 2, 3).translate(0, 0.21, 0),\n );\n const leaves = own(new THREE.InstancedMesh(leafGeometry, mats.leaf(), 12));\n leaves.castShadow = true;\n const matrix = new THREE.Matrix4();\n const euler = new THREE.Euler();\n for (let i = 0; i < 12; i++) {\n euler.set(\n -0.4 - hash(i, 1, seed) * 0.8,\n (i / 12) * Math.PI * 2 + seed,\n 0,\n 'YXZ',\n );\n const scale = size * (0.7 + hash(i, 2, seed) * 0.5);\n matrix.compose(\n new THREE.Vector3(0, size * 0.42, 0),\n new THREE.Quaternion().setFromEuler(euler),\n new THREE.Vector3(scale, scale, scale),\n );\n leaves.setMatrixAt(i, matrix);\n }\n g.add(leaves);\n return g;\n}\n\n// ---------------------------------------------------------- floor and walls\n\n// Rug lying on the floor, lit like the floor beneath it.\nfunction rug(\n g: THREE.Object3D,\n {\n width = 2.4,\n depth = 1.7,\n style = 'lattice' as RugStyle,\n field = '#e6ddcc',\n accent = '#5a524a',\n } = {},\n) {\n const material = shellMaterial({\n map: fitted(rugCanvas(width, depth, style, field, accent), width, depth),\n roughness: 1,\n });\n const object = mesh(panel(width, depth), material, [0, 0.006, 0], g, {\n cast: false,\n });\n object.rotation.x = -Math.PI / 2;\n litSurface(object, width, depth);\n return g;\n}\n\ntype ArtStyle = 'abstract' | 'botanical' | 'landscape';\n\n// Framed picture on a wall group (local +Z into the room). The whole frame\n// is the WebXR 'wall art' plane, as a room scan would label it.\nfunction picture(\n g: THREE.Object3D,\n {\n width = 0.9,\n height = 0.65,\n art = 'abstract' as ArtStyle,\n seed = 1,\n frame = mats.blackMetal() as THREE.Material,\n palette = ['#b9673f', '#2c4547', '#d7a24b', '#8d9b85'],\n } = {},\n) {\n box([width, height, 0.03], frame, [0, 0, 0.015], g).userData.xrPlane =\n 'wall art';\n const matBorder = Math.min(width, height) * 0.1;\n mesh(unitPlane, mats.trim(), [0, 0, 0.0305], g, { cast: false }).scale.set(\n width - 0.04,\n height - 0.04,\n 1,\n );\n const w = width - 2 * matBorder;\n const h = height - 2 * matBorder;\n const map =\n art === 'botanical'\n ? botanicalTexture(seed)\n : art === 'landscape'\n ? landscapeTexture(seed, w / h)\n : paintingTexture(seed, palette, w / h);\n mesh(unitPlane, standard({ map, roughness: 0.85 }), [0, 0, 0.031], g, {\n cast: false,\n }).scale.set(w, h, 1);\n return g;\n}\n\n// Mirror on a wall group: round with a brass ring, or rectangular with a\n// wooden frame. A 'wall art' plane.\nfunction mirror(\n g: THREE.Object3D,\n {\n radius = 0.36,\n width = 0,\n height = 0,\n frame = mats.oak() as THREE.Material,\n } = {},\n) {\n if (width && height) {\n box([width, height, 0.03], frame, [0, 0, 0.015], g).userData.xrPlane =\n 'wall art';\n mesh(unitPlane, mats.mirror(), [0, 0, 0.031], g, { cast: false }).scale.set(\n width - 0.08,\n height - 0.08,\n 1,\n );\n } else {\n const glass = mesh(\n own(new THREE.CircleGeometry(radius, 64)),\n mats.mirror(),\n [0, 0, 0.012],\n g,\n { cast: false },\n );\n glass.userData.xrPlane = 'wall art';\n mesh(\n own(new THREE.TorusGeometry(radius + 0.01, 0.012, 12, 96)),\n mats.brass(),\n [0, 0, 0.014],\n g,\n );\n }\n return g;\n}\n\n// Wall-mounted display (screen off). A room scan reports screens as volumes\n// only (no plane).\nfunction wallScreen(g: THREE.Object3D, { width = 1.46, height = 0.84 } = {}) {\n box(\n [width, height, 0.028],\n paintMaterial('#0a0a0a', 0.35, 0.5),\n [0, 0, 0.014],\n g,\n );\n const screen = mesh(unitPlane, mats.screen(), [0, 0, 0.0285], g, {\n cast: false,\n });\n screen.scale.set(width - 0.03, height - 0.03, 1);\n volume('screen', [width, height, 0.04], [0, 0, 0.02], g, 0.3);\n return g;\n}\n\n// Desk monitor on a stand (put `g` on the desk top); a 'screen' volume, as a\n// room scan reports screens.\n// A desk monitor; `tracked: false` leaves out its 'screen' volume (rooms with\n// many monitors stay within the objects a room scan reports).\nfunction monitor(\n g: THREE.Object3D,\n { width = 0.62, height = 0.37, tracked = true } = {},\n) {\n box([0.22, 0.012, 0.16], mats.charcoal(), [0, 0.006, 0], g);\n box([0.04, 0.16, 0.025], mats.charcoal(), [0, 0.09, -0.04], g);\n box(\n [width, height, 0.025],\n paintMaterial('#141414', 0.4),\n [0, 0.12 + height / 2, -0.02],\n g,\n );\n const screen = mesh(\n unitPlane,\n mats.screen(),\n [0, 0.12 + height / 2, -0.007],\n g,\n { cast: false },\n );\n screen.scale.set(width - 0.02, height - 0.03, 1);\n (tracked ? volume : occluder)(\n 'screen',\n [width, height + 0.12, 0.16],\n [0, (height + 0.12) / 2, -0.02],\n g,\n 0.2,\n );\n return g;\n}\n\n// Whiteboard or cork pinboard on a wall group; a 'wall art' plane.\nfunction board(\n g: THREE.Object3D,\n {\n width = 1.2,\n height = 0.9,\n kind = 'white' as 'white' | 'cork',\n seed = 0,\n } = {},\n) {\n box(\n [width, height, 0.02],\n kind === 'white' ? mats.steel() : mats.oak(),\n [0, 0, 0.01],\n g,\n ).userData.xrPlane = 'wall art';\n const surface = mesh(\n unitPlane,\n kind === 'white'\n ? paintMaterial('#f6f6f3', 0.25)\n : standard({ map: corkTexture(), roughness: 0.95 }),\n [0, 0, 0.0205],\n g,\n { cast: false },\n );\n surface.scale.set(width - 0.04, height - 0.04, 1);\n if (kind === 'cork') {\n const papers = ['#f3efe6', '#e7d9c4', '#d9e3d6', '#efe2d4'];\n for (let i = 0; i < 4; i++) {\n const sheet = mesh(\n unitPlane,\n paintMaterial(papers[i], 0.9),\n [\n (hash(i, 1, seed) - 0.5) * (width - 0.35),\n (hash(i, 2, seed) - 0.5) * (height - 0.35),\n 0.022 + i * 0.0005,\n ],\n g,\n { cast: false },\n );\n sheet.scale.set(0.21, 0.28, 1);\n sheet.rotation.z = (hash(i, 3, seed) - 0.5) * 0.15;\n }\n }\n return g;\n}\n\n// Felt acoustic panel on a wall group (no WebXR label).\nfunction acousticPanel(\n g: THREE.Object3D,\n { width = 0.6, height = 1.2, color = '#7d8a6a' } = {},\n) {\n mesh(\n roundedBox(width, height, 0.04, 0.01),\n fabricMaterial(color, 60),\n [0, 0, 0.02],\n g,\n );\n return g;\n}\n\n// ---------------------------------------------------------------------- room\n\n// Open studio: a deliberately empty 6 x 6 m room for fitness, locomotion,\n// large play spaces and baseline plane detection. Oak floor, plain walls.\n//\n// Layout (the viewer starts at the origin facing -Z, on open floor):\n// left wall (-X) one wide, low-sill window; the sun patch lands on the\n// open floor ahead-left of the viewer; a small plant on the sill\n// back wall (-Z) low wooden bench, rolled yoga mat, door, floor plant\n// right wall (+X) tall framed mirror panel\n// front wall (+Z) plain\n// A robot vacuum drives a loop across the open floor.\nconst room = createRoom({\n name: 'open_studio',\n width: 6,\n depth: 6,\n z0: -3.3,\n windows: [\n { wall: 'left', at: 0, width: 2.2, sill: 0.45, head: 2.3, sheers: false },\n ],\n doors: [{ wall: 'back', at: 1.3 }],\n floor: 'oak',\n wall: '#efe4d3',\n sun: { elevation: 32, azimuth: 25 },\n robot: { center: [0.2, -1.4], radius: [1.5, 0.9], speed: 0.3 },\n});\n\n// Warm oak for the bench, a shade richer than the floor.\nconst studioWood = once(() =>\n standard({ map: oakVeneerTexture(), color: '#c9ab8f', roughness: 0.5 }),\n);\n\n// Low slab bench: a thick top on two inset slab legs with a back apron.\nfunction studioBench(\n g: THREE.Object3D,\n { width = 1.2, depth = 0.36, height = 0.45 } = {},\n) {\n const wood = studioWood();\n const top = 0.045;\n const legHeight = height - top;\n mesh(roundedBox(width, top, depth, 0.008), wood, [0, height - top / 2, 0], g);\n for (const s of [-1, 1]) {\n mesh(\n roundedBox(0.05, legHeight, depth - 0.04, 0.006),\n wood,\n [s * (width / 2 - 0.13), legHeight / 2, 0],\n g,\n );\n }\n box(\n [width - 0.31, 0.06, 0.02],\n wood,\n [0, height - top - 0.03, -depth / 2 + 0.05],\n g,\n );\n volume('other', [width, height, depth], [0, height / 2, 0], g, 0.45);\n return g;\n}\n\n// Rolled yoga mat standing on end, with two carry straps (untagged).\nfunction studioYogaMat(\n g: THREE.Object3D,\n { length = 0.61, radius = 0.065, color = '#6d7c5a' } = {},\n) {\n cylinder(\n radius,\n radius,\n length,\n paintMaterial(color, 0.9),\n [0, length / 2, 0],\n g,\n 32,\n );\n for (const y of [length * 0.22, length * 0.78]) {\n cylinder(\n radius + 0.003,\n radius + 0.003,\n 0.025,\n mats.charcoal(),\n [0, y, 0],\n g,\n 32,\n );\n }\n const end = mesh(\n own(new THREE.RingGeometry(radius * 0.25, radius * 0.97, 32)),\n paintMaterial('#56633f', 0.95),\n [0, length + 0.001, 0],\n g,\n { cast: false },\n );\n end.rotation.x = -Math.PI / 2;\n return g;\n}\n\n// Horizontal transom across the window frame, so the sun patch shows a cross.\nfunction studioTransom(at: number, width: number, y: number) {\n const g = room.onWall('left', at, 0);\n box([width - 0.1, 0.045, 0.06], mats.trim(), [0, y, -0.12], g);\n return g;\n}\n\nstudioTransom(0, 2.2, 1.45);\n// Small plant on the window sill, at the front end of the window.\nsmallPlant(group(-0.85, 0.45, -0.02, 0, room.onWall('left', 0, 0)), {\n size: 0.34,\n pot: mats.pot(),\n seed: 4,\n});\n\n// Back wall: bench and yoga mat left of centre, the door, a plant in the corner.\nstudioBench(room.against('back', -1.45, 0.36));\nstudioYogaMat(room.place(-0.55, room.bounds.z0 + 0.1));\nplant(room.place(2.6, room.bounds.z0 + 0.4), { height: 1.6, seed: 1 });\n\n// Right wall: a tall mirror panel.\nmirror(room.onWall('right', -0.6, 1.2), {\n width: 0.85,\n height: 1.75,\n frame: mats.oak(),\n});\n\nroom.finish();\n";export{n as default};