@iwsdk/vite-plugin-dev 1.0.1 → 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="// A sunlit living room, IWER's default AR environment.\n//\n// Everything is procedural and offline: canvas textures, an HDR environment\n// map, baked lightmaps (window light + ambient occlusion, computed\n// analytically at load) and one static sun shadow. Meshes tagged with\n// userData.xrPlane / userData.xrMesh become WebXR planes / meshes; invisible\n// box proxies describe furniture volumes.\n//\n// Layout (meters, the viewer starts at the origin facing -Z):\n// back wall (-Z) sofa, wall art, side table with lamp, floor lamp\n// left wall (-X) window with sheers, armchair, fig tree\n// right wall (+X) media console and TV, bookshelf\n// front wall (+Z) door, console table with mirror, dining nook\n//\n// A robot vacuum drives loops across the open floor: a dynamic part of the\n// \"real world\". Like on real devices it is not a tracked plane/mesh, but it\n// is visible, hit-testable and in depth. It is added after the bake and merge\n// passes so it stays a separate, movable object.\nimport * as THREE from 'three';\nimport { onDispose, onFrame, scene } from '@drawcall/glts';\n\nconst W = 5.0;\nconst D = 5.8;\nconst H = 2.7;\nconst X0 = -W / 2;\nconst X1 = W / 2;\nconst Z0 = -3.4;\nconst Z1 = Z0 + D;\nconst ZC = (Z0 + Z1) / 2;\n\n// Baked lightmap values are irradiance / LIGHTMAP_INTENSITY.\nconst LIGHTMAP_INTENSITY = 2.4;\n\n// Window in the left wall.\nconst WINDOW_Z = -1.35;\nconst WINDOW_WIDTH = 2.1;\nconst SILL = 0.55;\nconst HEAD = 2.35;\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\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\n// Engineered oak: a 2 m x 4 m tile of 20 cm planks, 1-2 m long.\nfunction oakFloor() {\n const planks = 10;\n const lengths = [2, 4 / 3, 2, 1, 4 / 3, 2, 1, 4 / 3, 2, 4 / 3]; // meters\n const shifts = lengths.map((_, i) => hash(i, 3, 7) * 4);\n const [color, rough, bump] = paint(768, 1536, 3, (u, v) => {\n const column = Math.floor(u * planks);\n const across = u * planks - column; // 0..1 across the plank\n const along = mod(v * 4 + shifts[column], 4); // meters along the column\n const row = Math.floor(along / lengths[column]);\n const end = along - row * lengths[column]; // meters into this board\n const seed = column * 31 + row * 7 + 1;\n const gap =\n Math.min(across, 1 - across) * 0.2 < 0.001 ||\n Math.min(end, lengths[column] - end) < 0.0012;\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 ray = fbm(across * 4 + offset, along * 30, seed + 9, 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 + 0.03 * ray);\n const shade = gap ? 0.55 : 1;\n // Roughness varies per board and slowly along it, not per grain line.\n const r = gap ? 0.9 : 0.45 + 0.1 * hash(seed, 4, 4) + 0.05 * fbm(across, along * 0.5 + offset, seed + 11, 2);\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.\nfunction plaster() {\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.\nfunction fabric(seed: number) {\n const threads = 48;\n const [color, bump] = paint(256, 256, 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 return { map: tiled(color, true, 0.1), bumpMap: tiled(bump, false, 0.1) };\n}\n\n// Walnut veneer, 1 m tile, grain along U.\nfunction walnut() {\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// Wool rug: ivory field, charcoal lattice and border.\nfunction rugCanvas(w: number, h: number) {\n const [canvas] = paint(1024, Math.round((1024 * 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 const band = border > 0.1 && border < 0.13;\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 const lattice = border > 0.2 && Math.abs(dx + dy - 0.5) < 0.025;\n if (band || lattice) return [[0.35 * (1 + fiber), 0.31 * (1 + fiber), 0.28 * (1 + fiber)]];\n const base = 0.9 + fiber;\n return [[0.9 * base, 0.87 * base, 0.8 * base]];\n });\n return canvas;\n}\n\n// Abstract painting with soft overlapping shapes.\nfunction paintingTexture() {\n const canvas = document.createElement('canvas');\n canvas.width = 768;\n canvas.height = 512;\n const ctx = canvas.getContext('2d')!;\n ctx.fillStyle = '#e9e2d4';\n ctx.fillRect(0, 0, 768, 512);\n ctx.filter = 'blur(1.5px)';\n const shapes: [string, number, number, number][] = [\n ['#b9673f', 250, 300, 160],\n ['#2c4547', 480, 220, 180],\n ['#d7a24b', 600, 380, 100],\n ['#8d9b85', 340, 150, 110],\n ];\n for (const [fill, x, y, r] of shapes) {\n ctx.globalAlpha = 0.88;\n ctx.fillStyle = fill;\n ctx.beginPath();\n ctx.arc(x, y, r, 0, Math.PI * 2);\n ctx.fill();\n }\n ctx.globalAlpha = 0.85;\n ctx.strokeStyle = '#1d1d1d';\n ctx.lineWidth = 5;\n ctx.beginPath();\n ctx.moveTo(90, 420);\n ctx.bezierCurveTo(260, 130, 520, 520, 690, 100);\n ctx.stroke();\n // Canvas weave.\n const image = ctx.getImageData(0, 0, 768, 512);\n for (let i = 0; i < image.data.length; i += 4) {\n const p = i / 4;\n const weave = ((p % 768) % 3 === 0 ? -6 : 0) + (Math.floor(p / 768) % 3 === 0 ? -6 : 0);\n image.data[i] += weave;\n image.data[i + 1] += weave;\n image.data[i + 2] += weave;\n }\n ctx.putImageData(image, 0, 0);\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n return tex;\n}\n\n// Bright, hazy view out of the window: sky, a tree line, a hedge.\nfunction outsideTexture() {\n const [canvas] = paint(1024, 512, 1, (u, v) => {\n const sky: [number, number, number] = [mix(0.97, 0.9, v), mix(0.98, 0.94, v), mix(0.99, 0.98, v)];\n // A soft band of foliage under a clipped sky, darker towards the bottom.\n const ridge = 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 = [mix(0.42 * t, sky[0], haze), mix(0.52 * t, sky[1], haze), mix(0.36 * t, sky[2], haze)];\n return [[mix(sky[0], green[0], foliage), mix(sky[1], green[1], foliage), mix(sky[2], green[2], foliage)]];\n });\n const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n return tex;\n}\n\n// Fiddle-leaf fig leaf with veins; alpha cut-out.\nfunction leafTexture() {\n const [color, bump] = paint(256, 256, 2, (u, v) => {\n const x = (u - 0.5) * 2;\n // Violin outline: narrow base, slight waist, broad rounded tip.\n const waist = 1 - 0.12 * Math.exp(-Math.pow((v - 0.42) / 0.12, 2));\n const width = 0.96 * Math.pow(Math.sin(Math.PI * Math.pow(Math.min(v, 0.999), 0.5)), 0.6) * (0.5 + 0.5 * v) * waist;\n const inside = Math.abs(x) < width ? 1 : 0;\n const midrib = Math.abs(x) < 0.025 ? 1 : 0;\n const vein = 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 = 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 [0.19 * shade * light, 0.31 * shade * light, 0.12 * shade * light, inside],\n [height, height, height],\n ];\n });\n const map = own(new THREE.CanvasTexture(color));\n map.colorSpace = THREE.SRGBColorSpace;\n return { map, bumpMap: own(new THREE.CanvasTexture(bump)) };\n}\n\n// --------------------------------------------------------- baked lighting\n\n// Furniture boxes (world AABBs) that occlude ambient light on room surfaces.\ntype Occluder = { min: THREE.Vector3; max: THREE.Vector3; strength: number };\nconst occluders: Occluder[] = [];\nconst roomPlanes = [\n { n: new THREE.Vector3(1, 0, 0), d: -X0 },\n { n: new THREE.Vector3(-1, 0, 0), d: X1 },\n { n: new THREE.Vector3(0, 1, 0), d: 0 },\n { n: new THREE.Vector3(0, -1, 0), d: H },\n { n: new THREE.Vector3(0, 0, 1), d: -Z0 },\n { n: new THREE.Vector3(0, 0, -1), d: Z1 },\n];\nconst windowSamples: THREE.Vector3[] = [];\nfor (let i = 0; i < 5; i++) {\n for (let j = 0; j < 3; j++) {\n windowSamples.push(\n new THREE.Vector3(\n X0,\n SILL + ((j + 0.5) / 3) * (HEAD - SILL),\n WINDOW_Z - WINDOW_WIDTH / 2 + ((i + 0.5) / 5) * WINDOW_WIDTH,\n ),\n );\n }\n}\nconst windowSampleArea = (WINDOW_WIDTH * (HEAD - SILL)) / windowSamples.length;\n// Where sunlight through the window lands on the floor; the bright patch\n// bounces warm light onto the ceiling and walls.\nconst SUN_POSITION = new THREE.Vector3(-8.6, 6.7, 0.25);\nconst SUN_TARGET = new THREE.Vector3(-0.6, 0, -1.95);\nconst sunDirection = SUN_TARGET.clone().sub(SUN_POSITION).normalize();\nconst patchSamples = windowSamples\n .map((w) => w.clone().addScaledVector(sunDirection, -w.y / sunDirection.y))\n .filter((f) => f.x > X0 && f.x < X1 && f.z > Z0 && f.z < Z1);\nconst patchSampleArea =\n (WINDOW_WIDTH * (HEAD - SILL) * Math.abs(sunDirection.x)) / -sunDirection.y / windowSamples.length;\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 && p.x < o.max.x + 0.02 &&\n p.y > o.min.y - 0.02 && p.y < o.max.y + 0.02 &&\n p.z > o.min.z - 0.02 && 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 let ao = 1;\n for (const plane of roomPlanes) {\n if (Math.abs(plane.n.dot(n)) > 0.5) continue;\n const distance = Math.max(0, plane.n.dot(p) + plane.d);\n ao *= (1 - 0.45 * Math.exp(-distance / 0.3)) * (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 *= (1 - o.strength * Math.exp(-distance / 0.25)) * (1 - 0.5 * Math.exp(-distance / 0.04));\n }\n return ao;\n}\n\n// Diffuse irradiance (relative units) at p with normal n. Furniture\n// vertices pass `self = true` so the volume containing them is ignored.\nfunction irradiance(p: THREE.Vector3, n: THREE.Vector3, self = false): [number, number, number] {\n const active = self ? occluders.filter((o) => !inside(p, o)) : occluders;\n // Skylight through the window as an area light, shadowed by furniture.\n let sky = 0;\n for (const s of windowSamples) {\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 = -toSample.x;\n if (cosP <= 0 || cosW <= 0) continue;\n if (active.some((o) => blocks(p, s, o))) continue;\n sky += (cosP * cosW * windowSampleArea) / (Math.PI * d2);\n }\n // Bounce from the sun patch on the floor (a Lambertian emitter facing up).\n let patch = 0;\n for (const f of patchSamples) {\n toSample.subVectors(f, 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) patch += (cosP * cosE * patchSampleArea) / (Math.PI * d2);\n }\n const ao = occlusion(p, n, active);\n // Warm multi-bounce ambient: ~100 units of light enter through the window\n // and spread over ~116 m2 of surfaces with albedo ~0.6, giving ~1.3\n // irradiance (dimmer on the ceiling, which only sees bounce light).\n const bounce = (1.2 / 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 (22) x cos(elevation) x albedo (0.45).\n const warm = ((22 * -sunDirection.y * 0.45) / LIGHTMAP_INTENSITY) * patch * (Math.abs(n.y) < 0.5 && p.y < 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 flat mesh whose UVs are its local XY in\n// meters over a centered w x h rectangle.\nfunction bakeLightmap(object: THREE.Object3D, w: number, h: number, texelsPerMeter = 24) {\n object.updateWorldMatrix(true, false);\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(object.matrixWorld);\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(new THREE.DataTexture(data, width, height, THREE.RGBAFormat, THREE.HalfFloatType));\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// ---------------------------------------------------------------- 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(geometry: THREE.BoxGeometry, w: number, h: number, d: number) {\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(w: number, h: number, d: number, r: number, puff = 0, segments = 6) {\n const geometry = own(meterUVs(new THREE.BoxGeometry(w, h, d, segments, segments, segments), w, h, d));\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(w: number, h: number, holes: [number, number, number, number][] = []) {\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 plasterBump = plaster();\nconst oak = oakFloor();\nconst walnutMap = walnut();\nconst walnutMaterial = standard({ map: walnutMap, roughness: 0.5 });\nconst darkWalnut = standard({ map: walnutMap, color: '#8a7a70', roughness: 0.55 });\nconst trimMaterial = standard({ color: '#f3f1ec', roughness: 0.5 });\nconst blackMetal = standard({ color: '#1a1a1a', roughness: 0.4, metalness: 0.85 });\nconst brass = standard({ color: '#c6a062', roughness: 0.28, metalness: 1 });\nconst ceramic = standard({ color: '#ebe6dc', roughness: 0.3 });\nconst stoneware = standard({ color: '#4a4844', roughness: 0.55 });\nconst terracotta = standard({ color: '#a65f40', roughness: 0.85 });\nconst soil = standard({ color: '#2a2019', roughness: 1 });\nconst sofaMaterial = standard({ color: '#7f868b', roughness: 0.95, ...fabric(51), bumpScale: 0.5 });\nconst chairMaterial = standard({ color: '#b2643e', roughness: 0.9, ...fabric(54), bumpScale: 0.5 });\nconst pillowOchre = standard({ color: '#c79e68', roughness: 0.95, ...fabric(52), bumpScale: 0.5 });\nconst pillowLinen = standard({ color: '#e8e2d5', roughness: 0.95, ...fabric(53), bumpScale: 0.5 });\nconst throwMaterial = standard({ color: '#d8cfc0', roughness: 1, ...fabric(55), bumpScale: 1 });\nconst screenMaterial = customizeEnvironment(standard({ color: '#050506', roughness: 0.05, metalness: 0.2, envMapIntensity: 0.3 }), { boxProjected: true });\nconst glassMaterial = standard({ color: '#e6f0f5', roughness: 0.03, transparent: true, opacity: 0.1 });\nconst mirrorMaterial = customizeEnvironment(standard({ color: '#d8dcdc', roughness: 0.15, metalness: 1 }), { boxProjected: true });\nconst outsideMaterial = own(new THREE.MeshBasicMaterial({ map: outsideTexture() }));\noutsideMaterial.color.setScalar(4); // overexposed, like a photo of a window\nconst curtainMaterial = 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, // backlit by the window\n});\nconst lampShadeMaterial = standard({\n color: '#efe4cf',\n roughness: 1,\n side: THREE.DoubleSide,\n emissive: '#ffc985',\n emissiveIntensity: 1.1,\n});\nconst bulbMaterial = own(new THREE.MeshBasicMaterial({ color: '#fff1dc' }));\nbulbMaterial.color.setScalar(5);\nconst bookMaterial = standard({ roughness: 0.8 });\nconst leafMaterial = standard({\n ...leafTexture(),\n bumpScale: 0.6,\n alphaTest: 0.5,\n side: THREE.DoubleSide,\n roughness: 0.45,\n envMapIntensity: 0.12,\n});\nconst potMaterial = standard({ color: '#e4ded3', roughness: 0.85 });\nconst hiddenMaterial = own(new THREE.MeshBasicMaterial({ visible: false }));\n\n// Room surfaces get their indirect light from baked lightmaps, so their\n// environment map only contributes reflections.\nfunction shellMaterial(params: THREE.MeshStandardMaterialParameters) {\n const material = standard({ envMapIntensity: 0.5, lightMapIntensity: LIGHTMAP_INTENSITY, ...params });\n material.shadowSide = THREE.DoubleSide;\n return customizeEnvironment(material, { specularOnly: true });\n}\n\n// ----------------------------------------------------------------- helpers\n\ntype Vec3 = [number, number, number];\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([w, h, d]: Vec3, material: THREE.Material, position: Vec3, parent: THREE.Object3D = scene) {\n return mesh(own(meterUVs(new THREE.BoxGeometry(w, h, d), w, h, d)), material, position, parent);\n}\n\nfunction group(x: number, y: number, z: number, rotationY = 0) {\n const object = new THREE.Group();\n object.position.set(x, y, z);\n object.rotation.y = rotationY;\n scene.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(label: string, [w, h, d]: Vec3, position: Vec3, parent: THREE.Object3D, strength = 0.7) {\n const object = mesh(own(new THREE.BoxGeometry(w, h, d)), hiddenMaterial, position, parent, {\n cast: false,\n receive: false,\n });\n object.userData.xrMesh = label;\n object.updateWorldMatrix(true, false);\n const bounds = new THREE.Box3().setFromObject(object);\n occluders.push({ min: bounds.min, max: bounds.max, strength });\n return object;\n}\n\n// --------------------------------------------------------------- furniture\n// Furniture is built first so its volumes shape the baked lighting.\n\n// Sofa against the back wall.\nconst sofa = group(0, 0, Z0 + 0.52);\n{\n const width = 2.3;\n mesh(roundedBox(width, 0.2, 0.92, 0.04), sofaMaterial, [0, 0.19, 0], sofa);\n mesh(roundedBox(width, 0.52, 0.2, 0.07), sofaMaterial, [0, 0.55, -0.36], sofa);\n for (const s of [-1, 1]) {\n mesh(roundedBox(0.2, 0.38, 0.92, 0.07, 0.008), sofaMaterial, [s * (width / 2 - 0.1), 0.45, 0], sofa);\n for (const z of [-0.36, 0.36]) {\n mesh(own(new THREE.CylinderGeometry(0.016, 0.011, 0.09, 10)), blackMetal, [s * (width / 2 - 0.08), 0.045, z], sofa, { cast: false });\n }\n }\n const seat = (width - 0.4) / 3;\n for (let i = 0; i < 3; i++) {\n const x = -width / 2 + 0.2 + seat * (i + 0.5);\n const cushion = mesh(roundedBox(seat - 0.008, 0.16, 0.68, 0.06, 0.022, 8), sofaMaterial, [x, 0.37, 0.1], sofa);\n cushion.rotation.z = (i - 1) * 0.006;\n const back = mesh(roundedBox(seat - 0.015, 0.46, 0.2, 0.09, 0.025, 8), sofaMaterial, [x, 0.66, -0.2], sofa);\n back.rotation.set(-0.2, 0, (i - 1) * 0.012);\n }\n const ochre = mesh(roundedBox(0.48, 0.48, 0.14, 0.07, 0.045, 8), pillowOchre, [-0.74, 0.67, -0.07], sofa);\n ochre.rotation.set(-0.3, 0.28, 0.14);\n const linen = mesh(roundedBox(0.44, 0.44, 0.13, 0.07, 0.04, 8), pillowLinen, [0.78, 0.66, -0.07], sofa);\n linen.rotation.set(-0.32, -0.32, -0.12);\n // Throw blanket draped over the right arm.\n const throwGeometry = own(new THREE.PlaneGeometry(0.5, 1.0, 12, 30));\n const tp = throwGeometry.getAttribute('position');\n for (let i = 0; i < tp.count; i++) {\n const tx = tp.getX(i);\n const ty = tp.getY(i) + 0.5; // 0..1 along the drape\n const angle = Math.min(ty / 0.45, 1) * Math.PI * 0.95;\n const radius = 0.11;\n const ripple = Math.sin(tx * 30 + ty * 6) * 0.008 + Math.sin(tx * 13) * 0.006;\n const y = ty < 0.45 ? Math.sin(angle) * radius : radius * Math.sin(Math.PI * 0.95) - (ty - 0.45) * 0.9;\n const z = ty < 0.45 ? -Math.cos(angle) * radius : radius * 0.98 + (ty - 0.45) * 0.08;\n tp.setXYZ(i, tx, y, z + ripple);\n }\n throwGeometry.computeVertexNormals();\n const drape = mesh(throwGeometry, throwMaterial, [width / 2 - 0.1, 0.55, 0.05], sofa);\n drape.rotation.y = Math.PI / 2;\n (drape.material as THREE.Material).side = THREE.DoubleSide;\n // A room scan reports a couch as a volume plus an (invisible) seat plane.\n const sofaSeat = mesh(unitPlane, hiddenMaterial, [0, 0.45, 0.1], sofa, { cast: false, receive: false });\n sofaSeat.rotation.x = -Math.PI / 2;\n sofaSeat.scale.set(width - 0.4, 0.66, 1);\n sofaSeat.userData.xrPlane = 'couch';\n volume('couch', [width, 0.86, 0.94], [0, 0.43, 0], sofa, 0.85);\n}\n\n// Side table with a lit lamp, left of the sofa.\nconst sideTable = group(-1.55, 0, Z0 + 0.35);\n{\n mesh(own(new THREE.CylinderGeometry(0.23, 0.23, 0.03, 48)), walnutMaterial, [0, 0.55, 0], sideTable);\n mesh(own(new THREE.CylinderGeometry(0.018, 0.018, 0.54, 12)), blackMetal, [0, 0.27, 0], sideTable);\n mesh(own(new THREE.CylinderGeometry(0.15, 0.16, 0.015, 32)), blackMetal, [0, 0.008, 0], sideTable);\n const base = mesh(own(new THREE.SphereGeometry(0.095, 32, 20)), ceramic, [0, 0.66, 0], sideTable);\n base.scale.y = 1.1;\n mesh(own(new THREE.CylinderGeometry(0.01, 0.01, 0.2, 8)), brass, [0, 0.82, 0], sideTable);\n mesh(own(new THREE.CylinderGeometry(0.13, 0.18, 0.25, 48, 1, true)), lampShadeMaterial, [0, 0.98, 0], sideTable, { cast: false });\n mesh(own(new THREE.SphereGeometry(0.03, 12, 8)), bulbMaterial, [0, 0.93, 0], sideTable, { cast: false, receive: false });\n const glow = new THREE.PointLight('#ffc27a', 1.4, 3.5, 2);\n glow.position.set(0, 0.95, 0);\n sideTable.add(glow);\n volume('lamp', [0.46, 1.1, 0.46], [0, 0.55, 0], sideTable, 0.5);\n}\n\n// Wall art above the sofa.\nconst art = group(0, 1.62, Z0);\n{\n // The whole framed picture is the wall art, as a room scan would label it.\n box([1.22, 0.82, 0.03], blackMetal, [0, 0, 0.015], art).userData.xrPlane = 'wall art';\n mesh(unitPlane, trimMaterial, [0, 0, 0.0305], art, { cast: false }).scale.set(1.18, 0.78, 1);\n const canvas = mesh(unitPlane, standard({ map: paintingTexture(), roughness: 0.85 }), [0, 0, 0.031], art, { cast: false });\n canvas.scale.set(1.02, 0.66, 1);\n}\n\n// Rug and coffee table.\nconst RUG_W = 2.5;\nconst RUG_D = 1.8;\nconst RUG_Z = Z0 + 1.45;\nconst coffee = group(0, 0, Z0 + 1.45);\n{\n const top = mesh(roundedBox(1.15, 0.035, 0.6, 0.015), walnutMaterial, [0, 0.42, 0], coffee);\n top.userData.xrPlane = 'table';\n mesh(roundedBox(1.05, 0.02, 0.5, 0.008), walnutMaterial, [0, 0.12, 0], coffee);\n for (const x of [-0.54, 0.54]) {\n for (const z of [-0.26, 0.26]) {\n mesh(roundedBox(0.032, 0.4, 0.032, 0.008), blackMetal, [x, 0.2, z], coffee);\n }\n }\n const lower = box([0.28, 0.035, 0.21], standard({ color: '#2f3e46', roughness: 0.8 }), [-0.3, 0.454, 0.04], coffee);\n lower.rotation.y = 0.12;\n const upper = box([0.24, 0.028, 0.18], standard({ color: '#e2dacb', roughness: 0.8 }), [-0.29, 0.486, 0.045], coffee);\n upper.rotation.y = -0.06;\n const bowl = mesh(\n own(new THREE.SphereGeometry(0.13, 40, 12, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2)),\n standard({ color: '#3b3a37', roughness: 0.5, side: THREE.DoubleSide }),\n [0.3, 0.495, -0.03],\n coffee,\n );\n bowl.scale.y = 0.5;\n mesh(own(new THREE.SphereGeometry(0.035, 16, 12)), standard({ color: '#d39a3a', roughness: 0.6 }), [0.28, 0.465, -0.02], coffee);\n mesh(own(new THREE.SphereGeometry(0.035, 16, 12)), standard({ color: '#8fa35a', roughness: 0.6 }), [0.33, 0.465, -0.06], coffee);\n mesh(own(new THREE.CylinderGeometry(0.035, 0.045, 0.15, 32)), ceramic, [0.08, 0.512, 0.17], coffee);\n volume('table', [1.15, 0.44, 0.6], [0, 0.22, 0], coffee, 0.45);\n}\n\n// Armchair angled towards the coffee table, by the window.\nconst chair = group(-1.75, 0, -1.25, 1.0);\n{\n mesh(roundedBox(0.78, 0.28, 0.8, 0.06, 0.008), chairMaterial, [0, 0.29, 0], chair);\n mesh(roundedBox(0.66, 0.12, 0.62, 0.05, 0.022, 8), chairMaterial, [0, 0.48, 0.06], chair);\n mesh(roundedBox(0.78, 0.5, 0.14, 0.06, 0.008), chairMaterial, [0, 0.65, -0.33], chair).rotation.x = -0.14;\n for (const s of [-1, 1]) {\n mesh(roundedBox(0.1, 0.22, 0.74, 0.045), chairMaterial, [s * 0.36, 0.55, 0.02], chair);\n for (const z of [-0.32, 0.32]) {\n mesh(roundedBox(0.035, 0.16, 0.035, 0.012), walnutMaterial, [s * 0.32, 0.08, z], chair).rotation.z = s * 0.12;\n }\n }\n // A room scan reports a couch as a volume plus an (invisible) seat plane.\n const chairSeat = mesh(unitPlane, hiddenMaterial, [0, 0.54, 0.06], chair, { cast: false, receive: false });\n chairSeat.rotation.x = -Math.PI / 2;\n chairSeat.scale.set(0.62, 0.58, 1);\n chairSeat.userData.xrPlane = 'couch';\n volume('couch', [0.8, 0.9, 0.82], [0, 0.45, 0], chair, 0.6);\n}\n\n// Fiddle-leaf fig in the front-left corner: a bare trunk, a few short\n// branches, and large near-horizontal leaves clustered towards the top.\nconst plant = group(X0 + 0.38, 0, 0.35);\n{\n mesh(own(new THREE.CylinderGeometry(0.19, 0.155, 0.38, 48)), potMaterial, [0, 0.19, 0], plant);\n mesh(own(new THREE.TorusGeometry(0.185, 0.012, 10, 48)), potMaterial, [0, 0.38, 0], plant).rotation.x = Math.PI / 2;\n mesh(own(new THREE.CylinderGeometry(0.178, 0.178, 0.01, 32)), soil, [0, 0.355, 0], plant);\n const bark = standard({ color: '#5b4835', roughness: 0.9 });\n mesh(own(new THREE.CylinderGeometry(0.014, 0.026, 1.5, 8).translate(0, 0.75, 0)), bark, [0, 0.36, 0], plant);\n\n // Leaf geometry: +Y along the leaf, cupped along the midrib.\n const leafGeometry = own(new THREE.PlaneGeometry(0.28, 0.38, 4, 6));\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\n // Branches: [height on trunk, yaw, length].\n const branches: [number, number, number][] = [\n [1.05, 0.6, 0.42],\n [1.25, 2.6, 0.38],\n [1.45, 4.4, 0.34],\n [1.62, 1.6, 0.26],\n ];\n const twig = own(new THREE.CylinderGeometry(0.007, 0.011, 1, 6).translate(0, 0.5, 0));\n const anchors: { at: THREE.Vector3; yaw: number }[] = [];\n for (const [height, yaw, length] of branches) {\n const start = new THREE.Vector3(0, height, 0);\n const direction = new THREE.Vector3(Math.sin(yaw) * 0.75, 0.66, Math.cos(yaw) * 0.75).normalize();\n const branch = mesh(twig, bark, [start.x, start.y, start.z], plant);\n branch.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);\n branch.scale.set(1, length, 1);\n for (let k = 1; k <= 4; k++) {\n anchors.push({ at: start.clone().addScaledVector(direction, (length * k) / 4), yaw });\n }\n }\n for (let k = 0; k < 12; k++) {\n anchors.push({ at: new THREE.Vector3(0.02, 1.0 + k * 0.075, 0.01), yaw: k * 2.39996 });\n }\n\n const count = anchors.length * 2;\n const leaves = new THREE.InstancedMesh(leafGeometry, leafMaterial, count);\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 leafYaw = yaw + side * (0.5 + hash(a, side + 2, 3) * 0.6);\n // Near horizontal, drooping a little more the further out it is.\n // About a third of the leaves droop below horizontal.\n const droop = hash(a, side + 2, 8) < 0.3;\n const pitch = droop ? -1.65 - hash(a, side + 2, 1) * 0.3 : -0.85 - hash(a, side + 2, 1) * 0.55;\n euler.set(pitch, leafYaw, (hash(a, side + 2, 5) - 0.5) * 0.88, 'YXZ');\n rotation.setFromEuler(euler);\n const s = 0.6 + hash(a, side + 2, 2) * 0.6;\n matrix.compose(at, rotation, new THREE.Vector3(s, s, s));\n leaves.setMatrixAt(index, matrix);\n // Window side (-X) leaves are lighter and yellower; inner ones darker.\n const toWindow = Math.max(0, -Math.sin(leafYaw));\n const lit = 0.6 + 0.3 * hash(a, side + 2, 6) + 0.25 * toWindow;\n color.setRGB(lit * (1 + 0.12 * toWindow), lit, lit * 0.85);\n leaves.setColorAt(index, color);\n index++;\n }\n }\n plant.add(leaves);\n volume('plant', [0.75, 1.95, 0.75], [0, 0.97, 0], plant, 0.4);\n}\n\n// Media console and wall-mounted TV on the right wall.\nconst media = group(X1 - 0.22, 0, -1.4, -Math.PI / 2);\n{\n mesh(roundedBox(1.9, 0.44, 0.42, 0.01), walnutMaterial, [0, 0.3, 0], media);\n const slat = own(new THREE.BoxGeometry(0.02, 0.36, 0.012));\n const slats = new THREE.InstancedMesh(slat, darkWalnut, 62);\n const m = new THREE.Matrix4();\n for (let i = 0; i < 62; i++) {\n slats.setMatrixAt(i, m.makeTranslation(-0.915 + 0.03 * i, 0.3, 0.214));\n }\n slats.receiveShadow = true;\n media.add(slats);\n for (const x of [-0.88, 0.88]) {\n for (const z of [-0.16, 0.16]) {\n mesh(own(new THREE.CylinderGeometry(0.014, 0.01, 0.08, 8)), blackMetal, [x, 0.04, z], media);\n }\n }\n mesh(own(new THREE.CylinderGeometry(0.05, 0.065, 0.26, 32)), stoneware, [-0.72, 0.65, 0.02], media);\n mesh(own(new THREE.CylinderGeometry(0.004, 0.004, 0.3, 4)), standard({ color: '#6b5a40' }), [-0.72, 0.9, 0.02], media).rotation.z = 0.15;\n const speaker = box([0.12, 0.19, 0.12], standard({ color: '#2a2a2a', roughness: 0.7 }), [0.74, 0.615, 0], media);\n speaker.rotation.y = 0.25;\n box([0.3, 0.04, 0.22], standard({ color: '#7a3b2e', roughness: 0.8 }), [0.3, 0.54, 0.02], media);\n volume('shelf', [1.9, 0.52, 0.42], [0, 0.26, 0], media, 0.75);\n}\nconst tv = group(X1 - 0.03, 1.3, -1.4, -Math.PI / 2);\n{\n box([1.46, 0.84, 0.028], standard({ color: '#0a0a0a', roughness: 0.35, metalness: 0.5 }), [0, 0, 0], tv);\n const screen = mesh(unitPlane, screenMaterial, [0, 0, 0.0145], tv, { cast: false });\n screen.scale.set(1.43, 0.81, 1);\n volume('screen', [1.46, 0.84, 0.04], [0, 0, 0], tv, 0.3);\n}\n\n// Bookshelf on the right wall, towards the front.\nconst shelf = group(X1 - 0.18, 0, 0.7, -Math.PI / 2);\n{\n const width = 0.9;\n const height = 1.9;\n for (const x of [-width / 2, width / 2]) mesh(roundedBox(0.025, height, 0.34, 0.004, 0, 8), walnutMaterial, [x, height / 2, 0], shelf);\n box([width, height, 0.012], darkWalnut, [0, height / 2, -0.164], shelf);\n const levels = [0.05, 0.43, 0.81, 1.19, 1.57, 1.89];\n for (const y of levels) mesh(roundedBox(width, 0.025, 0.34, 0.004, 0, 2), walnutMaterial, [0, y, 0], shelf);\n const palette = ['#2f3e46', '#b08d57', '#e3dccf', '#7a3b2e', '#55624a', '#cbb79a', '#3c3c3c', '#8c4f3b'];\n const books = new THREE.InstancedMesh(own(new THREE.BoxGeometry(1, 1, 1)), bookMaterial, 120);\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 let count = 0;\n for (let level = 0; level < 5; level++) {\n let x = -width / 2 + 0.02;\n const y = levels[level] + 0.0125;\n const end = level % 2 ? 0.12 : width / 2 - 0.02;\n while (x < end - 0.03 && count < 120) {\n const thickness = 0.018 + hash(count, 5, 5) * 0.03;\n const height = 0.19 + hash(count, 6, 6) * 0.11;\n const depth = 0.17 + hash(count, 7, 7) * 0.07;\n rotation.setFromAxisAngle(new THREE.Vector3(0, 0, 1), x + thickness > end - 0.05 ? -0.18 : 0);\n matrix.compose(new THREE.Vector3(x + thickness / 2, y + height / 2, 0.03), rotation, new THREE.Vector3(thickness, height, depth));\n books.setMatrixAt(count, matrix);\n color.set(palette[Math.floor(hash(count, 8, 8) * palette.length)]);\n books.setColorAt(count, color.multiplyScalar(0.8 + hash(count, 9, 9) * 0.3));\n x += thickness + 0.0015;\n count++;\n }\n }\n books.count = count;\n shelf.add(books);\n mesh(own(new THREE.SphereGeometry(0.07, 32, 20)), ceramic, [0.28, levels[1] + 0.08, 0], shelf);\n mesh(own(new THREE.CylinderGeometry(0.05, 0.035, 0.18, 24)), terracotta, [0.26, levels[3] + 0.1, 0], shelf);\n box([0.24, 0.3, 0.02], blackMetal, [0.05, levels[4] + 0.16, -0.12], shelf).rotation.x = -0.08;\n volume('shelf', [width, height, 0.34], [0, height / 2, 0], shelf, 0.7);\n}\n\n// Front wall: door, console table with mirror, basket.\nconst door = group(1.45, 0, Z1, Math.PI);\n{\n // A dark backing shows as a 3 mm gap around the slab.\n box([0.86, 2.065, 0.01], standard({ color: '#3a3836', roughness: 1 }), [0, 1.0325, 0.005], door);\n const slab = mesh(roundedBox(0.854, 2.056, 0.04, 0.004, 0, 2), trimMaterial, [0, 1.028, 0.022], door);\n slab.userData.xrPlane = 'door';\n for (const [w, h, x, y] of [\n [0.07, 2.13, -0.465, 1.065],\n [0.07, 2.13, 0.465, 1.065],\n [1.0, 0.07, 0, 2.095],\n ] as const) {\n box([w, h, 0.022], trimMaterial, [x, y, 0.011], door);\n }\n box([0.025, 0.12, 0.012], brass, [0.36, 1.0, 0.05], door);\n mesh(own(new THREE.CylinderGeometry(0.012, 0.012, 0.12, 12)), brass, [0.32, 1.02, 0.07], door).rotation.z = Math.PI / 2;\n}\nconst entry = group(-0.7, 0, Z1, Math.PI);\n{\n mesh(roundedBox(1.1, 0.03, 0.32, 0.008), walnutMaterial, [0, 0.8, 0.17], entry);\n for (const x of [-0.52, 0.52]) {\n for (const z of [0.04, 0.3]) mesh(roundedBox(0.025, 0.79, 0.025, 0.006), blackMetal, [x, 0.395, z], entry);\n }\n const mirror = mesh(own(new THREE.CircleGeometry(0.36, 64)), mirrorMaterial, [0, 1.45, 0.012], entry, { cast: false });\n mirror.userData.xrPlane = 'wall art';\n mesh(own(new THREE.TorusGeometry(0.37, 0.012, 12, 96)), brass, [0, 1.45, 0.014], entry);\n mesh(own(new THREE.CylinderGeometry(0.06, 0.09, 0.3, 32)), ceramic, [-0.32, 0.965, 0.17], entry);\n mesh(own(new THREE.CylinderGeometry(0.17, 0.14, 0.3, 32, 1, true)), standard({ color: '#b8996b', roughness: 1, side: THREE.DoubleSide }), [0.25, 0.15, 0.25], entry);\n volume('table', [1.1, 0.82, 0.34], [0, 0.41, 0.17], entry, 0.45);\n}\n\n// Dining nook behind the viewer: round oak table with two chairs.\nconst dining = group(-0.95, 0, 1.35);\n{\n const oakTop = standard({ map: oak.map, roughness: 0.5 });\n const chairOak = standard({ map: oak.map, color: '#d9c0a5', roughness: 0.55 });\n const top = mesh(own(new THREE.CylinderGeometry(0.45, 0.45, 0.03, 64)), oakTop, [0, 0.74, 0], dining);\n top.userData.xrPlane = 'table';\n mesh(own(new THREE.CylinderGeometry(0.04, 0.05, 0.71, 24)), blackMetal, [0, 0.365, 0], dining);\n mesh(own(new THREE.CylinderGeometry(0.24, 0.26, 0.02, 48)), blackMetal, [0, 0.01, 0], dining);\n mesh(own(new THREE.CylinderGeometry(0.06, 0.04, 0.2, 32)), stoneware, [0.08, 0.855, -0.05], dining);\n volume('table', [0.9, 0.76, 0.9], [0, 0.38, 0], dining, 0.45);\n // Chairs sit toward the window side so neither backs into the entry\n // console against the front wall.\n for (const [angle, seed] of [\n [1.0, 1],\n [Math.PI + 0.85, 2],\n ]) {\n const chair = new THREE.Group();\n chair.position.set(Math.sin(angle) * 0.62, 0, Math.cos(angle) * 0.62);\n chair.rotation.y = angle + Math.PI + (seed - 1.5) * 0.15;\n dining.add(chair);\n mesh(roundedBox(0.44, 0.03, 0.42, 0.012), chairOak, [0, 0.45, 0], chair);\n const back = mesh(roundedBox(0.42, 0.16, 0.025, 0.01), chairOak, [0, 0.76, -0.2], chair);\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(roundedBox(0.025, height, 0.025, 0.008), chairOak, [x, height / 2, z], chair);\n }\n }\n chair.updateWorldMatrix(true, false);\n volume('other', [0.44, 0.85, 0.42], [0, 0.425, 0], chair, 0.4);\n }\n}\n// Doormat inside the door.\nbox([0.75, 0.008, 0.45], standard({ color: '#6e5a44', roughness: 1, ...fabric(56), bumpScale: 1.5 }), [1.45, 0.004, Z1 - 0.4]);\n\n// Floor lamp (switched off) at the right end of the sofa.\nconst floorLamp = group(1.55, 0, Z0 + 0.3);\n{\n mesh(own(new THREE.CylinderGeometry(0.14, 0.15, 0.02, 40)), blackMetal, [0, 0.01, 0], floorLamp);\n mesh(own(new THREE.CylinderGeometry(0.009, 0.009, 1.45, 10)), blackMetal, [0, 0.74, 0], floorLamp);\n const linen = standard({ color: '#d8d0c2', roughness: 0.9, side: THREE.DoubleSide });\n mesh(own(new THREE.CylinderGeometry(0.2, 0.2, 0.3, 48, 1, true)), linen, [0, 1.55, 0], floorLamp);\n const diffuser = mesh(own(new THREE.CircleGeometry(0.19, 40)), standard({ color: '#cfc7b8', roughness: 1 }), [0, 1.67, 0], floorLamp, { cast: false });\n diffuser.rotation.x = Math.PI / 2;\n volume('lamp', [0.4, 1.72, 0.4], [0, 0.86, 0], floorLamp, 0.4);\n}\n\n// Large botanical print on the left wall by the dining nook.\nconst print = group(X0, 1.5, 1.35, Math.PI / 2);\n{\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 // A stem with alternating leaf outlines.\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 % 2 ? 1 : -1;\n const x = 200 + Math.sin(i) * 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 const tex = own(new THREE.CanvasTexture(canvas));\n tex.colorSpace = THREE.SRGBColorSpace;\n box([0.64, 0.94, 0.025], walnutMaterial, [0, 0, 0.0125], print).userData.xrPlane = 'wall art';\n mesh(unitPlane, trimMaterial, [0, 0, 0.0255], print, { cast: false }).scale.set(0.6, 0.9, 1);\n const art = mesh(unitPlane, standard({ map: tex, roughness: 0.9 }), [0, 0, 0.026], print, { cast: false });\n art.scale.set(0.44, 0.66, 1);\n}\n\n// Light switch by the door and a few sockets.\n{\n const plate = standard({ color: '#f4f2ee', roughness: 0.4 });\n const switchPlate = box([0.085, 0.085, 0.01], plate, [0.85, 1.1, Z1 - 0.005], scene);\n switchPlate.rotation.y = Math.PI;\n box([0.025, 0.035, 0.006], plate, [0.85, 1.1, Z1 - 0.012], scene);\n for (const [x, z, rotation] of [\n [-1.15, Z0 + 0.005, 0],\n [X1 - 0.005, -0.45, -Math.PI / 2],\n [X0 + 0.005, 1.4, Math.PI / 2],\n ] as const) {\n const socket = box([0.085, 0.085, 0.01], plate, [x, 0.3, z], scene);\n socket.rotation.y = rotation;\n }\n}\n\n// ------------------------------------------------------------------- shell\n\nfunction shell(geometry: THREE.BufferGeometry, material: THREE.MeshStandardMaterial, position: Vec3, rotation: [number, number], label: string, w: number, h: number) {\n const object = mesh(geometry, material, position, scene, { cast: label !== 'floor' });\n object.rotation.set(rotation[0], rotation[1], 0);\n object.userData.xrPlane = label;\n material.lightMap = bakeLightmap(object, w, h);\n return object;\n}\n\nconst wallParams = { color: '#eeeae3', roughness: 0.9, bumpMap: plasterBump, bumpScale: 0.12 };\nshell(panel(W, D), customizeEnvironment(shellMaterial({ ...oak, bumpScale: 0.15, roughness: 1, envMapIntensity: 0.5 }), { boxProjected: true, specularOnly: true }), [0, 0, ZC], [-Math.PI / 2, 0], 'floor', W, D);\nshell(panel(W, D), shellMaterial({ color: '#f7f4ef', roughness: 0.95 }), [0, H, ZC], [Math.PI / 2, 0], 'ceiling', W, D);\nconst windowLocalX = -(WINDOW_Z - ZC);\n// Walls overlap the floor, ceiling and each other slightly so no seam\n// shows a hairline.\nconst SEAM = 0.004;\nshell(\n panel(D + SEAM, H + SEAM, [[windowLocalX - WINDOW_WIDTH / 2, SILL - H / 2, windowLocalX + WINDOW_WIDTH / 2, HEAD - H / 2]]),\n shellMaterial(wallParams),\n [X0, H / 2, ZC],\n [0, Math.PI / 2],\n 'wall',\n D + SEAM,\n H + SEAM,\n);\nshell(panel(D + SEAM, H + SEAM), shellMaterial(wallParams), [X1, H / 2, ZC], [0, -Math.PI / 2], 'wall', D + SEAM, H + SEAM);\nshell(panel(W + SEAM, H + SEAM), shellMaterial(wallParams), [0, H / 2, Z0], [0, 0], 'wall', W + SEAM, H + SEAM);\nshell(panel(W + SEAM, H + SEAM), shellMaterial(wallParams), [0, H / 2, Z1], [0, Math.PI], 'wall', W + SEAM, H + SEAM);\n\n// Shadow-only shell: thick boxes around the room (with the window opening),\n// reaching 3 cm into it, so no sunlight leaks in where the thin wall and\n// ceiling planes meet. They write neither color nor depth and ignore\n// hit-test rays.\n{\n const caster = own(new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false }));\n // Front faces must cast too, so points just inside a slab are shadowed.\n caster.shadowSide = THREE.DoubleSide;\n const slab = (min: Vec3, max: Vec3) => {\n const size: Vec3 = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];\n const object = box(size, caster, [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]);\n object.receiveShadow = false;\n object.userData.shadowOnly = true;\n };\n const t = 0.2;\n const inset = 0.03;\n const zw0 = WINDOW_Z - WINDOW_WIDTH / 2;\n const zw1 = WINDOW_Z + WINDOW_WIDTH / 2;\n slab([X0 - 0.4, H - inset, Z0 - 0.4], [X1 + 0.4, H + t, Z1 + 0.4]);\n slab([X1 - inset, -0.1, Z0 - 0.4], [X1 + t, H + t, Z1 + 0.4]);\n slab([X0 - 0.4, -0.1, Z0 - t], [X1 + 0.4, H + t, Z0 + inset]);\n slab([X0 - 0.4, -0.1, Z1 - inset], [X1 + 0.4, H + t, Z1 + t]);\n // Left wall, outside the window reveal, around the opening.\n const x0 = X0 - 0.2 - t;\n const x1 = X0 - 0.2;\n slab([x0, -0.1, Z0 - 0.4], [x1, SILL, Z1 + 0.4]);\n slab([x0, HEAD, Z0 - 0.4], [x1, H + t, Z1 + 0.4]);\n slab([x0, SILL, Z0 - 0.4], [x1, HEAD, zw0]);\n slab([x0, SILL, zw1], [x1, HEAD, Z1 + 0.4]);\n}\n\n// Rug, lit like the floor beneath it.\n{\n const rug = mesh(panel(RUG_W, RUG_D), shellMaterial({ map: fitted(rugCanvas(RUG_W, RUG_D), RUG_W, RUG_D), roughness: 1 }), [0, 0.006, RUG_Z], scene, { cast: false });\n rug.rotation.x = -Math.PI / 2;\n (rug.material as THREE.MeshStandardMaterial).lightMap = bakeLightmap(rug, RUG_W, RUG_D);\n}\n\n// Baseboards.\nfor (const [x, z, length, rotation] of [\n [X0, ZC, D, Math.PI / 2],\n [X1, ZC, D, -Math.PI / 2],\n [0, Z0, W, 0],\n [0, Z1, W, Math.PI],\n] as const) {\n box([length, 0.09, 0.014], trimMaterial, [0, 0.045, 0.007], group(x, 0, z, rotation));\n}\n\n// Window: reveal, frame, glass, the view outside, sheers.\nconst win = group(X0, 0, WINDOW_Z, Math.PI / 2);\n{\n const reveal = 0.16;\n const revealMaterial = shellMaterial({ ...wallParams, lightMapIntensity: 0 });\n revealMaterial.envMapIntensity = 0.6;\n box([0.02, HEAD - SILL, reveal], revealMaterial, [-WINDOW_WIDTH / 2 - 0.01, (SILL + HEAD) / 2, -reveal / 2], win);\n box([0.02, HEAD - SILL, reveal], revealMaterial, [WINDOW_WIDTH / 2 + 0.01, (SILL + HEAD) / 2, -reveal / 2], win);\n box([WINDOW_WIDTH, 0.02, reveal], revealMaterial, [0, HEAD + 0.01, -reveal / 2], win);\n box([WINDOW_WIDTH + 0.12, 0.03, reveal + 0.06], trimMaterial, [0, SILL - 0.015, -reveal / 2 + 0.03], win);\n const frameZ = -reveal + 0.04;\n box([WINDOW_WIDTH, 0.05, 0.06], trimMaterial, [0, SILL + 0.025, frameZ], win);\n box([WINDOW_WIDTH, 0.05, 0.06], trimMaterial, [0, HEAD - 0.025, frameZ], win);\n box([0.05, HEAD - SILL, 0.06], trimMaterial, [-WINDOW_WIDTH / 2 + 0.025, (SILL + HEAD) / 2, frameZ], win);\n box([0.05, HEAD - SILL, 0.06], trimMaterial, [WINDOW_WIDTH / 2 - 0.025, (SILL + HEAD) / 2, frameZ], win);\n box([0.06, HEAD - SILL, 0.06], trimMaterial, [0, (SILL + HEAD) / 2, frameZ], win);\n const glass = mesh(unitPlane, glassMaterial, [0, (SILL + HEAD) / 2, frameZ], win, { cast: false, receive: false });\n glass.scale.set(WINDOW_WIDTH, HEAD - SILL, 1);\n // The WebXR plane is flush with the wall, as a room scan reports it.\n const windowPlane = mesh(unitPlane, hiddenMaterial, [0, (SILL + HEAD) / 2, 0.002], win, { cast: false, receive: false });\n windowPlane.scale.set(WINDOW_WIDTH, HEAD - SILL, 1);\n windowPlane.userData.xrPlane = 'window';\n const view = mesh(unitPlane, outsideMaterial, [0, 1.3, -4], win, { cast: false, receive: false });\n view.userData.xrGlobalMesh = false; // outside the room, not scanned\n view.scale.set(12, 6, 1);\n // Brass rod and gathered sheers.\n mesh(own(new THREE.CylinderGeometry(0.012, 0.012, WINDOW_WIDTH + 1, 12)), brass, [0, HEAD + 0.15, 0.1], win).rotation.z = Math.PI / 2;\n for (const [x, seed] of [\n [-WINDOW_WIDTH / 2 - 0.22, 1],\n [WINDOW_WIDTH / 2 + 0.22, 4],\n ]) {\n const height = HEAD + 0.13;\n const geometry = own(new THREE.PlaneGeometry(0.62, height, 72, 12));\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; // 0 bottom .. 1 top\n // ~11 cm folds with a slowly varying period; valleys are shaded.\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, { cast: false });\n }\n}\n\n// Recessed downlights (off during the day): trim ring and lens.\nconst ringGeometry = own(new THREE.RingGeometry(0.045, 0.062, 32));\nconst lensGeometry = own(new THREE.CircleGeometry(0.045, 32));\nconst lensMaterial = standard({ color: '#dcd7ce', roughness: 0.3 });\nfor (const [x, z] of [\n [-1.1, -2.2],\n [1.1, -2.2],\n [-1.1, 0.6],\n [1.1, 0.6],\n]) {\n mesh(ringGeometry, trimMaterial, [x, H - 0.002, z], scene, { cast: false }).rotation.x = Math.PI / 2;\n mesh(lensGeometry, lensMaterial, [x, H - 0.004, z], scene, { cast: false }).rotation.x = Math.PI / 2;\n}\n\n// Bake ambient occlusion into furniture as vertex colors (and instance\n// colors): darker near the floor and next to other furniture. Directional\n// light comes from the environment probe, so it is not baked here.\n{\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(p, n, occluders.filter((o) => !inside(p, o)));\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 !m.isMeshStandardMaterial || m === trimMaterial || m.transparent || !m.visible || m.lightMap || m.emissive.getHex() !== 0;\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)) 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) return;\n if (target.geometry.getAttribute('color')) return;\n const count = target.geometry.getAttribute('position').count;\n target.geometry.setAttribute('color', new THREE.BufferAttribute(new Float32Array(count * 3).fill(1), 3));\n });\n}\n\n// Merge static meshes that share a material into one draw call each.\n// Labelled meshes stay separate so they remain WebXR planes / meshes.\n{\n scene.updateMatrixWorld(true);\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) 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 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 const normalMatrix = new THREE.Matrix3();\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((sum, m) => sum + m.geometry.getAttribute('position').count, 0);\n const arrays = Object.fromEntries(\n names.map((name) => [name, new Float32Array(vertexCount * meshes[0].geometry.getAttribute(name).itemSize)]),\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 normalMatrix.getNormalMatrix(m.matrixWorld);\n for (const name of names) {\n const attribute = geometry.getAttribute(name);\n arrays[name].set(attribute.array as Float32Array, base * attribute.itemSize);\n }\n const index = geometry.getIndex();\n const count = geometry.getAttribute('position').count;\n if (index) for (let i = 0; i < index.count; i++) 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(name, new THREE.BufferAttribute(arrays[name], meshes[0].geometry.getAttribute(name).itemSize));\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// 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, window and sun patch.\nconst PROBE = new THREE.Vector3(0, 1.3, ZC);\nfunction roomEnvironment() {\n const width = 96;\n const height = 48;\n const data = new Float32Array(width * height * 4);\n const d = new THREE.Vector3();\n const hit = new THREE.Vector3();\n const n = new THREE.Vector3();\n const toWindow = new THREE.Vector3();\n const room = { min: new THREE.Vector3(X0, 0, Z0), max: new THREE.Vector3(X1, H, Z1), strength: 0 };\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]) 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(Math.cos(theta) * Math.cos(phi), Math.sin(theta), Math.cos(theta) * Math.sin(phi));\n let t = exit(room);\n let albedo = [0, 0, 0];\n let furniture: Occluder | undefined;\n for (const o of 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 // Inward normal of the face that was hit.\n const box = furniture ?? room;\n const sign = furniture ? 1 : -1;\n if (Math.abs(hit.x - box.min.x) < 1e-3) n.set(-sign, 0, 0);\n else if (Math.abs(hit.x - box.max.x) < 1e-3) n.set(sign, 0, 0);\n else if (Math.abs(hit.y - box.min.y) < 1e-3) n.set(0, -sign, 0);\n else if (Math.abs(hit.y - box.max.y) < 1e-3) n.set(0, sign, 0);\n else if (Math.abs(hit.z - box.min.z) < 1e-3) n.set(0, 0, -sign);\n else n.set(0, 0, sign);\n let rgb: number[];\n const inWindow =\n !furniture && n.x > 0.5 && hit.y > SILL && hit.y < HEAD && Math.abs(hit.z - WINDOW_Z) < WINDOW_WIDTH / 2;\n if (inWindow) {\n rgb = [3.2, 3.4, 3.6];\n } else {\n if (furniture) albedo = [0.3, 0.28, 0.26];\n else if (n.y > 0.5) albedo = [0.4, 0.27, 0.15];\n else if (n.y < -0.5) albedo = [0.9, 0.87, 0.83];\n else albedo = [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 // Sunlit floor: trace back towards the sun through the window.\n if (!furniture && n.y > 0.5) {\n toWindow.copy(hit).addScaledVector(sunDirection, (X0 - hit.x) / sunDirection.x);\n if (toWindow.y > SILL && toWindow.y < HEAD && Math.abs(toWindow.z - WINDOW_Z) < WINDOW_WIDTH / 2) {\n const sun = (22 * -sunDirection.y * 0.45) / Math.PI;\n rgb = [rgb[0] + sun, rgb[1] + sun * 0.86, rgb[2] + sun * 0.67];\n }\n }\n }\n data.set([rgb[0], rgb[1], rgb[2], 1], (y * width + x) * 4);\n }\n }\n const tex = own(new THREE.DataTexture(data, width, height, THREE.RGBAFormat, THREE.FloatType));\n tex.mapping = THREE.EquirectangularReflectionMapping;\n tex.magFilter = THREE.LinearFilter;\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) console.warn('Box-projected reflections are not supported by this three.js version');\n chunk = patched;\n }\n if (specularOnly) {\n chunk = chunk.replace('return PI * envMapColor.rgb * envMapIntensity;', 'return vec3( 0.0 );');\n }\n material.onBeforeCompile = (shader) => {\n shader.uniforms.boxMin = { value: new THREE.Vector3(X0, 0, Z0) };\n shader.uniforms.boxMax = { value: new THREE.Vector3(X1, H, Z1) };\n shader.uniforms.probePosition = { value: PROBE };\n shader.vertexShader = shader.vertexShader\n .replace('#include <common>', '#include <common>\\nvarying vec3 vBoxWorldPosition;')\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 = () => `environment:${boxProjected}:${specularOnly}`;\n return material;\n}\n\n// ---------------------------------------------------------------- lighting\n\nscene.background = new THREE.Color('#e6e1d8');\nscene.environment = roomEnvironment();\nscene.environmentIntensity = 1.2;\n\n// Afternoon sun through the window: a static shadow, rendered once.\nconst sun = new THREE.DirectionalLight('#ffdcaa', 22);\n// Aimed so the window's light patch lands on the rug and the armchair.\nsun.target.position.copy(SUN_TARGET);\nsun.position.copy(SUN_POSITION);\nsun.castShadow = true;\nsun.shadow.mapSize.set(2048, 2048);\n// Fit the shadow frustum tightly around the room (outside it would be lit).\n{\n const view = new THREE.Matrix4().lookAt(SUN_POSITION, SUN_TARGET, new THREE.Vector3(0, 1, 0));\n view.setPosition(SUN_POSITION).invert();\n const bounds = new THREE.Box3();\n for (const x of [X0 - 0.3, X1]) {\n for (const y of [0, H]) {\n for (const z of [Z0, Z1]) 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}\nsun.shadow.bias = -0.0002;\nsun.shadow.normalBias = 0.02;\nsun.shadow.radius = 0.8;\nsun.shadow.autoUpdate = false;\nsun.shadow.needsUpdate = true;\nscene.add(sun, sun.target);\n\nscene.rendering.shadows = true;\nscene.rendering.toneMapping = THREE.AgXToneMapping;\nscene.rendering.toneMappingExposure = 0.95;\n\n// ------------------------------------------------------------ robot vacuum\n\nconst robot = new THREE.Group();\nrobot.name = 'robot';\n// It moves, so it is not part of the room's global mesh.\nrobot.userData.xrGlobalMesh = false;\nscene.add(robot);\n{\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 );\n mesh(own(new THREE.TorusGeometry(0.17, 0.012, 8, 48)), standard({ color: '#4a4a4c', roughness: 0.6 }), [0, 0.03, 0], robot).rotation.x = Math.PI / 2;\n mesh(own(new THREE.CylinderGeometry(0.045, 0.045, 0.025, 32)), standard({ color: '#3a3a3c', roughness: 0.4 }), [0, 0.095, 0.06], robot);\n mesh(own(new THREE.CircleGeometry(0.008, 12)), bulbMaterial, [0.05, 0.0835, -0.1], robot, { cast: false }).rotation.x = -Math.PI / 2;\n // Soft contact shadow that travels with it.\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(new THREE.MeshBasicMaterial({ color: 'black', alphaMap: own(new THREE.CanvasTexture(canvas)), transparent: true, opacity: 0.45, depthWrite: false })),\n [0, 0.008, 0],\n robot,\n { cast: false, receive: false },\n );\n shadow.rotation.x = -Math.PI / 2;\n}\n// An elliptical loop through the open floor between the sofa area and the\n// dining nook.\nlet robotTime = 0;\nfunction placeRobot() {\n const angle = robotTime * 0.35;\n robot.position.set(0.35 + Math.cos(angle) * 1.1, 0, 0.15 + Math.sin(angle) * 0.45);\n // Face along the path (the robot's front is -Z).\n robot.rotation.y = Math.atan2(Math.sin(angle) * 1.1, -Math.cos(angle) * 0.45);\n}\nplaceRobot();\nonFrame((delta) => {\n robotTime += delta;\n placeRobot();\n});\n\n";export{n as default};
@@ -0,0 +1 @@
1
+ export{s as startIwsdkDevRuntime}from"./chunks/injection-template-9pnR-F15.js";
@@ -6,6 +6,29 @@
6
6
  */
7
7
  import type { ProcessedDevOptions, InjectionBundleResult } from './types.js';
8
8
  /**
9
- * Load and customize the pre-built injection bundle
9
+ * Module id prefix of the pre-built runtime (dist/injection/) and its lazy
10
+ * chunks (GLTS, rooms). The plugin resolves and loads these ids itself, so
11
+ * Vite serves them in development and bundles them (dynamic imports becoming
12
+ * lazy chunks) in production builds.
13
+ */
14
+ export declare const INJECTION_RUNTIME_ID_PREFIX = "virtual:iwsdk-dev-runtime/";
15
+ /**
16
+ * Locate the pre-built emulator runtime (an ES module with lazy chunks) and
17
+ * capture the configuration it starts with.
10
18
  */
11
19
  export declare function buildInjectionBundle(options: ProcessedDevOptions): Promise<InjectionBundleResult>;
20
+ /**
21
+ * Source of the module the plugin injects into the page: it imports the
22
+ * runtime and starts it with the configuration.
23
+ */
24
+ export declare function createInjectionModuleSource(bundle: InjectionBundleResult): string;
25
+ /**
26
+ * Resolves a runtime module id (or a relative import from one) to its
27
+ * resolved id, or returns null for anything else.
28
+ */
29
+ export declare function resolveInjectionRuntimeId(id: string, importer: string | undefined): string | null;
30
+ /**
31
+ * The runtime file a resolved runtime module id refers to, or null if the id
32
+ * is not one or points outside the runtime folder.
33
+ */
34
+ export declare function resolveInjectionRuntimeFile(bundle: InjectionBundleResult, resolvedId: string): string | null;
@@ -4,4 +4,6 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- export {};
7
+ import type { ProcessedDevOptions } from './types.js';
8
+ /** Starts the emulator runtime; the plugin's injected module passes the config. */
9
+ export declare function startIwsdkDevRuntime(config: ProcessedDevOptions): void;
package/dist/types.d.ts CHANGED
@@ -4,16 +4,18 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
+ import type { ProjectEmulatorEnvironment } from '@iwsdk/core/project';
7
8
  /**
8
9
  * Synthetic Environment Module configuration
9
10
  * @deprecated Use `emulator.environment` instead
10
11
  */
11
12
  export interface SEMOptions {
12
13
  /**
13
- * Default scene to load
14
- * @default 'living_room'
14
+ * Default room to load: one of IWER SEM's built-in rooms. Legacy capture
15
+ * room ids load the room that replaces them.
16
+ * @default 'sunlit_living_room'
15
17
  */
16
- defaultScene?: 'living_room' | 'meeting_room' | 'music_room' | 'office_large' | 'office_small';
18
+ defaultScene?: ProjectEmulatorEnvironment;
17
19
  }
18
20
  export type AiMode = 'agent' | 'collaborate';
19
21
  export interface TargetDevicePreviewOptions {
@@ -97,10 +99,14 @@ export interface EmulatorOptions {
97
99
  */
98
100
  activation?: 'localhost' | 'always' | RegExp;
99
101
  /**
100
- * Synthetic environment to load in the emulator
102
+ * Room to load in the emulator: one of IWER SEM's built-in rooms
103
+ * ('sunlit_living_room', 'home_office', 'conference_room', 'open_office',
104
+ * 'kitchen', 'bedroom', 'music_studio', 'open_studio'). The legacy capture
105
+ * room ids ('living_room', 'meeting_room', 'music_room', 'office_large',
106
+ * 'office_small') are deprecated and load the room that replaces each.
101
107
  * @default undefined (no environment)
102
108
  */
103
- environment?: 'living_room' | 'meeting_room' | 'music_room' | 'office_large' | 'office_small';
109
+ environment?: ProjectEmulatorEnvironment;
104
110
  /**
105
111
  * Inject script during build phase (in addition to dev)
106
112
  * @default false
@@ -258,6 +264,12 @@ export type ProcessedIWEROptions = ProcessedDevOptions;
258
264
  * Injection bundle result
259
265
  */
260
266
  export interface InjectionBundleResult {
261
- code: string;
267
+ /** The pre-built runtime entry (dist/injection/runtime.js). */
268
+ entryPath: string;
269
+ /** Its folder, which also holds the lazy chunks (GLTS, rooms). */
270
+ directory: string;
271
+ /** The configuration the runtime starts with, as JSON. */
272
+ config: string;
273
+ /** Bytes the page loads up front: the entry and its static imports. */
262
274
  size: number;
263
275
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iwsdk/vite-plugin-dev",
3
- "version": "1.0.1",
3
+ "version": "1.1.0-rc.0",
4
4
  "type": "module",
5
5
  "description": "Vite plugin for IWSDK development — XR emulation, AI agent tooling, and Playwright browser",
6
6
  "main": "dist/index.js",
@@ -43,7 +43,7 @@
43
43
  "license": "MIT",
44
44
  "dependencies": {
45
45
  "@drawcall/uikitml": "0.1.8",
46
- "@iwer/devui": "^2.5.0",
46
+ "@iwer/devui": "^2.6.0",
47
47
  "@preact/signals-core": "^1.12.1",
48
48
  "@vitejs/plugin-basic-ssl": "^2.3.0",
49
49
  "lucide": "^0.468.0",
@@ -51,18 +51,18 @@
51
51
  "playwright": "^1.58.2",
52
52
  "preact": "^10.29.7",
53
53
  "sharp": "^0.35.4",
54
- "three": "npm:super-three@0.181.0",
54
+ "three": "npm:super-three@0.185.0",
55
55
  "three-viewport-gizmo": "^2.2.0",
56
56
  "ws": "^8.21.1",
57
- "@iwsdk/core": "1.0.1",
58
- "@iwsdk/scene-composition": "1.0.1"
57
+ "@iwsdk/scene-composition": "1.1.0-rc.0",
58
+ "@iwsdk/core": "1.1.0-rc.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@iwer/sem": "^2.5.0",
61
+ "@iwer/sem": "^2.6.0",
62
62
  "@types/ws": "^8.5.13",
63
- "iwer": "^2.5.0",
63
+ "iwer": "^2.6.0",
64
64
  "vitest": "^4.1.10",
65
- "@iwsdk/cli": "1.0.1"
65
+ "@iwsdk/cli": "1.1.0-rc.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "vite": "^7.0.0"