@selvajs/compute 3.1.0-beta.9 → 3.1.1
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.
- package/LICENSE +21 -0
- package/dist/chunk-FQKQISPG.cjs +2 -0
- package/dist/chunk-FQKQISPG.cjs.map +1 -0
- package/dist/chunk-H3FZW6OX.cjs +4 -0
- package/dist/chunk-H3FZW6OX.cjs.map +1 -0
- package/dist/chunk-N2WCSETE.js +120 -0
- package/dist/chunk-N2WCSETE.js.map +1 -0
- package/dist/chunk-RFE763NG.cjs +120 -0
- package/dist/chunk-RFE763NG.cjs.map +1 -0
- package/dist/chunk-S3VUIIRE.js +2 -0
- package/dist/chunk-S3VUIIRE.js.map +1 -0
- package/dist/chunk-Y3M7P3BW.js +4 -0
- package/dist/chunk-Y3M7P3BW.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +22 -1
- package/dist/core.d.ts +22 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +22 -2
- package/dist/grasshopper.d.ts +22 -2
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{types-Dtok-mVq.d.ts → types-4FMvnx2j.d.ts} +14 -1
- package/dist/{types-C8XWc4Ab.d.cts → types-BpOl6U02.d.cts} +14 -1
- package/dist/visualization-E6BTQZCA.cjs +2 -0
- package/dist/visualization-E6BTQZCA.cjs.map +1 -0
- package/dist/visualization-HDBKPJGQ.js +2 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +331 -29
- package/dist/visualization.d.ts +331 -29
- package/dist/visualization.js +1 -1
- package/package.json +56 -35
- package/dist/chunk-CUQQ3ZBV.cjs +0 -4
- package/dist/chunk-CUQQ3ZBV.cjs.map +0 -1
- package/dist/chunk-GFY3L653.cjs +0 -62
- package/dist/chunk-GFY3L653.cjs.map +0 -1
- package/dist/chunk-MJOXUCDH.js +0 -62
- package/dist/chunk-MJOXUCDH.js.map +0 -1
- package/dist/chunk-WPB2LKCD.js +0 -4
- package/dist/chunk-WPB2LKCD.js.map +0 -1
- package/dist/chunk-WWD655BZ.cjs +0 -2
- package/dist/chunk-WWD655BZ.cjs.map +0 -1
- package/dist/chunk-YREXY7GT.js +0 -2
- package/dist/chunk-YREXY7GT.js.map +0 -1
- package/dist/visualization-4PVR5P7N.js +0 -2
- package/dist/visualization-LS3Z7Q3N.cjs +0 -2
- package/dist/visualization-LS3Z7Q3N.cjs.map +0 -1
- /package/dist/{visualization-4PVR5P7N.js.map → visualization-HDBKPJGQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/features/visualization/threejs/three-materials.ts","../src/features/visualization/threejs/up-axis.ts","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/camera-controller.ts","../src/features/visualization/threejs/grid.ts","../src/features/visualization/threejs/view-gizmo.ts","../src/features/visualization/threejs/edges.ts","../src/features/visualization/threejs/edge-extract.ts","../src/features/visualization/threejs/edge-detection-pass.ts","../src/features/visualization/threejs/render-pipeline.ts","../src/features/visualization/threejs/label-layer.ts","../src/features/visualization/threejs/measure.ts","../src/features/visualization/webdisplay/texture-cache.ts","../src/features/visualization/threejs/three-initializer.ts","../src/features/visualization/threejs/near-plane.ts","../src/features/visualization/types.ts","../src/features/visualization/display-items/display-items-parser.ts","../src/features/visualization/coordinate-transform.ts","../src/features/visualization/webdisplay/binary-parser.ts","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/geometry-cache.ts","../src/features/visualization/webdisplay/mesh-assembly.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"sourcesContent":["import * as THREE from 'three';\n\nexport const EMISSIVE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: 0x000000,\n\temissive: new THREE.Color(0xffffff),\n\temissiveIntensity: 5,\n\tmetalness: 0.0,\n\troughness: 0.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\tdepthWrite: true,\n\tdepthTest: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const METAL_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x000000),\n\tmetalness: 0.9,\n\troughness: 0.3,\n\tenvMapIntensity: 1.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\treflectivity: 1,\n\tior: 2.5,\n\tthickness: 1,\n\tdepthWrite: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const CONCRETE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xcccccc),\n\tmetalness: 0.0,\n\troughness: 0.92,\n\tenvMapIntensity: 0.15,\n\tclearcoat: 0.05,\n\tclearcoatRoughness: 0.9,\n\treflectivity: 0.15,\n\ttransmission: 0.0,\n\tior: 1.45,\n\tthickness: 0.0,\n\tdepthWrite: true,\n\ttransparent: false,\n\t// No alphaTest: concrete has no alpha map, and a nonzero alphaTest needlessly switches the\n\t// shader onto the alpha-test path.\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const PLASTIC_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff), // Default white plastic\n\tmetalness: 0.0,\n\troughness: 0.3,\n\tenvMapIntensity: 0.5,\n\tclearcoat: 0.5,\n\tclearcoatRoughness: 0.1,\n\treflectivity: 0.5,\n\tior: 1.4,\n\ttransmission: 0.0,\n\ttransparent: false,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const GLASS_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff),\n\tmetalness: 0.0,\n\troughness: 0.0,\n\t// Transmission alone models the see-through look; stacking a low `opacity` on top would\n\t// attenuate twice and render glass much darker than intended (opacity stays at its default 1).\n\ttransmission: 0.95,\n\ttransparent: true,\n\t// A depth-writing transparent DoubleSide surface culls whatever sorts behind it — objects\n\t// behind glass would intermittently vanish depending on draw order.\n\tdepthWrite: false,\n\tenvMapIntensity: 1.0,\n\tclearcoat: 1.0,\n\tclearcoatRoughness: 0.0,\n\tior: 1.52,\n\treflectivity: 0.9,\n\tthickness: 1.0,\n\tside: THREE.DoubleSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const RUBBER_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x1a1a1a),\n\tmetalness: 0.0,\n\troughness: 0.9,\n\tenvMapIntensity: 0.2,\n\tclearcoat: 0.1,\n\tclearcoatRoughness: 0.8,\n\treflectivity: 0.2,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const WOOD_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x885533),\n\tmetalness: 0.0,\n\troughness: 0.7,\n\tenvMapIntensity: 0.3,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.4,\n\treflectivity: 0.3,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\n/** Shared singleton materials; must not be disposed (rebuilds shaders, frees textures). */\nexport const SHARED_MATERIALS: ReadonlySet<THREE.Material> = new Set<THREE.Material>([\n\tEMISSIVE_MATERIAL,\n\tMETAL_MATERIAL,\n\tCONCRETE_MATERIAL,\n\tPLASTIC_MATERIAL,\n\tGLASS_MATERIAL,\n\tRUBBER_MATERIAL,\n\tWOOD_MATERIAL\n]);\n","import * as THREE from 'three';\n\n/**\n * The single source of truth for \"which way is up, and what do front/right mean\" in the viewer.\n *\n * Every up-dependent default (camera framing, sun position, ground offset, view presets) derives\n * from {@link buildUpBasis} instead of hardcoding an axis. Before this module those defaults each\n * spelled out a Z-up vector inline, so a scene configured Y-up got a below-horizon camera and a\n * near-horizontal sun while the presets and floor correctly followed `sceneUp`.\n *\n * ## Why front is -forward\n *\n * The basis returns `forward` = the direction the camera LOOKS (from camera toward model), and the\n * preset positions are the opposite (from target toward camera). Rhino's convention fixes the signs:\n * its Front view looks along +Y, so the camera sits at -Y; its Right view looks along -X, so the\n * camera sits at +X. Deriving `right` as `seed x up` (rather than `up x seed`) is what makes the\n * handedness come out matching Rhino rather than mirrored.\n */\n\n/** An orthonormal frame derived from a scene up axis. All vectors are unit length. */\nexport interface UpBasis {\n\t/** The scene up axis, normalized. */\n\tup: THREE.Vector3;\n\t/** The direction a \"front\" view looks along (from camera toward the model). */\n\tforward: THREE.Vector3;\n\t/** Completes a right-handed frame with `up` and `forward`. */\n\tright: THREE.Vector3;\n}\n\n/**\n * Derive the ground-plane axes for a given up vector.\n *\n * The seed picks whichever world axis is least parallel to `up`, so the cross products stay\n * well-conditioned in any up convention. For Rhino's Z-up this yields forward = +Y and right = +X,\n * matching Rhino's own Front/Right views; for Three's native Y-up it yields forward = -Z and\n * right = +X, matching Three's convention that the default camera looks down -Z.\n */\nexport function buildUpBasis(up: THREE.Vector3): UpBasis {\n\tconst u = up.clone().normalize();\n\n\t// Seed with a world axis that isn't (nearly) parallel to up, so the cross product is stable.\n\tconst worldZ = new THREE.Vector3(0, 0, 1);\n\tconst worldY = new THREE.Vector3(0, 1, 0);\n\tconst seed = Math.abs(u.dot(worldZ)) > 0.9 ? worldY : worldZ;\n\n\t// `seed x up` (not `up x seed`) so the handedness matches Rhino: Z-up gives right = +X.\n\tconst right = new THREE.Vector3().crossVectors(seed, u).normalize();\n\t// Completes the frame. Z-up: forward = +Y (Rhino's Front looks along +Y). Y-up: forward = -Z.\n\tconst forward = new THREE.Vector3().crossVectors(u, right).normalize();\n\n\treturn { up: u, forward, right };\n}\n\n/**\n * The default 3/4 iso camera OFFSET from the target, scaled to `distance`.\n *\n * Placed behind-left and above the model (the conventional architectural 3/4), expressed in the\n * scene's own basis so it reads the same in any up convention. Callers add this to the framing\n * target to get a camera position.\n */\nexport function isoOffset(up: THREE.Vector3, distance: number): THREE.Vector3 {\n\tconst { forward, right, up: u } = buildUpBasis(up);\n\t// Behind (-forward), left (-right), above (+up) — normalized so `distance` is the true radius.\n\treturn forward\n\t\t.clone()\n\t\t.multiplyScalar(-1)\n\t\t.add(right.clone().multiplyScalar(-1))\n\t\t.add(u)\n\t\t.normalize()\n\t\t.multiplyScalar(distance);\n}\n\n/**\n * A default sun position: high above the model, offset to one side so surfaces get a directional\n * gradient instead of flat top-down light. Expressed in the scene basis rather than a literal\n * Z-up vector, so a Y-up scene still gets an overhead sun rather than a horizontal one.\n */\nexport function sunOffset(up: THREE.Vector3, sideDistance: number, height: number): THREE.Vector3 {\n\tconst { forward, right, up: u } = buildUpBasis(up);\n\treturn right\n\t\t.clone()\n\t\t.multiplyScalar(sideDistance)\n\t\t.add(forward.clone().multiplyScalar(sideDistance))\n\t\t.add(u.clone().multiplyScalar(height));\n}\n\n/**\n * The rotation that puts an equirectangular environment map's horizon on the scene's ground plane.\n *\n * Three's equirect mapping is hardcoded to Y-up: it assumes the HDR's horizon lies in the XZ plane\n * and its zenith points along +Y. In a Z-up scene that leaves the environment on its side — the\n * horizon runs vertically and image-based lighting arrives from +Y rather than from overhead. The\n * result is a subtly wrong key direction that a neutral studio HDR hides but any sky/ground HDR\n * makes obvious.\n *\n * Returns the Euler that rotates the map's native +Y zenith onto `up`. Identity for a Y-up scene.\n * Apply to BOTH `scene.environmentRotation` and `scene.backgroundRotation` — they are independent\n * properties, and setting only one makes the visible background disagree with the lighting.\n */\nexport function environmentRotationFor(up: THREE.Vector3): THREE.Euler {\n\tconst u = up.clone().normalize();\n\tconst mapZenith = new THREE.Vector3(0, 1, 0);\n\n\t// Already Y-up: the map is authored in this frame, so no correction is needed.\n\tif (u.dot(mapZenith) > 0.9999) return new THREE.Euler();\n\n\t// Upside-down (-Y): setFromUnitVectors picks an arbitrary perpendicular axis for a 180° flip,\n\t// which would also spin the horizon. Roll about X so the horizon stays put.\n\tif (u.dot(mapZenith) < -0.9999) return new THREE.Euler(Math.PI, 0, 0);\n\n\tconst quaternion = new THREE.Quaternion().setFromUnitVectors(mapZenith, u);\n\treturn new THREE.Euler().setFromQuaternion(quaternion);\n}\n\n/**\n * Which world axis (`'x' | 'y' | 'z'`) the up vector most closely aligns with.\n *\n * Used for the grid plane and for the ground-offset axis — both need a single component index\n * rather than a full vector. An off-axis up vector resolves to its dominant component.\n */\nexport function upToAxis(up: THREE.Vector3): 'x' | 'y' | 'z' {\n\tconst ax = Math.abs(up.x);\n\tconst ay = Math.abs(up.y);\n\tconst az = Math.abs(up.z);\n\tif (ax >= ay && ax >= az) return 'x';\n\tif (ay >= az) return 'y';\n\treturn 'z';\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { getLogger } from '@/core';\n\nimport { SHARED_MATERIALS } from './three-materials';\nimport { isoOffset } from './up-axis';\n\nconst CAMERA_CONFIG = {\n\tHUGE_THRESHOLD: 10000,\n\tLARGE_THRESHOLD: 1000,\n\tSCALE_RATIO_THRESHOLD: 100,\n\tNEAR_PLANE_FACTOR: {\n\t\tTINY: 0.0001,\n\t\tSMALL: 0.001,\n\t\tNORMAL: 0.01\n\t},\n\tFAR_PLANE_FACTOR: {\n\t\tHUGE: 100,\n\t\tLARGE: 50,\n\t\tNORMAL: 20\n\t},\n\tINITIAL_DISTANCE_MULTIPLIER: 4\n};\n\n/** Updates scene with meshes and positions camera on first call. */\nexport function updateScene(\n\tscene: THREE.Scene,\n\tmeshes: THREE.Object3D[],\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\tinitialPositionSet: boolean\n) {\n\tclearScene(scene);\n\n\tif (meshes.length === 0) return;\n\n\t// Add new objects (meshes, lines, points) to scene\n\tmeshes.forEach((mesh) => {\n\t\tscene.add(mesh);\n\t});\n\n\t// Calculate bounds of the new content\n\tconst unionBoundingBox = computeCombinedBoundingBox(meshes);\n\n\t// Get the center of the union bounding box\n\tconst center = unionBoundingBox.getCenter(new THREE.Vector3());\n\tconst size = unionBoundingBox.getSize(new THREE.Vector3());\n\n\t// Calculate a distance that is slightly larger than the largest dimension of the union bounding box\n\tconst maxDim = Math.max(size.x, size.y, size.z);\n\n\t// Always update camera frustum to ensure geometry is visible\n\t// This prevents clipping when geometry size changes significantly\n\tconst scaleRatio = maxDim / Math.min(size.x || 1, size.y || 1, size.z || 1);\n\n\tif (scaleRatio > CAMERA_CONFIG.SCALE_RATIO_THRESHOLD || maxDim > CAMERA_CONFIG.HUGE_THRESHOLD) {\n\t\t// Large scale range detected - use logarithmic depth buffer approach\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.TINY;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.HUGE;\n\t} else if (maxDim > CAMERA_CONFIG.LARGE_THRESHOLD) {\n\t\t// Large scene\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.SMALL;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.LARGE;\n\t} else {\n\t\t// Normal scene\n\t\tcamera.near = Math.max(0.01, maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.NORMAL);\n\t\tcamera.far = Math.max(2000, maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.NORMAL);\n\t}\n\n\tcamera.updateProjectionMatrix();\n\n\t// Only reposition camera and controls on first frame.\n\t// Zoom limits (min/maxDistance) are deliberately NOT touched here: they are owned by the\n\t// host via setupControls, and overwriting them per solve silently discarded user-supplied\n\t// configuration after the first geometry update.\n\tif (!initialPositionSet) {\n\t\tconst distance = maxDim * CAMERA_CONFIG.INITIAL_DISTANCE_MULTIPLIER;\n\n\t\t// Frame from the standard 3/4 iso, derived from the camera's own up axis (initThree sets it to\n\t\t// the configured sceneUp before this ever runs). Previously a hardcoded (0.8, 1.0, 1.2) offset\n\t\t// that both assumed Z-up and disagreed with the configured iso default, so the first solve\n\t\t// jumped to a different angle than the one the viewer opened at.\n\t\tcamera.position.copy(center).add(isoOffset(camera.up, distance));\n\t\tcontrols.target.copy(center);\n\n\t\tcontrols.update();\n\t}\n}\n\n/** Parses color strings (hex, RGB, CSS names). */\nexport function parseColor(colorString: string): THREE.Color {\n\tif (!colorString || typeof colorString !== 'string') {\n\t\tgetLogger().warn(`Invalid color input: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n\n\tconst trimmed = colorString.trim();\n\n\t// Try hex format (#C7A5A5 or C7A5A5) — require exactly 6 hex chars\n\tif (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) {\n\t\ttry {\n\t\t\tconst hex = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;\n\t\t\treturn new THREE.Color(hex);\n\t\t} catch {\n\t\t\tgetLogger().warn(`Invalid hex color: ${colorString}, using white`);\n\t\t\treturn new THREE.Color(0xffffff);\n\t\t}\n\t}\n\n\t// Try RGB format (R, G, B)\n\tif (trimmed.includes(',')) {\n\t\tconst rgb = trimmed.split(',').map((c) => parseInt(c.trim(), 10));\n\t\tif (rgb.length === 3 && rgb.every((n) => !isNaN(n) && n >= 0 && n <= 255)) {\n\t\t\treturn new THREE.Color(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);\n\t\t}\n\t}\n\n\t// Try CSS named color. `new THREE.Color(name)` never throws on unknown names (it logs its own\n\t// warning and leaves the color white), so validate against three's CSS name table instead.\n\tconst named = trimmed.toLowerCase();\n\tif (named in THREE.Color.NAMES) {\n\t\treturn new THREE.Color(THREE.Color.NAMES[named as keyof typeof THREE.Color.NAMES]);\n\t}\n\n\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\treturn new THREE.Color(0xffffff);\n}\n\n/**\n * Shift objects along one world axis. Defaults to `z` — the up axis of the unified Z-up scene\n * frame (see `../coordinate-transform.ts`), so grounding subtracts the content's lowest z. Pass an\n * explicit axis when the scene is configured with a different `sceneUp`.\n */\nexport function applyOffset(\n\tmeshes: THREE.Object3D[],\n\toffset: number,\n\taxis: 'x' | 'y' | 'z' = 'z'\n): void {\n\tmeshes.forEach((mesh) => {\n\t\tmesh.position[axis] -= offset;\n\t});\n}\n\n/**\n * Computes the combined world-axis-aligned bounding box of a set of objects (meshes, lines, points).\n * Correctly accounts for transformations (rotation, position, scale).\n */\nexport function computeCombinedBoundingBox(meshes: THREE.Object3D[]): THREE.Box3 {\n\tconst combinedBoundingBox = new THREE.Box3();\n\tif (meshes.length === 0) return combinedBoundingBox;\n\tmeshes.forEach((mesh) => {\n\t\t// Ensure the world matrix is up to date before calculating the box\n\t\tmesh.updateMatrixWorld(true);\n\t\tconst bbox = new THREE.Box3().setFromObject(mesh);\n\t\tcombinedBoundingBox.union(bbox);\n\t});\n\treturn combinedBoundingBox;\n}\n\n/**\n * userData.id of objects that are viewer *aids*, not content — the grid, floor, CSS2D label layer and\n * measure markers. Excluded from every content-bounds query: the grid especially is a huge plane that\n * re-centers on the camera each frame, so including it would make fit-to-view frame the camera's\n * position instead of the geometry.\n */\nconst VIEWER_AID_IDS = new Set(['grid', 'floor', 'label-layer', 'measure']);\n\n/** True if the object or any ancestor is a viewer aid (grid/floor/labels/measure markers). */\nfunction isViewerAid(object: THREE.Object3D): boolean {\n\tlet current: THREE.Object3D | null = object;\n\twhile (current) {\n\t\tif (typeof current.userData.id === 'string' && VIEWER_AID_IDS.has(current.userData.id)) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = current.parent;\n\t}\n\treturn false;\n}\n\n/**\n * Axis-aligned world bounds of the scene's renderable *content* — every visible mesh/line/points, with\n * viewer aids (grid/floor/labels/measure) excluded. The single content-bounds function: shared by\n * fit-to-view, pick-threshold scaling, camera framing (`setView`), and shadow-frustum fitting so they\n * all measure exactly the same box. Returns an empty Box3 when there is no content.\n *\n * Refreshes world matrices once up front (one traversal) so `expandByObject` reads current transforms\n * regardless of when the caller invokes this — cheaper and more correct than updating per object.\n */\nexport function computeContentBounds(scene: THREE.Scene): THREE.Box3 {\n\tscene.updateMatrixWorld(true);\n\tconst box = new THREE.Box3();\n\tscene.traverse((object) => {\n\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (object.visible && !isViewerAid(object) && renderable.geometry) {\n\t\t\tbox.expandByObject(object);\n\t\t}\n\t});\n\treturn box;\n}\n\n/** IDs of scene infrastructure that survives content updates (floor, grid, label layer). */\nconst PERSISTENT_SCENE_IDS = new Set(['floor', 'grid', 'label-layer']);\n\n/**\n * `geometry.userData` tag marking a geometry owned by the cross-solve geometry cache\n * (webdisplay/geometry-cache.ts). `clearScene` must NOT dispose these — the cache keeps them alive\n * (GPU buffers included) so the next solve can reuse them; the cache disposes on eviction instead.\n */\nexport const CACHED_GEOMETRY_USERDATA_FLAG = 'selvaGeometryCache';\n\n/** Removes all compute content except persistent infrastructure and shared materials. */\nexport function clearScene(scene: THREE.Scene): void {\n\t// Snapshot children — we mutate the array via removeFromParent during iteration\n\tconst topLevel = [...scene.children];\n\n\ttopLevel.forEach((object) => {\n\t\t// Persistent scene infrastructure (floor, grid, the CSS2D label layer) outlives content\n\t\t// updates — it's added once at init, not per solve. Removing the label-layer group here\n\t\t// orphans it, so labels created afterwards never render (the CSS2D renderer walks the live\n\t\t// scene and never finds them).\n\t\tif (PERSISTENT_SCENE_IDS.has(object.userData.id)) return;\n\n\t\t// User-drawn geometry (added via the viewer's addUserGeometry, tagged source==='user')\n\t\t// persists across solves so it isn't lost when compute content is replaced.\n\t\tif (object.userData.source === 'user') return;\n\n\t\t// Recursively dispose all renderable objects (meshes, lines, points) in this subtree.\n\t\tobject.traverse((child) => {\n\t\t\tconst renderable = child as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\t\t// Cache-owned geometries survive scene rebuilds — the cache disposes them on eviction.\n\t\t\tif (!renderable.geometry?.userData?.[CACHED_GEOMETRY_USERDATA_FLAG]) {\n\t\t\t\trenderable.geometry?.dispose();\n\t\t\t}\n\n\t\t\tconst material = renderable.material;\n\t\t\tif (!material) return;\n\t\t\tconst materials = Array.isArray(material) ? material : [material];\n\t\t\tmaterials.forEach((material) => {\n\t\t\t\t// Module-scope singletons (METAL_MATERIAL et al.) are shared across meshes and across\n\t\t\t\t// solves — disposing one here would force a shader rebuild on its next use and free\n\t\t\t\t// textures still referenced by surviving objects.\n\t\t\t\tif (SHARED_MATERIALS.has(material)) return;\n\n\t\t\t\t// Walk only own enumerable properties — `for...in` on a Three.js material\n\t\t\t\t// also iterates the prototype chain, which is needlessly expensive.\n\t\t\t\tfor (const value of Object.values(material)) {\n\t\t\t\t\tif (value instanceof THREE.Texture) {\n\t\t\t\t\t\tvalue.dispose();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmaterial.dispose();\n\t\t\t});\n\t\t});\n\n\t\tobject.removeFromParent();\n\t});\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nimport { computeContentBounds } from './three-helpers';\nimport { buildUpBasis } from './up-axis';\n\n/**\n * Runtime camera control for the viewer: preset views (top/front/…), a true 2D/3D toggle\n * (orthographic ⇄ perspective), and a rotate lock.\n *\n * Why a controller and not just loose methods: all three features have to agree on *which* camera\n * is active. Switching projection swaps the camera object OrbitControls drives, the animation loop\n * renders, the resize handler reshapes, and the raycaster picks with. Centralizing that here keeps\n * those four call sites reading one source of truth ({@link getActiveCamera}) instead of each\n * branching on a `mode` flag.\n *\n * The perspective camera stays the primary (it's what {@link updateScene} and existing consumers\n * size). The orthographic camera shadows it: same position/target, frustum derived from the\n * perspective FOV + current distance so the 3D→2D switch doesn't visually jump.\n */\n\n/** The six axis-aligned presets plus the default 3/4 iso. Named in Three's Y-up frame. */\nexport type ViewPreset = 'top' | 'bottom' | 'front' | 'back' | 'left' | 'right' | 'iso';\n\nexport type CameraProjection = 'perspective' | 'orthographic';\n\nexport interface CameraController {\n\t/** The camera currently being rendered/picked with. Swaps identity on {@link setProjection}. */\n\tgetActiveCamera(): THREE.Camera;\n\t/** Current projection mode. */\n\tgetProjection(): CameraProjection;\n\t/** Switch between perspective (3D) and orthographic (2D). No-op if already in that mode. */\n\tsetProjection(projection: CameraProjection): void;\n\t/** Convenience toggle for a 2D/3D button. */\n\ttoggleProjection(): CameraProjection;\n\t/** Move the camera to a preset orientation, framing current scene content. Animated. */\n\tsetView(preset: ViewPreset, animate?: boolean): void;\n\t/**\n\t * Frame current content viewed from `direction` (a world-space vector from target toward camera).\n\t * Like {@link setView} but takes an explicit direction — used by the nav-cube, whose clicked axis\n\t * is a world axis, not a named preset. Pole directions are nudged off-axis to avoid the orbit\n\t * singularity.\n\t */\n\tsetViewDirection(direction: THREE.Vector3, animate?: boolean): void;\n\t/**\n\t * Frame an arbitrary world-space box (e.g. a double-clicked object) from the current view\n\t * direction, moving the *active* camera — in 2D mode that means resizing the ortho frustum, not\n\t * just translating. No-op on an empty box.\n\t */\n\tframeBounds(box: THREE.Box3, animate?: boolean): void;\n\t/** Enable/disable orbit rotation at runtime (pan/zoom unaffected). */\n\tsetRotateEnabled(enabled: boolean): void;\n\t/** Whether rotation is currently enabled. */\n\tisRotateEnabled(): boolean;\n\t/** Keep the orthographic frustum aspect in sync on canvas resize. Called by the resize loop. */\n\tupdateAspect(width: number, height: number): void;\n\t/** Cancel any in-flight camera tween. Call on viewer teardown so ticks can't touch disposed controls. */\n\tdispose(): void;\n}\n\ninterface CameraControllerDeps {\n\tscene: THREE.Scene;\n\tperspective: THREE.PerspectiveCamera;\n\tcontrols: OrbitControls;\n\t/** Called whenever the active camera identity changes, so callers can re-point the renderer/raycaster. */\n\tonActiveCameraChange: (camera: THREE.Camera) => void;\n\t/**\n\t * The scene's up axis. Presets, the orthographic camera's up, and the iso direction are all derived\n\t * from this so the controller is correct in any up convention (Three's native Y-up, Rhino's Z-up, …)\n\t * without hardcoding an axis. Falls back to `perspective.up` when omitted; `initThree` always\n\t * passes the configured `sceneUp`, which itself defaults to Rhino's Z-up.\n\t */\n\tup?: THREE.Vector3;\n}\n\n/**\n * Build the seven preset view directions (from target toward camera, unit vectors) for a given up\n * axis. \"Top\" looks straight down the up axis; front/back/left/right are the two axes orthogonal to\n * up; iso is a 3/4 blend.\n *\n * Deriving these from `up` (instead of a fixed Y-up table) is what keeps Top/Front/… meaningful for\n * Z-up Rhino scenes — otherwise \"Top\" would frame the side of the model.\n *\n * Note the sign flip against {@link buildUpBasis}: the basis' `forward` is the direction a front\n * view LOOKS (camera toward model), while these presets are camera POSITIONS relative to the target.\n * So \"front\" places the camera at `-forward`. Getting this backwards is exactly the bug this\n * convention fixes — it put the camera behind the model and swapped left with right.\n */\nfunction buildViewDirections(up: THREE.Vector3): Record<ViewPreset, THREE.Vector3> {\n\tconst { up: u, forward, right } = buildUpBasis(up);\n\n\t// Camera positions are opposite the look direction: Rhino's Front looks along +Y from -Y.\n\tconst frontPosition = forward.clone().negate();\n\tconst rightPosition = right.clone();\n\n\treturn {\n\t\ttop: u.clone(),\n\t\tbottom: u.clone().negate(),\n\t\tfront: frontPosition.clone(),\n\t\tback: frontPosition.clone().negate(),\n\t\tright: rightPosition.clone(),\n\t\tleft: rightPosition.clone().negate(),\n\t\t// 3/4 iso: blend front, right, and up so it reads as a corner view regardless of up axis.\n\t\tiso: frontPosition\n\t\t\t.clone()\n\t\t\t.multiplyScalar(1.2)\n\t\t\t.add(rightPosition.clone())\n\t\t\t.add(u.clone())\n\t\t\t.normalize()\n\t};\n}\n\nexport function createCameraController(deps: CameraControllerDeps): CameraController {\n\tconst { scene, perspective, controls, onActiveCameraChange } = deps;\n\n\t// Up axis drives presets, the ortho camera's up, and the iso direction. Prefer an explicit `up`,\n\t// fall back to the perspective camera's current up (which initThree sets to sceneUp).\n\tconst up = (deps.up ?? perspective.up).clone().normalize();\n\tconst VIEW_DIRECTIONS = buildViewDirections(up);\n\n\tconst ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, perspective.near, perspective.far);\n\tortho.up.copy(up);\n\n\tlet projection: CameraProjection = 'perspective';\n\tlet aspect = perspective.aspect;\n\n\tconst active = (): THREE.Camera => (projection === 'perspective' ? perspective : ortho);\n\n\t// The one in-flight camera tween, if any. Starting a new tween cancels the previous one (two\n\t// concurrent loops would fight, each lerping from its own snapshot), and dispose() cancels it so\n\t// no tick can touch disposed controls after teardown.\n\tlet activeTween: TweenHandle | null = null;\n\tconst cancelTween = () => {\n\t\tactiveTween?.cancel();\n\t\tactiveTween = null;\n\t};\n\n\t// Sizes the ortho frustum so its on-screen content matches the perspective view at the current\n\t// distance — the apparent height of the perspective view at the target plane is\n\t// 2 * distance * tan(fov/2). Half-height drives top/bottom; aspect drives left/right.\n\tconst syncOrthoFrustum = () => {\n\t\t// While ortho is active, the ORTHO camera is the one presets/fit move (OrbitControls only\n\t\t// changes its zoom); the perspective camera's distance is stale until the next 3D switch.\n\t\t// Measure whichever camera is live so presets and resizes in 2D size the frustum correctly.\n\t\tconst reference = projection === 'orthographic' ? ortho : perspective;\n\t\tconst distance = reference.position.distanceTo(controls.target);\n\t\tconst halfH = distance * Math.tan((perspective.fov * Math.PI) / 360);\n\t\tconst halfW = halfH * aspect;\n\t\tortho.left = -halfW;\n\t\tortho.right = halfW;\n\t\tortho.top = halfH;\n\t\tortho.bottom = -halfH;\n\t\tortho.near = perspective.near;\n\t\tortho.far = perspective.far;\n\t\tortho.updateProjectionMatrix();\n\t};\n\n\tconst setProjection = (next: CameraProjection) => {\n\t\tif (next === projection) return;\n\t\t// A tween mid-flight would keep lerping the OLD active camera after the swap.\n\t\tcancelTween();\n\n\t\t// Carry position/target across so the switch doesn't jump.\n\t\tif (next === 'orthographic') {\n\t\t\tortho.position.copy(perspective.position);\n\t\t\tortho.up.copy(perspective.up);\n\t\t\tortho.lookAt(controls.target);\n\t\t\t// OrbitControls dollies an ortho camera via `zoom`, not position — start each 2D session\n\t\t\t// at 1 so the freshly-derived frustum isn't still multiplied by zoom left over from a\n\t\t\t// previous 2D session (which showed as a zoom jump on every 2D→3D→2D round-trip).\n\t\t\tortho.zoom = 1;\n\t\t\tsyncOrthoFrustum();\n\t\t} else {\n\t\t\t// Carry the ortho dolly back as perspective DISTANCE so the switch preserves apparent\n\t\t\t// size: the ortho view shows a half-height of top/zoom at the target plane, and the\n\t\t\t// perspective camera shows the same at distance = halfH / tan(fov/2). Copying position\n\t\t\t// alone would discard any zooming done in 2D.\n\t\t\tconst halfH = (ortho.top - ortho.bottom) / (2 * ortho.zoom);\n\t\t\tconst distance = halfH / Math.tan((perspective.fov * Math.PI) / 360);\n\t\t\tconst direction = ortho.position.clone().sub(controls.target);\n\t\t\tif (direction.lengthSq() < 1e-12) direction.copy(up);\n\t\t\tdirection.normalize();\n\t\t\tperspective.position.copy(controls.target).add(direction.multiplyScalar(distance));\n\t\t}\n\n\t\tprojection = next;\n\t\tcontrols.object = active();\n\t\tcontrols.update();\n\t\tonActiveCameraChange(active());\n\t};\n\n\t// Shared framing move: position the ACTIVE camera along `direction` at the distance that fits\n\t// `maxDim`, retargeting controls at `center`. In ortho mode the dolly zoom is reset and the\n\t// frustum re-derived (per tick while animating) — moving position alone wouldn't change the\n\t// apparent size of an orthographic view.\n\tconst frame = (\n\t\tcenter: THREE.Vector3,\n\t\tmaxDim: number,\n\t\tdirection: THREE.Vector3,\n\t\tanimate: boolean\n\t) => {\n\t\t// Distance to fit the content for the perspective camera; ortho reuses it via syncOrthoFrustum.\n\t\tconst fov = perspective.fov * (Math.PI / 180);\n\t\tconst distance = (maxDim / (2 * Math.tan(fov / 2))) * 1.5;\n\n\t\t// A direction along the up axis (top/bottom) puts the view direction parallel to camera.up — an\n\t\t// OrbitControls singularity (the next mouse drag flips the view 180° and the gizmo jitters).\n\t\t// Tilt it a hair off-axis so the orbit basis stays well-defined.\n\t\tconst dir = nudgeOffPole(direction, up);\n\t\tconst toPosition = center.clone().add(dir.clone().multiplyScalar(distance));\n\n\t\tconst cam = active();\n\t\t// Framing means fitting: a leftover ortho dolly (OrbitControls zooms ortho via `zoom`) would\n\t\t// keep multiplying the freshly-derived frustum and defeat the fit.\n\t\tif (projection === 'orthographic') ortho.zoom = 1;\n\n\t\tcancelTween();\n\t\tif (animate) {\n\t\t\tactiveTween = animateMove(cam, controls, toPosition, center, () => {\n\t\t\t\tif (projection === 'orthographic') syncOrthoFrustum();\n\t\t\t});\n\t\t} else {\n\t\t\tcam.position.copy(toPosition);\n\t\t\tcontrols.target.copy(center);\n\t\t\tif (projection === 'orthographic') syncOrthoFrustum();\n\t\t\tcontrols.update();\n\t\t}\n\t};\n\n\tconst setViewDirection = (direction: THREE.Vector3, animate = true) => {\n\t\tconst box = computeContentBounds(scene);\n\t\tconst center = box.isEmpty() ? controls.target.clone() : box.getCenter(new THREE.Vector3());\n\t\tconst size = box.isEmpty() ? new THREE.Vector3(1, 1, 1) : box.getSize(new THREE.Vector3());\n\t\tconst maxDim = Math.max(size.x, size.y, size.z) || 1;\n\t\tframe(center, maxDim, direction, animate);\n\t};\n\n\tconst frameBounds = (box: THREE.Box3, animate = true) => {\n\t\tif (box.isEmpty()) return;\n\t\tconst center = box.getCenter(new THREE.Vector3());\n\t\tconst size = box.getSize(new THREE.Vector3());\n\t\tconst maxDim = Math.max(size.x, size.y, size.z) || 1;\n\t\t// Keep the user's current viewing direction; only the distance/target change.\n\t\tconst direction = active().position.clone().sub(controls.target);\n\t\tif (direction.lengthSq() < 1e-12) direction.copy(VIEW_DIRECTIONS.iso);\n\t\tframe(center, maxDim, direction.normalize(), animate);\n\t};\n\n\tconst setView = (preset: ViewPreset, animate = true) => {\n\t\tsetViewDirection(VIEW_DIRECTIONS[preset], animate);\n\t};\n\n\tconst setRotateEnabled = (enabled: boolean) => {\n\t\tcontrols.enableRotate = enabled;\n\t};\n\n\tconst updateAspect = (width: number, height: number) => {\n\t\taspect = height === 0 ? aspect : width / height;\n\t\tif (projection === 'orthographic') syncOrthoFrustum();\n\t};\n\n\treturn {\n\t\tgetActiveCamera: active,\n\t\tgetProjection: () => projection,\n\t\tsetProjection,\n\t\ttoggleProjection: () => {\n\t\t\tsetProjection(projection === 'perspective' ? 'orthographic' : 'perspective');\n\t\t\treturn projection;\n\t\t},\n\t\tsetView,\n\t\tsetViewDirection,\n\t\tframeBounds,\n\t\tsetRotateEnabled,\n\t\tisRotateEnabled: () => controls.enableRotate,\n\t\tupdateAspect,\n\t\tdispose: cancelTween\n\t};\n}\n\n/**\n * If a view direction is (nearly) parallel to the up axis — i.e. top/bottom — tilt it a fraction of\n * a degree toward an in-plane axis. Looking exactly down `up` is an OrbitControls singularity: the\n * camera direction coincides with `camera.up`, so azimuth is undefined and the first drag snaps the\n * view. A ~0.5° tilt is imperceptible but keeps the orbit basis well-defined. Non-pole presets pass\n * through unchanged.\n *\n * The tilt DIRECTION also decides the roll of the resulting view, because at the pole `camera.up`\n * can no longer define it.\n *\n * Both poles lean toward `-forward`, which reproduces Rhino's own convention:\n * - Top (+X right, +Y up) — looking down, `+forward` at the top of the screen.\n * - Bottom (+X right, +Y down) — the underside, mirrored about the HORIZONTAL axis.\n *\n * Bottom being mirrored is correct: you are looking at the far side of the model, so text on the\n * geometry reads backwards there in Rhino too. What matters is WHICH way it mirrors. Leaning the\n * two poles opposite ways also produces a mirror, but rolled 180° from Rhino's (+X left, +Y up) —\n * the same image spun around, which is why it still looked wrong.\n */\nfunction nudgeOffPole(dir: THREE.Vector3, up: THREE.Vector3): THREE.Vector3 {\n\tconst { up: u, forward } = buildUpBasis(up);\n\tconst d = dir.clone().normalize();\n\tif (Math.abs(d.dot(u)) < 0.9999) return dir;\n\n\t// Same lean for both poles: the shared screen-space +X is what makes Bottom read as Top flipped\n\t// about the horizontal, rather than about the vertical.\n\tconst inPlane = forward.clone().negate();\n\n\tconst tilt = (0.5 * Math.PI) / 180; // ~0.5°\n\treturn d\n\t\t.multiplyScalar(Math.cos(tilt))\n\t\t.add(inPlane.multiplyScalar(Math.sin(tilt)))\n\t\t.normalize();\n}\n\nconst easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n\n/** Handle to a running camera tween, so callers can stop it (new move, projection swap, teardown). */\ninterface TweenHandle {\n\tcancel(): void;\n}\n\n/**\n * Tween camera position + controls target. Returns a cancel handle: the controller cancels the\n * previous tween before starting a new one (two loops would fight over the camera) and on\n * dispose() so no tick touches disposed controls after teardown.\n */\nfunction animateMove(\n\tcamera: THREE.Camera,\n\tcontrols: OrbitControls,\n\ttoPosition: THREE.Vector3,\n\ttoTarget: THREE.Vector3,\n\tonTick: () => void,\n\tdurationMs = 250\n): TweenHandle {\n\tconst fromPosition = camera.position.clone();\n\tconst fromTarget = controls.target.clone();\n\tconst startTime = performance.now();\n\tlet rafId: number | null = null;\n\n\tconst tick = () => {\n\t\trafId = null;\n\t\tconst t = easeOut(Math.min((performance.now() - startTime) / durationMs, 1));\n\t\tcamera.position.lerpVectors(fromPosition, toPosition, t);\n\t\tcontrols.target.lerpVectors(fromTarget, toTarget, t);\n\t\tonTick();\n\t\tcontrols.update();\n\t\tif (t < 1) rafId = requestAnimationFrame(tick);\n\t};\n\n\trafId = requestAnimationFrame(tick);\n\n\treturn {\n\t\tcancel: () => {\n\t\t\tif (rafId !== null) {\n\t\t\t\tcancelAnimationFrame(rafId);\n\t\t\t\trafId = null;\n\t\t\t}\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\n\n/**\n * An \"infinite\", distance-fading reference grid — the single strongest visual cue that reads as CAD.\n *\n * Why not `GridHelper`: it's a fixed-size square of line segments that visibly ends and looks wrong\n * once you pan or zoom past it. Instead we draw one large screen-facing plane and compute the grid\n * in the fragment shader from world coordinates, fading lines out with distance so the edge is never\n * a hard cutoff. The plane is big enough to cover any reasonable view; the fade hides its bounds.\n *\n * Two line frequencies (minor + major every 10th) give the usual graph-paper depth read. Spacing is\n * in world units (meters — the scene's normalized unit), so a `cellSize` of 1 = 1m minor cells.\n */\n\nexport interface GridOptions {\n\t/** Minor cell size in world units (meters). Default 1. */\n\tcellSize?: number;\n\t/** How many minor cells per major line. Default 10. */\n\tmajorEvery?: number;\n\t/** Minor line color. */\n\tcellColor?: THREE.ColorRepresentation;\n\t/** Major line color. */\n\tmajorColor?: THREE.ColorRepresentation;\n\t/** World-space radius at which the grid has fully faded out. Default 100. */\n\tfadeDistance?: number;\n\t/**\n\t * Axis the grid is laid perpendicular to — i.e. the scene's up axis. `'z'` is the horizontal\n\t * ground in the Rhino Z-up frame the viewer uses; `'y'` is Three's native Y-up.\n\t *\n\t * This standalone default is `'y'`, but `initThree` always passes a plane derived from the\n\t * configured `sceneUp`, so a viewer-created grid defaults to `'z'`.\n\t */\n\tplane?: 'x' | 'y' | 'z';\n}\n\nexport interface Grid {\n\t/** The grid mesh; add to the scene. Tagged `userData.id = 'grid'` so pick/fit code skips it. */\n\treadonly object: THREE.Mesh;\n\t/** Keep the fade centered on the camera so the grid feels infinite as you move. Call per frame. */\n\tupdate(cameraPosition: THREE.Vector3): void;\n\t/**\n\t * Rescale the grid's cell spacing and fade radius to the loaded content's extent. Call after a\n\t * geometry change (e.g. right after `updateScene`) so a part that is 3 units or 3000 units wide\n\t * both get sensibly-sized cells and a fade that reaches past the model. No-op for empty/degenerate\n\t * bounds — the grid keeps its last (or default) scale. See {@link Grid.fitToContent}'s impl notes.\n\t */\n\tfitToContent(bounds: THREE.Box3): void;\n\tsetVisible(visible: boolean): void;\n\tdispose(): void;\n}\n\n/**\n * Round a value to a \"nice\" 1/2/5 × 10ⁿ step — the spacing conventions used by rulers and CAD grids,\n * so cells land on human-readable multiples (…, 0.5, 1, 2, 5, 10, 20, 50, …) rather than arbitrary\n * fractions like 1.37. Returns the largest nice step ≤ `value` (floored on the mantissa) so cells\n * never come out finer than the target and alias into a solid sheet.\n */\nfunction niceStep(value: number): number {\n\tif (!(value > 0) || !Number.isFinite(value)) return 1;\n\tconst exponent = Math.floor(Math.log10(value));\n\tconst power = Math.pow(10, exponent);\n\tconst mantissa = value / power; // in [1, 10)\n\tconst niceMantissa = mantissa >= 5 ? 5 : mantissa >= 2 ? 2 : 1;\n\treturn niceMantissa * power;\n}\n\nconst GRID_VERTEX = /* glsl */ `\n\tvarying vec3 vWorldPos;\n\tvoid main() {\n\t\tvec4 world = modelMatrix * vec4(position, 1.0);\n\t\tvWorldPos = world.xyz;\n\t\tgl_Position = projectionMatrix * viewMatrix * world;\n\t}\n`;\n\nconst GRID_FRAGMENT = /* glsl */ `\n\tprecision highp float;\n\tvarying vec3 vWorldPos;\n\n\tuniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes\n\tuniform float uCell;\n\tuniform float uMajor;\n\tuniform vec3 uCellColor;\n\tuniform vec3 uMajorColor;\n\tuniform vec3 uCenter; // fade center (camera position), projected onto plane\n\tuniform float uFade;\n\n\t// Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines\n\t// stay ~1px regardless of zoom (the standard \"pristine grid\" technique).\n\tfloat gridLine(vec2 coord, float spacing) {\n\t\tvec2 c = coord / spacing;\n\t\tvec2 d = fwidth(c);\n\t\tvec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);\n\t\tfloat line = min(g.x, g.y);\n\t\treturn 1.0 - clamp(line, 0.0, 1.0);\n\t}\n\n\t// Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).\n\tfloat axis(vec3 v, float i) {\n\t\treturn i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);\n\t}\n\n\tvoid main() {\n\t\t// Pick the two in-plane world coordinates.\n\t\tvec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));\n\n\t\tfloat minor = gridLine(coord, uCell);\n\t\tfloat major = gridLine(coord, uCell * uMajor);\n\n\t\tvec3 color = mix(uCellColor, uMajorColor, major);\n\t\tfloat alpha = max(minor, major);\n\n\t\t// Radial fade from the camera-projected center.\n\t\tfloat dist = distance(vWorldPos, uCenter);\n\t\tfloat fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);\n\t\talpha *= fade * fade;\n\n\t\tif (alpha < 0.001) discard;\n\t\tgl_FragColor = vec4(color, alpha);\n\t}\n`;\n\nexport function createGrid(options: GridOptions = {}): Grid {\n\tconst {\n\t\tcellSize = 1,\n\t\tmajorEvery = 10,\n\t\tcellColor = 0x888888,\n\t\tmajorColor = 0x444444,\n\t\tfadeDistance = 100,\n\t\tplane = 'y'\n\t} = options;\n\n\t// The two in-plane world axes (0=x,1=y,2=z): ground 'y' grids over x,z; 'z' over x,y; 'x' over y,z.\n\tconst axes =\n\t\tplane === 'y'\n\t\t\t? new THREE.Vector2(0, 2) // x, z\n\t\t\t: plane === 'z'\n\t\t\t\t? new THREE.Vector2(0, 1) // x, y\n\t\t\t\t: new THREE.Vector2(1, 2); // y, z\n\n\t// The plane must comfortably outreach the fade radius, else the grid ends before it has faded and\n\t// shows a hard rectangular edge. Built as a unit plane and sized purely by scale so fitToContent\n\t// can regrow it without recreating geometry — the same rotation onto the world plane still applies.\n\tconst PLANE_TO_FADE_RATIO = 2.5;\n\tconst geometry = new THREE.PlaneGeometry(1, 1);\n\n\t// PlaneGeometry is in the XY plane by default; rotate it onto the requested world plane.\n\tif (plane === 'y') geometry.rotateX(-Math.PI / 2);\n\telse if (plane === 'x') geometry.rotateY(Math.PI / 2);\n\n\tconst material = new THREE.ShaderMaterial({\n\t\tvertexShader: GRID_VERTEX,\n\t\tfragmentShader: GRID_FRAGMENT,\n\t\ttransparent: true,\n\t\tdepthWrite: false,\n\t\tside: THREE.DoubleSide,\n\t\tuniforms: {\n\t\t\tuAxes: { value: axes },\n\t\t\tuCell: { value: cellSize },\n\t\t\tuMajor: { value: majorEvery },\n\t\t\tuCellColor: { value: new THREE.Color(cellColor) },\n\t\t\tuMajorColor: { value: new THREE.Color(majorColor) },\n\t\t\tuCenter: { value: new THREE.Vector3() },\n\t\t\tuFade: { value: fadeDistance }\n\t\t}\n\t});\n\n\tconst mesh = new THREE.Mesh(geometry, material);\n\tmesh.name = 'grid';\n\tmesh.userData.id = 'grid'; // excluded from raycasting/fit-to-view, like the floor\n\tmesh.renderOrder = -1; // draw before content so transparent geometry blends over it\n\n\t// Live scale of the (unit) plane and current fade radius; fitToContent mutates both, `update`\n\t// reads planeScale each frame to size the camera-tracking plane. Seeded from the constructor's\n\t// fadeDistance so an un-fitted grid still covers its fade.\n\tlet fadeRadius = fadeDistance;\n\tlet planeScale = fadeDistance * PLANE_TO_FADE_RATIO;\n\n\tconst center = new THREE.Vector3();\n\n\treturn {\n\t\tobject: mesh,\n\t\tupdate: (cameraPosition) => {\n\t\t\t// Re-center the plane and the fade on the camera so the grid tracks the view \"infinitely\".\n\t\t\t// Keep the plane's own axis fixed (don't lift the ground grid up to the camera height).\n\t\t\tif (plane === 'y') {\n\t\t\t\tmesh.position.set(cameraPosition.x, 0, cameraPosition.z);\n\t\t\t\tcenter.set(cameraPosition.x, 0, cameraPosition.z);\n\t\t\t} else if (plane === 'z') {\n\t\t\t\tmesh.position.set(cameraPosition.x, cameraPosition.y, 0);\n\t\t\t\tcenter.set(cameraPosition.x, cameraPosition.y, 0);\n\t\t\t} else {\n\t\t\t\tmesh.position.set(0, cameraPosition.y, cameraPosition.z);\n\t\t\t\tcenter.set(0, cameraPosition.y, cameraPosition.z);\n\t\t\t}\n\t\t\tmaterial.uniforms.uCenter.value.copy(center);\n\t\t\t// Size the unit plane to the current scale. The rotation baked into the geometry means the\n\t\t\t// plane's local XY spans the two world in-plane axes, so a uniform scale is correct on any\n\t\t\t// plane orientation.\n\t\t\tmesh.scale.setScalar(planeScale);\n\t\t},\n\t\tfitToContent: (bounds) => {\n\t\t\tif (bounds.isEmpty()) return;\n\t\t\t// Use the two in-plane axes' extent (not the full 3D diagonal) as the \"how big is this on\n\t\t\t// the ground\" measure — a tall thin part shouldn't blow the cell size up by its height.\n\t\t\tconst sizeVec = bounds.getSize(new THREE.Vector3());\n\t\t\tconst axisComponent = (v: THREE.Vector3, i: number) => (i === 0 ? v.x : i === 1 ? v.y : v.z);\n\t\t\tconst inPlaneExtent = Math.max(\n\t\t\t\taxisComponent(sizeVec, axes.x),\n\t\t\t\taxisComponent(sizeVec, axes.y)\n\t\t\t);\n\t\t\tif (!(inPlaneExtent > 0) || !Number.isFinite(inPlaneExtent)) return;\n\n\t\t\t// Aim for ~20 minor cells across the part, snapped to a nice 1/2/5 step so labels stay\n\t\t\t// readable; majorEvery keeps the coarser reference lines. Fade reaches ~2× past the part so\n\t\t\t// the grid extends beyond it without a visible edge, and the plane outreaches the fade.\n\t\t\tconst TARGET_CELLS_ACROSS = 20;\n\t\t\tmaterial.uniforms.uCell.value = niceStep(inPlaneExtent / TARGET_CELLS_ACROSS);\n\t\t\tfadeRadius = inPlaneExtent * 2;\n\t\t\tmaterial.uniforms.uFade.value = fadeRadius;\n\t\t\tplaneScale = fadeRadius * PLANE_TO_FADE_RATIO;\n\t\t},\n\t\tsetVisible: (visible) => {\n\t\t\tmesh.visible = visible;\n\t\t},\n\t\tdispose: () => {\n\t\t\tmesh.removeFromParent(); // don't leave a dead mesh in the scene graph\n\t\t\tgeometry.dispose();\n\t\t\tmaterial.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { ViewHelper } from 'three/addons/helpers/ViewHelper.js';\n\nimport type { CameraController } from './camera-controller';\n\n/**\n * The corner nav-cube/axis gizmo. Uses three's {@link ViewHelper} purely as the rendered widget, but\n * NOT its click→animate behavior: ViewHelper's built-in snap assumes a Y-up world and animates the\n * camera straight onto the up axis, which in our Z-up scene rolls the view and makes the gizmo jitter\n * at the pole. Instead we hit-test the axis sprites ourselves and drive the viewer's up-aware camera\n * controller, which snaps (no animation) with a pole nudge so the orbit basis never degenerates.\n *\n * Integration points with the viewer's dual-camera setup:\n * 1. The snap frames the current orbit target via the controller, so it rotates about what the user\n * is looking at (not the world origin).\n * 2. The nav cube is inherently a 3D-orientation tool, so if the viewer is in orthographic (2D) mode\n * when the gizmo is clicked, we first flip back to perspective.\n *\n * Caller responsibilities (mirror ViewHelper's own contract):\n * - call {@link ViewGizmo.render} *after* the main scene render each frame (overlay viewport),\n * - forward pointer clicks to {@link ViewGizmo.handleClick}.\n */\nexport interface ViewGizmo {\n\trender(renderer: THREE.WebGLRenderer): void;\n\t/**\n\t * @deprecated No-op, kept only for API stability. This wrapper never uses ViewHelper's\n\t * click→animate path (see module comment) — view changes snap instantly through the camera\n\t * controller — so there is never a gizmo animation to advance. Safe to stop calling.\n\t */\n\tupdate(delta: number): void;\n\t/** Hit-test a click. Returns true if it hit the gizmo (and a view change started). */\n\thandleClick(event: MouseEvent): boolean;\n\t/**\n\t * @deprecated Always `false`, kept only for API stability. Gizmo clicks snap the view\n\t * instantly rather than animating (deliberately — ViewHelper's built-in animation assumes a\n\t * Y-up world and rolls the view in this Z-up scene), so there is no animation window to gate\n\t * input on.\n\t */\n\treadonly isAnimating: boolean;\n\t/** Show/hide the gizmo at runtime. Hidden = not rendered and not click-hittable. */\n\tsetVisible(visible: boolean): void;\n\tisVisible(): boolean;\n\tdispose(): void;\n}\n\ninterface ViewGizmoDeps {\n\t/** The perspective (primary) camera the gizmo visualizes and re-orients. */\n\tcamera: THREE.PerspectiveCamera;\n\tdomElement: HTMLElement;\n\tcontroller: CameraController;\n}\n\nexport function createViewGizmo(deps: ViewGizmoDeps): ViewGizmo {\n\tconst { camera, domElement, controller } = deps;\n\n\tconst helper = new ViewHelper(camera, domElement);\n\thelper.setLabels('X', 'Y', 'Z');\n\n\tlet visible = true;\n\n\t// Our own hit-test against the helper's axis sprites, mirroring ViewHelper's internal viewport math\n\t// (a `dim`×`dim` square in the corner given by `location`). We do this instead of ViewHelper's own\n\t// `handleClick` so the camera move goes through the viewer's up-aware controller — ViewHelper's\n\t// built-in snap assumes a Y-up world and animates straight onto the pole, which rolls the view and\n\t// makes the gizmo jitter in our Z-up scene.\n\tconst DIM = 128;\n\tconst raycaster = new THREE.Raycaster();\n\tconst gizmoCamera = new THREE.OrthographicCamera(-2, 2, 2, -2, 0, 4);\n\tgizmoCamera.position.set(0, 0, 2);\n\t// This camera is never rendered, so nothing else computes its matrixWorld — and\n\t// Raycaster.setFromCamera doesn't either. Without this the ray originates at the identity\n\t// position (z = 0, the cube's mid-plane) and the camera-facing axis sprites sit behind it.\n\tgizmoCamera.updateMatrixWorld();\n\n\t// Map a clicked axis sprite to the world-space view direction (from target toward camera).\n\tconst AXIS_DIRECTIONS: Record<string, THREE.Vector3> = {\n\t\tposX: new THREE.Vector3(1, 0, 0),\n\t\tnegX: new THREE.Vector3(-1, 0, 0),\n\t\tposY: new THREE.Vector3(0, 1, 0),\n\t\tnegY: new THREE.Vector3(0, -1, 0),\n\t\tposZ: new THREE.Vector3(0, 0, 1),\n\t\tnegZ: new THREE.Vector3(0, 0, -1)\n\t};\n\n\t/** Which axis sprite (if any) a click landed on. Returns its `userData.type` or null. */\n\tconst pickAxis = (event: MouseEvent): string | null => {\n\t\tconst rect = domElement.getBoundingClientRect();\n\t\t// The gizmo viewport sits in the bottom-right corner (helper.location defaults: right/bottom 0).\n\t\tconst offsetX = rect.left + domElement.offsetWidth - DIM - helper.location.right;\n\t\tconst offsetY = rect.top + domElement.offsetHeight - DIM - helper.location.bottom;\n\n\t\tconst mouse = new THREE.Vector2(\n\t\t\t((event.clientX - offsetX) / DIM) * 2 - 1,\n\t\t\t-((event.clientY - offsetY) / DIM) * 2 + 1\n\t\t);\n\t\t// Outside the gizmo square — not our click.\n\t\tif (Math.abs(mouse.x) > 1 || Math.abs(mouse.y) > 1) return null;\n\n\t\t// Orient the helper as it's rendered (inverse of the camera), so the sprites are where the user\n\t\t// sees them, then raycast the interactive axis sprites.\n\t\thelper.quaternion.copy(camera.quaternion).invert();\n\t\thelper.updateMatrixWorld();\n\n\t\traycaster.setFromCamera(mouse, gizmoCamera);\n\t\tconst hits = raycaster.intersectObjects(helper.children, false);\n\t\tfor (const hit of hits) {\n\t\t\tconst type = hit.object.userData?.type;\n\t\t\tif (typeof type === 'string' && type in AXIS_DIRECTIONS) return type;\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst handleClick = (event: MouseEvent): boolean => {\n\t\tif (!visible) return false;\n\n\t\tconst axis = pickAxis(event);\n\t\tif (!axis) return false;\n\n\t\t// The cube orients in 3D, so a click while in 2D returns us to perspective first.\n\t\tif (controller.getProjection() === 'orthographic') {\n\t\t\tcontroller.setProjection('perspective');\n\t\t}\n\n\t\t// Snap directly via the up-aware controller — no animation, no Y-up pole roll.\n\t\tcontroller.setViewDirection(AXIS_DIRECTIONS[axis]!, false);\n\t\treturn true;\n\t};\n\n\treturn {\n\t\trender: (renderer) => {\n\t\t\tif (!visible) return;\n\t\t\t// ViewHelper.render() calls renderer.render(this, orthoCamera), which with the default\n\t\t\t// autoClear=true clears the FULL framebuffer (to the scene's grey clear color) before drawing\n\t\t\t// the cube in its corner viewport — wiping the just-rendered scene. It only needs the depth\n\t\t\t// clear it does internally (clearDepth). So suppress the automatic color/depth clear here.\n\t\t\tconst prevAutoClear = renderer.autoClear;\n\t\t\trenderer.autoClear = false;\n\t\t\thelper.render(renderer);\n\t\t\trenderer.autoClear = prevAutoClear;\n\t\t},\n\t\t// Deliberately a no-op (see the interface docs): ViewHelper.update() only exists to advance\n\t\t// its click-snap animation, which this wrapper never starts (handleClick snaps via the\n\t\t// camera controller instead). Calling helper.update() outside an animation would rewrite\n\t\t// camera.position from (center=origin, radius=0) and blank the view.\n\t\tupdate: () => {},\n\t\thandleClick,\n\t\t// Honestly constant (see the interface docs): nothing here ever animates.\n\t\tisAnimating: false,\n\t\tsetVisible: (value) => {\n\t\t\tvisible = value;\n\t\t},\n\t\tisVisible: () => visible,\n\t\tdispose: () => helper.dispose()\n\t};\n}\n","import * as THREE from 'three';\nimport { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';\nimport { LineSegments2 } from 'three/addons/lines/LineSegments2.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport { MAX_EXTRACT_VERTICES, edgeExtractWorkerSource, extractEdgeSegments } from './edge-extract';\n\n/**\n * Crisp boundary/crease edges overlaid on meshes — the defining \"technical drawing\" look that makes\n * shaded geometry read as discrete objects rather than blobs.\n *\n * Edge segments are extracted by `extractEdgeSegments` (see edge-extract.ts — an\n * `EdgesGeometry`-equivalent that is ~an order of magnitude faster and worker-portable) and\n * rendered as fat `LineSegments2` using the same `LineMaterial` family as curves — so edges get\n * controllable thickness, not the 1px cap of `THREE.LineSegments`. The overlay is added as a\n * *child* of each mesh, so it inherits the mesh's transform and is disposed when the mesh subtree\n * is cleared.\n *\n * Performance model (docs/plans/4.edge-overlay-performance.md):\n * - Extraction results are cached at two levels: per source `BufferGeometry` (object identity,\n * helps instanced parts within one solve) and by *content fingerprint* in an LRU — the viewer\n * rebuilds all geometry objects every solve, so only a content key survives re-solves.\n * - {@link addEdgesAsync} runs extraction for large meshes in a Worker built from a blob URL\n * (bundler-agnostic; falls back to inline extraction when Workers are unavailable), keeping the\n * main thread free of the multi-second stalls extraction causes at millions of triangles.\n * - Caps bound the pathological cases: meshes above `maxTriangles` are skipped outright (tagged\n * `userData.edgesSkipped = 'triangle-cap'`), overlays above `maxSegments` lose the distance\n * fade so they render in the cheaper opaque pass.\n *\n * Depth strategy: surfaces render at TRUE depth, untouched; the LINES carry a small units-only\n * polygonOffset toward the camera (see EDGE_OFFSET_FACTOR/UNITS).\n *\n * This reverses an earlier strategy that instead pushed each mesh's *surface* back with a\n * slope-scaled offset (factor 1, units 2). That version bled badly: the slope term scales with\n * dZ/dpixel, which is enormous on a surface viewed near edge-on, so grazing faces receded by much\n * more than the millimetre gaps between stacked parts — geometry behind a wall then beat the wall's\n * own receded surface and drew through it. It also clobbered the polygonOffset that look presets\n * configure on their materials, and its \"restore\" path reset those to 0 rather than to the preset's\n * values.\n *\n * A units-only bias on the lines is bounded by construction: a fixed number of depth quantization\n * steps, independent of viewing angle, so it lifts an edge off its own coplanar surface without ever\n * reaching across to a neighbouring part.\n *\n * The caveat the old strategy correctly identified: a depth ULP grows ~quadratically with viewing\n * distance, so a constant bias is only safe while ULPs stay small. That is what the dynamic\n * near-plane fitter (near-plane.ts) buys — it keeps `camera.near` proportional to the camera↔content\n * gap, holding ULPs at micron scale even zoomed well out. The two mechanisms are load-bearing\n * together; weakening the near fit will make this bias start to bleed.\n */\nexport interface EdgeOptions {\n\t/**\n\t * Force a single edge color for every overlay. When omitted (the default), each overlay derives\n\t * its color from its own mesh's material — a darkened tint of the surface — so edges read as the\n\t * object's own outline rather than a uniform black frame. Meshes with no readable material color\n\t * fall back to {@link DEFAULT_EDGE_COLOR}.\n\t */\n\tcolor?: THREE.ColorRepresentation;\n\t/**\n\t * How far to darken the derived edge color toward black, 0–1 (default 0.75). Only applies when\n\t * `color` is omitted. Higher = darker edges; 0 leaves edges the surface color, 1 makes them black.\n\t */\n\tdarken?: number;\n\t/** Edge thickness in CSS px. Default 1.5. */\n\twidth?: number;\n\t/**\n\t * Crease angle in degrees: an edge is kept only where its two faces differ by more than this.\n\t * Default 44. Higher = fewer edges (only sharp creases); lower = more (catches gentle bends).\n\t */\n\tthresholdAngle?: number;\n\t/**\n\t * Fade an overlay out as its own edges crowd together on screen (default true). Edges draw at a\n\t * constant pixel width, so once neighbouring lines sit less than a pixel or two apart they stop\n\t * resolving and merge into a dark smear — worst on layered sheet goods, whose millimetre-pitch\n\t * laminations are sub-pixel at any normal zoom on a metre-scale part. Fading by edge density\n\t * (not by how large the mesh is) returns those parts to a clean shaded read while leaving\n\t * sparsely-edged geometry fully drawn at the same distance.\n\t */\n\tdistanceFade?: boolean;\n\t/**\n\t * Skip meshes above this triangle count entirely (default 4M) — extraction time is linear in\n\t * triangles, and past this bound even the worker path burns seconds for a look the screen-space\n\t * fallback approximates at constant cost. Skipped meshes are tagged\n\t * `userData.edgesSkipped = 'triangle-cap'` so hosts can react (e.g. enable the render-pipeline\n\t * edge pass).\n\t */\n\tmaxTriangles?: number;\n\t/**\n\t * Above this many extracted segments (default 2M), an overlay drops the distance fade so it\n\t * renders opaque — millions of blended fat-line quads are a fill-rate cliff; opaque ones aren't.\n\t */\n\tmaxSegments?: number;\n}\n\n/** Tag on edge overlays so pick/fit/clear logic can recognize and skip or dispose them. */\nexport const EDGE_USERDATA_KIND = 'edge-overlay';\n\n/** `userData.edgesSkipped` value on meshes whose triangle count exceeded {@link EdgeOptions.maxTriangles}. */\nexport const EDGES_SKIPPED_TRIANGLE_CAP = 'triangle-cap';\n\nconst DEFAULT_EDGE_COLOR = 0x222222;\nconst DEFAULT_EDGE_WIDTH = 1.5;\nconst DEFAULT_THRESHOLD_ANGLE = 44;\nconst DEFAULT_DARKEN = 0.75;\nconst DEFAULT_MAX_TRIANGLES = 4_000_000;\nconst DEFAULT_MAX_SEGMENTS = 2_000_000;\n\n/**\n * Below this triangle count extraction runs inline even on the async path — a worker round-trip\n * (copy + transfer + wake) costs more than the extraction itself. Phase 0 measured three's\n * extractor at ~200 ms per 100k triangles; the replacement extractor is ~an order faster, putting\n * 25k triangles well under a frame.\n */\nconst INLINE_TRIANGLE_BUDGET = 25_000;\n\n/** CPU byte budget for the cross-solve segment cache (Float32 segment arrays only). */\nconst SEGMENT_CACHE_BYTE_BUDGET = 128 * 1024 * 1024;\n\n// Edge-density fade band, as the mean on-screen gap between neighbouring edges in px: fully opaque\n// at/above FADE_START_PX, fully gone at/below FADE_END_PX, linear between.\n//\n// Density, not object size, is what breaks the technical look when zoomed out. A big part whose\n// edges have collapsed to sub-pixel spacing is precisely the failure case — every line still draws\n// at full width and full opacity, so they merge into a dark smear that reads as \"all the interior\n// edges showing through\". Fading on the *bounding sphere* instead (the previous rule) never fires\n// for that part at all, because the sphere still covers most of the viewport.\n//\n// The band sits just above 1 px: below ~2 px apart, constant-width lines visibly overlap, and by\n// 1 px they are a solid fill. Fading out across that range returns the part to its shaded read.\nconst FADE_START_PX = 4;\nconst FADE_END_PX = 1;\n\n// Edge pull-forward (see module doc). Units only — deliberately NO slope (factor) term.\n//\n// The slope term scales with the polygon's dZ/dpixel, which is small head-on but very large at\n// grazing angles: on a long surface viewed near edge-on, one pixel spans a lot of depth. Applying it\n// to the *surfaces* (the previous strategy) pushed grazing faces back by far more than the\n// millimetre-scale gaps between stacked parts, so geometry BEHIND a wall won the depth test against\n// the wall's own receded surface and its edges drew straight through — exactly the bleed-through\n// this offset exists to prevent.\n//\n// A units-only bias on the lines is bounded instead: it is a fixed number of depth quantization\n// steps regardless of viewing angle, so it can lift an edge off its own coplanar surface without\n// ever reaching across the gap to a neighbouring part. 1 unit is the minimum that reliably wins\n// z-fighting against the surface the edge was extracted from.\nconst EDGE_OFFSET_FACTOR = 0;\nconst EDGE_OFFSET_UNITS = -1; // negative = toward the camera\n\n// ============================================================================\n// Segment extraction — fast path, content cache, worker offload\n// ============================================================================\n\nfunction triangleCountOf(geometry: THREE.BufferGeometry): number {\n\tconst position = geometry.getAttribute('position');\n\tif (!position) return 0;\n\treturn (geometry.index ? geometry.index.count : position.count) / 3;\n}\n\ninterface FastPathData {\n\tpositions: Float32Array;\n\tindex: Uint32Array | Uint16Array | null;\n}\n\n/**\n * The fast extractor consumes plain non-interleaved float32 xyz + typed index arrays — which is\n * what every geometry in this pipeline has. Anything exotic (interleaved, float64, morphed) falls\n * back to `THREE.EdgesGeometry`, trading speed for guaranteed-identical semantics.\n */\nfunction fastPathData(geometry: THREE.BufferGeometry): FastPathData | null {\n\tconst position = geometry.getAttribute('position');\n\tif (\n\t\t!position ||\n\t\t(position as THREE.InterleavedBufferAttribute).isInterleavedBufferAttribute ||\n\t\tposition.itemSize !== 3 ||\n\t\t!(position.array instanceof Float32Array) ||\n\t\tposition.count >= MAX_EXTRACT_VERTICES\n\t) {\n\t\treturn null;\n\t}\n\tconst index = geometry.index;\n\tif (index && !(index.array instanceof Uint32Array) && !(index.array instanceof Uint16Array)) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tpositions: position.array,\n\t\tindex: index ? (index.array as Uint32Array | Uint16Array) : null\n\t};\n}\n\n/**\n * Content fingerprint for the cross-solve cache: FNV-1a over sampled raw words of the position\n * (and index) arrays plus their lengths and the crease angle. Sampling (head + tail blocks) keeps\n * it ~free even at millions of vertices; two *different* solves colliding would need identical\n * lengths AND identical sampled regions — not a realistic geometry edit.\n */\nfunction contentKey(data: FastPathData, thresholdAngle: number): string {\n\tconst SAMPLE_WORDS = 4096;\n\tlet hash = 0x811c9dc5;\n\tconst mix = (word: number): void => {\n\t\thash ^= word;\n\t\thash = Math.imul(hash, 0x01000193);\n\t};\n\n\tconst words = new Uint32Array(\n\t\tdata.positions.buffer,\n\t\tdata.positions.byteOffset,\n\t\tdata.positions.length\n\t);\n\tconst head = Math.min(SAMPLE_WORDS, words.length);\n\tfor (let i = 0; i < head; i++) mix(words[i]);\n\tfor (let i = Math.max(head, words.length - SAMPLE_WORDS); i < words.length; i++) mix(words[i]);\n\n\tlet indexLength = 0;\n\tif (data.index) {\n\t\tindexLength = data.index.length;\n\t\tconst headIndex = Math.min(SAMPLE_WORDS, indexLength);\n\t\tfor (let i = 0; i < headIndex; i++) mix(data.index[i]);\n\t\tfor (let i = Math.max(headIndex, indexLength - SAMPLE_WORDS); i < indexLength; i++) {\n\t\t\tmix(data.index[i]);\n\t\t}\n\t}\n\n\treturn `${thresholdAngle}:${data.positions.length}:${indexLength}:${hash >>> 0}`;\n}\n\n/**\n * Cross-solve segment cache. The viewer rebuilds every `BufferGeometry` each solve, so identity\n * caches never hit across solves — this LRU keys on content instead, making \"same meshes again\"\n * (unchanged inputs, toggling edges, camera-only updates) free. Stores raw segment arrays (CPU\n * only); `LineSegmentsGeometry` uses the array as its backing store without copying, so entries\n * are safely shared across any number of overlays.\n */\nconst segmentCache = new Map<string, Float32Array>();\nlet segmentCacheBytes = 0;\n\nfunction segmentCacheGet(key: string): Float32Array | undefined {\n\tconst cached = segmentCache.get(key);\n\tif (cached) {\n\t\t// Refresh LRU order.\n\t\tsegmentCache.delete(key);\n\t\tsegmentCache.set(key, cached);\n\t}\n\treturn cached;\n}\n\nfunction segmentCachePut(key: string, segments: Float32Array): void {\n\tif (segments.byteLength > SEGMENT_CACHE_BYTE_BUDGET) return;\n\tconst existing = segmentCache.get(key);\n\tif (existing) {\n\t\tsegmentCacheBytes -= existing.byteLength;\n\t\tsegmentCache.delete(key);\n\t}\n\tsegmentCache.set(key, segments);\n\tsegmentCacheBytes += segments.byteLength;\n\twhile (segmentCacheBytes > SEGMENT_CACHE_BYTE_BUDGET) {\n\t\tconst oldestKey = segmentCache.keys().next().value as string;\n\t\tsegmentCacheBytes -= segmentCache.get(oldestKey)!.byteLength;\n\t\tsegmentCache.delete(oldestKey);\n\t}\n}\n\n/** Extract via `THREE.EdgesGeometry` — the slow but universally-correct fallback. */\nfunction extractViaThree(geometry: THREE.BufferGeometry, thresholdAngle: number): Float32Array {\n\tconst edges = new THREE.EdgesGeometry(geometry, thresholdAngle);\n\tconst positions = edges.attributes.position\n\t\t? (edges.attributes.position.array as Float32Array)\n\t\t: new Float32Array(0);\n\tedges.dispose(); // frees only GPU-side state; the CPU array is the return value\n\treturn positions;\n}\n\n/** Synchronous extraction: content cache → fast extractor → EdgesGeometry fallback. */\nfunction extractSegmentsSync(geometry: THREE.BufferGeometry, thresholdAngle: number): Float32Array {\n\tconst data = fastPathData(geometry);\n\tif (!data) return extractViaThree(geometry, thresholdAngle);\n\n\tconst key = contentKey(data, thresholdAngle);\n\tconst cached = segmentCacheGet(key);\n\tif (cached) return cached;\n\n\tconst segments = extractEdgeSegments(data.positions, data.index, thresholdAngle);\n\tsegmentCachePut(key, segments);\n\treturn segments;\n}\n\n// --- Worker offload -----------------------------------------------------------------------------\n\ninterface PendingRequest {\n\tresolve: (segments: Float32Array) => void;\n\treject: (error: Error) => void;\n}\n\nlet extractionWorker: Worker | null | undefined; // undefined = not yet tried, null = unavailable\nconst pendingRequests = new Map<number, PendingRequest>();\nlet nextRequestId = 1;\n\nfunction getExtractionWorker(): Worker | null {\n\tif (extractionWorker !== undefined) return extractionWorker;\n\tif (\n\t\ttypeof Worker === 'undefined' ||\n\t\ttypeof Blob === 'undefined' ||\n\t\ttypeof URL === 'undefined' ||\n\t\ttypeof URL.createObjectURL !== 'function'\n\t) {\n\t\textractionWorker = null;\n\t\treturn null;\n\t}\n\ttry {\n\t\t// Blob URL keeps the library bundler-agnostic (no `new Worker(new URL(...))` magic). The URL\n\t\t// is deliberately never revoked: revoking before the worker finishes fetching is\n\t\t// unspecified behavior, and one blob URL for a process-lifetime singleton is negligible.\n\t\tconst url = URL.createObjectURL(\n\t\t\tnew Blob([edgeExtractWorkerSource()], { type: 'text/javascript' })\n\t\t);\n\t\tconst worker = new Worker(url);\n\t\tworker.onmessage = (event: MessageEvent) => {\n\t\t\tconst { id, segments, error } = event.data as {\n\t\t\t\tid: number;\n\t\t\t\tsegments?: Float32Array;\n\t\t\t\terror?: string;\n\t\t\t};\n\t\t\tconst pending = pendingRequests.get(id);\n\t\t\tif (!pending) return;\n\t\t\tpendingRequests.delete(id);\n\t\t\tif (segments) pending.resolve(segments);\n\t\t\telse pending.reject(new Error(error ?? 'edge extraction failed in worker'));\n\t\t};\n\t\tworker.onerror = () => {\n\t\t\t// Worker died (CSP, OOM, script error): fail everything in flight — callers fall back to\n\t\t\t// inline extraction — and never try the worker again this session.\n\t\t\tfor (const pending of pendingRequests.values()) {\n\t\t\t\tpending.reject(new Error('edge extraction worker crashed'));\n\t\t\t}\n\t\t\tpendingRequests.clear();\n\t\t\tworker.terminate();\n\t\t\textractionWorker = null;\n\t\t};\n\t\textractionWorker = worker;\n\t} catch {\n\t\textractionWorker = null;\n\t}\n\treturn extractionWorker;\n}\n\nfunction extractInWorker(\n\tworker: Worker,\n\tdata: FastPathData,\n\tthresholdAngle: number\n): Promise<Float32Array> {\n\treturn new Promise<Float32Array>((resolve, reject) => {\n\t\tconst id = nextRequestId++;\n\t\tpendingRequests.set(id, { resolve, reject });\n\t\t// Copy before transfer — the originals back the render geometry.\n\t\tconst positions = data.positions.slice();\n\t\tconst index = data.index ? data.index.slice() : null;\n\t\tconst transfer: Transferable[] = [positions.buffer];\n\t\tif (index) transfer.push(index.buffer);\n\t\tworker.postMessage({ id, positions, index, thresholdAngle }, transfer);\n\t});\n}\n\n/**\n * In-flight dedupe: N meshes with identical content (or repeated applies during one extraction)\n * share one worker round-trip. Keyed by content key; cleared when the request settles (results\n * land in the segment cache, which takes over from there).\n */\nconst inFlightExtractions = new Map<string, Promise<Float32Array>>();\n\n/** Asynchronous extraction: cache → worker (large fast-path meshes) → inline fallback. */\nfunction extractSegmentsAsync(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number\n): Promise<Float32Array> {\n\tconst data = fastPathData(geometry);\n\tif (!data || triangleCountOf(geometry) < INLINE_TRIANGLE_BUDGET) {\n\t\treturn Promise.resolve(extractSegmentsSync(geometry, thresholdAngle));\n\t}\n\n\tconst key = contentKey(data, thresholdAngle);\n\tconst cached = segmentCacheGet(key);\n\tif (cached) return Promise.resolve(cached);\n\n\tconst inFlight = inFlightExtractions.get(key);\n\tif (inFlight) return inFlight;\n\n\tconst worker = getExtractionWorker();\n\tif (!worker) return Promise.resolve(extractSegmentsSync(geometry, thresholdAngle));\n\n\tconst request = extractInWorker(worker, data, thresholdAngle)\n\t\t.catch(() => extractEdgeSegments(data.positions, data.index, thresholdAngle))\n\t\t.then((segments) => {\n\t\t\tsegmentCachePut(key, segments);\n\t\t\treturn segments;\n\t\t})\n\t\t.finally(() => {\n\t\t\tinFlightExtractions.delete(key);\n\t\t});\n\tinFlightExtractions.set(key, request);\n\treturn request;\n}\n\n// ============================================================================\n// Per-geometry line-geometry cache (identity-keyed, refcounted)\n// ============================================================================\n\n/**\n * Extracted edge geometry, cached per source `BufferGeometry` (and per crease angle, since the\n * angle changes which edges survive). N meshes sharing one geometry — the common case for\n * instanced/repeated parts — get one extraction and one GPU buffer instead of N identical ones.\n *\n * Reference-counted so {@link removeEdges} only disposes a line geometry once its last overlay is\n * gone. The WeakMap keys on the source geometry, so entries vanish with the content they describe;\n * overlays disposed by whole-scene clears (which bypass removeEdges) just leave a refcount behind\n * on an entry that becomes unreachable together with its source geometry.\n */\ninterface EdgeGeometryEntry {\n\tgeometry: LineSegmentsGeometry;\n\trefCount: number;\n\tsegmentCount: number;\n\t/**\n\t * Mean world-space spacing between this overlay's edges: the characteristic distance at which\n\t * neighbouring lines sit. Drives the density fade (see {@link enableDistanceFade}) — an overlay\n\t * fades when *this* projects below a pixel, which is when its lines start merging, regardless of\n\t * how large the mesh itself is on screen.\n\t *\n\t * Estimated as area/length: total edge length L spread over the mesh's projected extent A behaves\n\t * like a set of parallel lines A/L apart. Infinity for degenerate cases (no length, no extent), so\n\t * they never fade.\n\t */\n\tedgeSpacing: number;\n}\n\n/**\n * Fraction of segments allowed to be shorter than the reported spacing. A low percentile tracks the\n * *fine* detail rather than the average: real parts mix a handful of long silhouette edges with many\n * short ones, and it is the short ones that merge first.\n */\nconst SPACING_PERCENTILE = 0.15;\n\n/** Cap on segments sampled for the percentile — a stride keeps this O(1) on millions of segments. */\nconst SPACING_SAMPLE_LIMIT = 4096;\n\n/**\n * Characteristic spacing between an overlay's edges, in world units: the\n * {@link SPACING_PERCENTILE} quantile of segment length.\n *\n * Segment length is the right proxy for spacing on the geometry this targets. Layered sheet goods —\n * plywood laminations, stacked panels — produce a ladder of short segments spanning each layer's\n * thickness, so the short-segment population *is* the layer pitch, which is exactly the distance\n * that collapses below a pixel and smears the lines together.\n *\n * A quantile rather than a mean because the two populations differ by orders of magnitude: a 10 m\n * part with 1 mm laminations mixes lengths at 1:10000, and any average of those sits far above the\n * pitch (so the laminations never fade) while still far below the outline (so the outline fades\n * early). Taking a low quantile lets the dense detail drive the fade without the silhouette edges\n * dragging it up. Infinity when there is nothing to measure, which never fades.\n */\nfunction edgeSpacingOf(segments: Float32Array): number {\n\tconst segmentCount = Math.floor(segments.length / 6);\n\tif (segmentCount === 0) return Infinity;\n\n\tconst stride = Math.max(1, Math.ceil(segmentCount / SPACING_SAMPLE_LIMIT));\n\tconst lengths: number[] = [];\n\tfor (let s = 0; s < segmentCount; s += stride) {\n\t\tconst i = s * 6;\n\t\tconst length = Math.hypot(\n\t\t\tsegments[i + 3] - segments[i],\n\t\t\tsegments[i + 4] - segments[i + 1],\n\t\t\tsegments[i + 5] - segments[i + 2]\n\t\t);\n\t\tif (length > 0) lengths.push(length);\n\t}\n\tif (lengths.length === 0) return Infinity;\n\n\tlengths.sort((a, b) => a - b);\n\treturn lengths[Math.min(lengths.length - 1, Math.floor(lengths.length * SPACING_PERCENTILE))];\n}\nconst edgeGeometryCache = new WeakMap<THREE.BufferGeometry, Map<number, EdgeGeometryEntry>>();\n\nfunction cachedEntry(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number\n): EdgeGeometryEntry | undefined {\n\treturn edgeGeometryCache.get(geometry)?.get(thresholdAngle);\n}\n\nfunction storeEntry(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number,\n\tsegments: Float32Array\n): EdgeGeometryEntry {\n\tlet byAngle = edgeGeometryCache.get(geometry);\n\tif (!byAngle) {\n\t\tbyAngle = new Map();\n\t\tedgeGeometryCache.set(geometry, byAngle);\n\t}\n\t// LineSegmentsGeometry adopts `segments` as its backing store without copying — sharing the\n\t// array with the segment cache and with other entries is safe (read-only from here on).\n\tconst lineGeometry = new LineSegmentsGeometry();\n\tlineGeometry.setPositions(segments);\n\tconst entry: EdgeGeometryEntry = {\n\t\tgeometry: lineGeometry,\n\t\trefCount: 0,\n\t\tsegmentCount: segments.length / 6,\n\t\tedgeSpacing: edgeSpacingOf(segments)\n\t};\n\tbyAngle.set(thresholdAngle, entry);\n\treturn entry;\n}\n\n/** Where an overlay's (possibly shared) line geometry came from, for refcounted disposal. */\ninterface EdgeOverlayUserData {\n\tkind: string;\n\tedgeSource?: THREE.BufferGeometry;\n\tedgeThresholdAngle?: number;\n}\n\n/** Refcounted disposal — only when the last overlay referencing an entry is gone. */\nfunction releaseEdgeGeometry(overlay: LineSegments2): void {\n\tconst userData = overlay.userData as EdgeOverlayUserData;\n\tconst byAngle = userData.edgeSource && edgeGeometryCache.get(userData.edgeSource);\n\tconst entry =\n\t\tuserData.edgeThresholdAngle != null ? byAngle?.get(userData.edgeThresholdAngle) : undefined;\n\n\tif (!entry || entry.geometry !== overlay.geometry) {\n\t\t// Not (or no longer) cache-managed — dispose directly.\n\t\toverlay.geometry.dispose();\n\t\treturn;\n\t}\n\n\tentry.refCount -= 1;\n\tif (entry.refCount <= 0) {\n\t\tentry.geometry.dispose();\n\t\tbyAngle!.delete(userData.edgeThresholdAngle!);\n\t}\n}\n\n// ============================================================================\n// Overlay construction\n// ============================================================================\n\ninterface ResolvedOptions {\n\tforcedColor: THREE.Color | null;\n\tdarken: number;\n\twidth: number;\n\tthresholdAngle: number;\n\tdistanceFade: boolean;\n\tmaxTriangles: number;\n\tmaxSegments: number;\n}\n\nfunction resolveOptions(options: EdgeOptions): ResolvedOptions {\n\treturn {\n\t\tforcedColor: options.color != null ? new THREE.Color(options.color) : null,\n\t\tdarken: THREE.MathUtils.clamp(options.darken ?? DEFAULT_DARKEN, 0, 1),\n\t\twidth: options.width ?? DEFAULT_EDGE_WIDTH,\n\t\tthresholdAngle: options.thresholdAngle ?? DEFAULT_THRESHOLD_ANGLE,\n\t\tdistanceFade: options.distanceFade ?? true,\n\t\tmaxTriangles: options.maxTriangles ?? DEFAULT_MAX_TRIANGLES,\n\t\tmaxSegments: options.maxSegments ?? DEFAULT_MAX_SEGMENTS\n\t};\n}\n\n/**\n * Edge color for a mesh when no color is forced: the mesh's own surface color darkened toward black\n * by `darken` (0 = surface color, 1 = black), so edges read as the object's darker outline. Falls\n * back to {@link DEFAULT_EDGE_COLOR} when no material color is readable. Multiplicative darkening\n * preserves hue and desaturates gently; a near-black surface just yields near-black edges.\n */\nfunction deriveEdgeColor(mesh: THREE.Mesh, darken: number): THREE.Color {\n\tconst material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;\n\tconst source = (material as { color?: THREE.Color } | null)?.color;\n\tif (!source) return new THREE.Color(DEFAULT_EDGE_COLOR);\n\treturn source.clone().multiplyScalar(1 - darken);\n}\n\n/**\n * Overlays sharing a color and fade mode share a material: with a forced color that's one material\n * per `addEdges` call; when deriving per-mesh, meshes of the same surface color (instanced/repeated\n * parts) still collapse onto one. The fade bit is part of the key because fading needs\n * `transparent = true` while capped overlays must stay opaque.\n */\nclass MaterialPool {\n\tprivate readonly byKey = new Map<number, LineMaterial>();\n\tconstructor(private readonly options: ResolvedOptions) {}\n\n\tfor(mesh: THREE.Mesh, fade: boolean): LineMaterial {\n\t\tconst color = this.options.forcedColor ?? deriveEdgeColor(mesh, this.options.darken);\n\t\tconst key = color.getHex() * 2 + (fade ? 1 : 0);\n\t\tlet material = this.byKey.get(key);\n\t\tif (!material) {\n\t\t\tmaterial = createEdgeMaterial(color, this.options.width, fade);\n\t\t\tthis.byKey.set(key, material);\n\t\t}\n\t\treturn material;\n\t}\n\n\t/** Dispose any material no overlay adopted (e.g. every mesh was skipped or cancelled). */\n\tdisposeUnused(created: LineSegments2[]): void {\n\t\tconst used = new Set(created.map((overlay) => overlay.material));\n\t\tfor (const material of this.byKey.values()) {\n\t\t\tif (!used.has(material)) material.dispose();\n\t\t}\n\t}\n}\n\nfunction createEdgeMaterial(\n\tcolor: THREE.Color,\n\twidth: number,\n\tdistanceFade: boolean\n): LineMaterial {\n\t// LineMaterialParameters omits linewidth/opacity from its type though both exist at runtime.\n\tconst material = new LineMaterial({ color });\n\t(material as LineMaterial & { linewidth: number }).linewidth = width;\n\t// Lift the lines a fixed couple of quantization steps toward the camera so they win against the\n\t// surface they were extracted from, without touching the surfaces themselves (see the constants).\n\tmaterial.polygonOffset = true;\n\tmaterial.polygonOffsetFactor = EDGE_OFFSET_FACTOR;\n\tmaterial.polygonOffsetUnits = EDGE_OFFSET_UNITS;\n\t// Fading needs blending; set once here rather than per draw, since flipping `transparent` after\n\t// the render list is built wouldn't re-sort the object into the transparent pass.\n\tif (distanceFade) material.transparent = true;\n\treturn material;\n}\n\nfunction buildEdgeOverlay(\n\tsourceGeometry: THREE.BufferGeometry,\n\tentry: EdgeGeometryEntry,\n\tmaterial: LineMaterial,\n\tthresholdAngle: number,\n\tdistanceFade: boolean\n): LineSegments2 {\n\tentry.refCount += 1;\n\n\tconst overlay = new LineSegments2(entry.geometry, material);\n\toverlay.userData.kind = EDGE_USERDATA_KIND;\n\t// Remember which cache entry backs this overlay so removeEdges can refcount its disposal. The\n\t// strong reference is fine: the overlay is a child of the mesh that owns the source geometry,\n\t// so their lifetimes already coincide.\n\toverlay.userData.edgeSource = sourceGeometry;\n\toverlay.userData.edgeThresholdAngle = thresholdAngle;\n\toverlay.raycast = () => {}; // never pickable; clicks should hit the mesh, not its outline\n\tif (distanceFade) enableDistanceFade(overlay, entry.edgeSpacing);\n\treturn overlay;\n}\n\nconst _fadeCenter = new THREE.Vector3();\nconst _fadeCameraPos = new THREE.Vector3();\n\n/**\n * Pixels per world unit at the overlay's centre — the scale that converts a world-space edge spacing\n * into the on-screen gap driving the density fade. Returns Infinity (\"don't fade\") when the\n * projection is unknown or degenerate, and for a perspective camera sitting inside the mesh.\n */\nfunction pixelsPerWorldUnit(\n\toverlay: LineSegments2,\n\tcamera: THREE.Camera,\n\tviewportHeightPx: number\n): number {\n\tif (!overlay.geometry.boundingSphere) overlay.geometry.computeBoundingSphere();\n\tconst sphere = overlay.geometry.boundingSphere;\n\tif (!sphere) return Infinity;\n\n\tif ((camera as THREE.PerspectiveCamera).isPerspectiveCamera) {\n\t\tconst perspective = camera as THREE.PerspectiveCamera;\n\t\t_fadeCenter.copy(sphere.center).applyMatrix4(overlay.matrixWorld);\n\t\tconst distance = _fadeCameraPos\n\t\t\t.setFromMatrixPosition(camera.matrixWorld)\n\t\t\t.distanceTo(_fadeCenter);\n\t\tconst radius = sphere.radius * overlay.matrixWorld.getMaxScaleOnAxis();\n\t\tif (distance <= radius) return Infinity; // camera inside the mesh — no fade\n\t\tconst tanHalfFov = Math.tan(THREE.MathUtils.degToRad(perspective.fov) * 0.5);\n\t\tconst worldHeightAtCentre = 2 * distance * tanHalfFov;\n\t\treturn worldHeightAtCentre > 0 ? viewportHeightPx / worldHeightAtCentre : Infinity;\n\t}\n\tif ((camera as THREE.OrthographicCamera).isOrthographicCamera) {\n\t\tconst ortho = camera as THREE.OrthographicCamera;\n\t\tconst worldHeight = (ortho.top - ortho.bottom) / ortho.zoom;\n\t\treturn worldHeight > 0 ? viewportHeightPx / worldHeight : Infinity;\n\t}\n\treturn Infinity;\n}\n\n/**\n * Fade this overlay by its on-screen size (see FADE_START_PX/FADE_END_PX). Hooked into\n * onBeforeRender so the opacity is written immediately before *this* overlay's draw — uniforms\n * upload per draw call, so overlays sharing one material still fade independently. Chains\n * LineSegments2's own onBeforeRender, which keeps the material's resolution uniform in sync.\n */\nfunction enableDistanceFade(overlay: LineSegments2, edgeSpacing: number): void {\n\t// Assign via the Object3D base type: LineSegments2's typings narrow onBeforeRender to\n\t// (renderer) only, but the renderer actually calls it with (renderer, scene, camera, …).\n\t(overlay as THREE.Object3D).onBeforeRender = (renderer, _scene, camera) => {\n\t\tLineSegments2.prototype.onBeforeRender.call(overlay, renderer);\n\t\tconst material = overlay.material as LineMaterial;\n\t\tconst scale = pixelsPerWorldUnit(overlay, camera, material.resolution.y);\n\t\t// Mean gap between neighbouring edges, on screen. Infinity (unknown projection, camera inside\n\t\t// the mesh) yields Infinity here too, which clamps to fully opaque — never fade on a guess.\n\t\tconst gapPx = edgeSpacing * scale;\n\t\tmaterial.opacity = THREE.MathUtils.clamp(\n\t\t\t(gapPx - FADE_END_PX) / (FADE_START_PX - FADE_END_PX),\n\t\t\t0,\n\t\t\t1\n\t\t);\n\t};\n}\n\n// ============================================================================\n// Public API — add / remove / query\n// ============================================================================\n\n/** Whether an object is an edge overlay (for pick/fit filters elsewhere). */\nexport function isEdgeOverlay(object: THREE.Object3D): boolean {\n\treturn object.userData?.kind === EDGE_USERDATA_KIND;\n}\n\n/** Meshes under `root` that should get an overlay: content meshes without one, caps applied. */\nfunction collectTargets(root: THREE.Object3D, maxTriangles: number): THREE.Mesh[] {\n\tconst targets: THREE.Mesh[] = [];\n\troot.traverse((object) => {\n\t\tif (!(object instanceof THREE.Mesh)) return;\n\t\tif (object.userData.id === 'floor' || object.userData.id === 'grid') return;\n\t\tif (object.userData.kind === EDGE_USERDATA_KIND) return;\n\t\tif (object.children.some((c) => c.userData?.kind === EDGE_USERDATA_KIND)) return; // already done\n\t\tif (!object.geometry) return;\n\n\t\tif (triangleCountOf(object.geometry) > maxTriangles) {\n\t\t\tobject.userData.edgesSkipped = EDGES_SKIPPED_TRIANGLE_CAP;\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.debug(\n\t\t\t\t`[edges] skipping mesh over triangle cap (${triangleCountOf(object.geometry)} > ${maxTriangles})`\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tdelete object.userData.edgesSkipped;\n\t\ttargets.push(object);\n\t});\n\treturn targets;\n}\n\nfunction attachOverlay(\n\tmesh: THREE.Mesh,\n\tentry: EdgeGeometryEntry,\n\tmaterials: MaterialPool,\n\tresolved: ResolvedOptions\n): LineSegments2 {\n\t// Distance fade needs the transparent pass; overlays over the segment cap stay opaque instead\n\t// of skipping outright — see EdgeOptions.maxSegments.\n\tconst fade = resolved.distanceFade && entry.segmentCount <= resolved.maxSegments;\n\tconst overlay = buildEdgeOverlay(\n\t\tmesh.geometry,\n\t\tentry,\n\t\tmaterials.for(mesh, fade),\n\t\tresolved.thresholdAngle,\n\t\tfade\n\t);\n\tmesh.add(overlay); // child → inherits transform, disposed with the parent subtree\n\treturn overlay;\n}\n\n/**\n * Walk an object subtree and attach an edge overlay to every `Mesh` found, returning the created\n * overlays (so callers can dispose them explicitly if they don't clear the whole subtree). Meshes\n * that already carry an overlay are skipped, so this is safe to call more than once.\n *\n * Skips the floor and the grid (they're aids, not content) and anything already tagged as an edge.\n *\n * Fully synchronous — extraction for every mesh runs on the calling thread. Interactive hosts with\n * potentially-large meshes should prefer {@link addEdgesAsync}, which offloads big extractions to\n * a worker.\n */\nexport function addEdges(root: THREE.Object3D, options: EdgeOptions = {}): LineSegments2[] {\n\tconst resolved = resolveOptions(options);\n\tconst materials = new MaterialPool(resolved);\n\tconst created: LineSegments2[] = [];\n\n\tfor (const mesh of collectTargets(root, resolved.maxTriangles)) {\n\t\tconst entry =\n\t\t\tcachedEntry(mesh.geometry, resolved.thresholdAngle) ??\n\t\t\tstoreEntry(\n\t\t\t\tmesh.geometry,\n\t\t\t\tresolved.thresholdAngle,\n\t\t\t\textractSegmentsSync(mesh.geometry, resolved.thresholdAngle)\n\t\t\t);\n\t\tcreated.push(attachOverlay(mesh, entry, materials, resolved));\n\t}\n\n\tmaterials.disposeUnused(created);\n\treturn created;\n}\n\n/**\n * Generation per root: {@link removeEdges} bumps it, and async attaches landing after a bump are\n * dropped — so \"toggle off while extracting\" can't resurrect overlays. Keyed on the root object,\n * which hosts keep stable across solves (the scene).\n */\nconst rootGenerations = new WeakMap<THREE.Object3D, number>();\n\nfunction generationOf(root: THREE.Object3D): number {\n\treturn rootGenerations.get(root) ?? 0;\n}\n\n/** Is `mesh` still reachable from `root`? Guards attaches racing scene clears. */\nfunction isConnected(mesh: THREE.Object3D, root: THREE.Object3D): boolean {\n\tfor (let node: THREE.Object3D | null = mesh; node; node = node.parent) {\n\t\tif (node === root) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Like {@link addEdges}, but extraction for large meshes runs in a Worker so the main thread never\n * stalls. Small meshes (< ~25k triangles) still attach synchronously before this returns — only\n * heavy extractions arrive a beat later. Resolves with every overlay actually attached.\n *\n * Late results are dropped (never attached) when the mesh has left the root's subtree (scene was\n * cleared by a newer solve), the root's edges were removed via {@link removeEdges}, or another\n * apply already attached an overlay to that mesh.\n */\nexport async function addEdgesAsync(\n\troot: THREE.Object3D,\n\toptions: EdgeOptions = {}\n): Promise<LineSegments2[]> {\n\tconst resolved = resolveOptions(options);\n\tconst materials = new MaterialPool(resolved);\n\tconst generation = generationOf(root);\n\tconst created: LineSegments2[] = [];\n\n\tconst attaches = collectTargets(root, resolved.maxTriangles).map(async (mesh) => {\n\t\tlet entry = cachedEntry(mesh.geometry, resolved.thresholdAngle);\n\t\tif (!entry) {\n\t\t\tconst segments = await extractSegmentsAsync(mesh.geometry, resolved.thresholdAngle);\n\t\t\t// Things may have moved on while extracting — attach only if this apply is still wanted.\n\t\t\tif (generationOf(root) !== generation) return;\n\t\t\tif (!isConnected(mesh, root)) return;\n\t\t\tif (mesh.children.some((c) => c.userData?.kind === EDGE_USERDATA_KIND)) return;\n\t\t\tentry = cachedEntry(mesh.geometry, resolved.thresholdAngle);\n\t\t\tif (!entry) entry = storeEntry(mesh.geometry, resolved.thresholdAngle, segments);\n\t\t}\n\t\tcreated.push(attachOverlay(mesh, entry, materials, resolved));\n\t});\n\n\tawait Promise.all(attaches);\n\tmaterials.disposeUnused(created);\n\treturn created;\n}\n\n/**\n * Remove every edge overlay under `root`, disposing its geometry and material. The inverse of\n * {@link addEdges}/{@link addEdgesAsync}; together they make edges a live on/off toggle — this\n * also cancels any in-flight async attaches for `root`. Returns how many were removed.\n */\nexport function removeEdges(root: THREE.Object3D): number {\n\trootGenerations.set(root, generationOf(root) + 1);\n\n\tconst overlays: LineSegments2[] = [];\n\troot.traverse((object) => {\n\t\tif (object instanceof LineSegments2 && isEdgeOverlay(object)) overlays.push(object);\n\t});\n\n\t// One addEdges call shares one material across its overlays — dispose each distinct one once.\n\t// (If `root` covers only part of a call's overlays, survivors self-heal: three recompiles a\n\t// disposed-but-still-referenced material on its next use.)\n\tconst materials = new Set<LineMaterial>();\n\tfor (const overlay of overlays) {\n\t\treleaseEdgeGeometry(overlay); // geometry may be shared across overlays — refcounted dispose\n\t\tmaterials.add(overlay.material as LineMaterial);\n\t\t// Nothing to undo on the parent mesh: the depth bias lives entirely on the overlay's own\n\t\t// material, so surfaces keep whatever polygonOffset their look preset configured.\n\t\toverlay.removeFromParent();\n\t}\n\tmaterials.forEach((material) => material.dispose());\n\treturn overlays.length;\n}\n","/**\n * Dependency-free crease/boundary edge extraction — the hot core behind `addEdges`.\n *\n * Semantically a drop-in for `THREE.EdgesGeometry(geometry, angle)` (same 1e-4 vertex welding,\n * same crease test, same boundary-edge handling, same quirks for 3+-face edges), but built for\n * speed and portability:\n *\n * - Operates on raw typed arrays, so extraction is O(triangles) with **numeric** hashing — no\n * per-vertex template strings, no string-keyed object maps. Phase 0 of\n * docs/plans/4.edge-overlay-performance.md measured three's string hashing at ~2.9 s per 1M\n * triangles; this path exists to remove exactly that.\n * - {@link extractEdgeSegments} is a single self-contained function with zero outer captures\n * (only `Math` and its own arguments), so `Function.prototype.toString` on it yields code that\n * runs unchanged inside a Worker — {@link edgeExtractWorkerSource} builds that script. Keep it\n * that way: importing anything into its body silently breaks the worker path.\n */\n\n/** Vertex ids are packed two-per-double in edge keys; above 2^26 vertices the packing overflows. */\nexport const MAX_EXTRACT_VERTICES = 0x4000000; // 2^26\n\n/**\n * Extract crease + boundary edge segments from raw triangle data.\n *\n * @param positions - Non-interleaved xyz triples (a plain `position` attribute array).\n * @param index - Triangle index array, or null for non-indexed soup.\n * @param thresholdAngleDeg - Keep edges whose adjacent face normals differ by more than this.\n * @returns Segment endpoint pairs `[x0,y0,z0, x1,y1,z1, ...]` — the exact format\n * `LineSegmentsGeometry.setPositions` (and `EdgesGeometry.attributes.position.array`) uses.\n * @throws When `positions` holds ≥ 2^26 vertices (see {@link MAX_EXTRACT_VERTICES}) — callers\n * fall back to `THREE.EdgesGeometry`.\n */\nexport function extractEdgeSegments(\n\tpositions: Float32Array,\n\tindex: Uint32Array | Uint16Array | null,\n\tthresholdAngleDeg: number\n): Float32Array {\n\t// NOTE: self-contained by design (worker stringification) — no outer references besides Math.\n\tconst PRECISION = 1e4; // same quantization grid as THREE.EdgesGeometry\n\tconst ID_BITS = 0x4000000; // 2^26 — two ids pack into one float64-exact integer key\n\tconst thresholdDot = Math.cos((Math.PI / 180) * thresholdAngleDeg);\n\n\tconst vertexCount = positions.length / 3;\n\tif (vertexCount >= ID_BITS) {\n\t\tthrow new Error(`extractEdgeSegments: ${vertexCount} vertices exceeds 2^26 limit`);\n\t}\n\n\t// --- Weld vertices on the quantization grid → canonical id per vertex -------------------\n\t// Rounded coords kept as float64 (huge coordinates stay exact where int32 would overflow);\n\t// the hash only needs int32 truncations — equality always compares the exact values.\n\tconst quantX = new Float64Array(vertexCount);\n\tconst quantY = new Float64Array(vertexCount);\n\tconst quantZ = new Float64Array(vertexCount);\n\tfor (let v = 0; v < vertexCount; v++) {\n\t\tquantX[v] = Math.round(positions[3 * v] * PRECISION);\n\t\tquantY[v] = Math.round(positions[3 * v + 1] * PRECISION);\n\t\tquantZ[v] = Math.round(positions[3 * v + 2] * PRECISION);\n\t}\n\n\t// Open-addressed table (linear probing): slot → first vertex id seen at that grid point.\n\tlet capacity = 16;\n\twhile (capacity < vertexCount * 2) capacity <<= 1;\n\tconst mask = capacity - 1;\n\tconst table = new Int32Array(capacity).fill(-1);\n\tconst canonical = new Int32Array(vertexCount);\n\tfor (let v = 0; v < vertexCount; v++) {\n\t\tlet slot =\n\t\t\t(Math.imul(quantX[v] | 0, 73856093) ^\n\t\t\t\tMath.imul(quantY[v] | 0, 19349663) ^\n\t\t\t\tMath.imul(quantZ[v] | 0, 83492791)) &\n\t\t\tmask;\n\t\tfor (;;) {\n\t\t\tconst existing = table[slot];\n\t\t\tif (existing === -1) {\n\t\t\t\ttable[slot] = v;\n\t\t\t\tcanonical[v] = v;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tquantX[existing] === quantX[v] &&\n\t\t\t\tquantY[existing] === quantY[v] &&\n\t\t\t\tquantZ[existing] === quantZ[v]\n\t\t\t) {\n\t\t\t\tcanonical[v] = existing;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tslot = (slot + 1) & mask;\n\t\t}\n\t}\n\n\t// --- Growable segment output ------------------------------------------------------------\n\tlet out = new Float32Array(4096);\n\tlet outLength = 0;\n\tconst emit = (i0: number, i1: number): void => {\n\t\tif (outLength + 6 > out.length) {\n\t\t\tconst grown = new Float32Array(out.length * 2);\n\t\t\tgrown.set(out);\n\t\t\tout = grown;\n\t\t}\n\t\tout[outLength++] = positions[3 * i0];\n\t\tout[outLength++] = positions[3 * i0 + 1];\n\t\tout[outLength++] = positions[3 * i0 + 2];\n\t\tout[outLength++] = positions[3 * i1];\n\t\tout[outLength++] = positions[3 * i1 + 1];\n\t\tout[outLength++] = positions[3 * i1 + 2];\n\t};\n\n\t// --- Walk triangles, pairing opposite-winding edges -------------------------------------\n\t// Mirrors EdgesGeometry: a directed edge a→b matches a pending b→a; on match the segment is\n\t// kept iff the face normals differ beyond the threshold, and the pending entry is tombstoned\n\t// (key kept, value -1) so a third face on the same edge re-registers it — quirk preserved.\n\t// Unmatched entries at the end are boundary edges and always emitted.\n\tconst edgeSlots = new Map<number, number>(); // directed key → pending-edge slot, -1 = matched\n\tconst pendingIndex0: number[] = []; // original vertex indices, for boundary emission\n\tconst pendingIndex1: number[] = [];\n\tconst pendingNormals: number[] = []; // xyz per pending edge\n\n\tconst triCount = (index ? index.length : vertexCount) / 3;\n\tfor (let t = 0; t < triCount; t++) {\n\t\tconst i0 = index ? index[3 * t] : 3 * t;\n\t\tconst i1 = index ? index[3 * t + 1] : 3 * t + 1;\n\t\tconst i2 = index ? index[3 * t + 2] : 3 * t + 2;\n\t\tconst a = canonical[i0];\n\t\tconst b = canonical[i1];\n\t\tconst c = canonical[i2];\n\n\t\t// Degenerate on the quantization grid — skip, as EdgesGeometry does.\n\t\tif (a === b || b === c || c === a) continue;\n\n\t\t// Face normal, computed exactly as Triangle.getNormal: normalize((c-b) × (a-b)).\n\t\tconst e0x = positions[3 * i2] - positions[3 * i1];\n\t\tconst e0y = positions[3 * i2 + 1] - positions[3 * i1 + 1];\n\t\tconst e0z = positions[3 * i2 + 2] - positions[3 * i1 + 2];\n\t\tconst e1x = positions[3 * i0] - positions[3 * i1];\n\t\tconst e1y = positions[3 * i0 + 1] - positions[3 * i1 + 1];\n\t\tconst e1z = positions[3 * i0 + 2] - positions[3 * i1 + 2];\n\t\tlet nx = e0y * e1z - e0z * e1y;\n\t\tlet ny = e0z * e1x - e0x * e1z;\n\t\tlet nz = e0x * e1y - e0y * e1x;\n\t\tconst lengthSq = nx * nx + ny * ny + nz * nz;\n\t\tif (lengthSq > 0) {\n\t\t\tconst inverseLength = 1 / Math.sqrt(lengthSq);\n\t\t\tnx *= inverseLength;\n\t\t\tny *= inverseLength;\n\t\t\tnz *= inverseLength;\n\t\t} else {\n\t\t\tnx = 0;\n\t\t\tny = 0;\n\t\t\tnz = 0;\n\t\t}\n\n\t\tfor (let j = 0; j < 3; j++) {\n\t\t\tlet from: number;\n\t\t\tlet to: number;\n\t\t\tlet fromCanonical: number;\n\t\t\tlet toCanonical: number;\n\t\t\tif (j === 0) {\n\t\t\t\tfrom = i0;\n\t\t\t\tto = i1;\n\t\t\t\tfromCanonical = a;\n\t\t\t\ttoCanonical = b;\n\t\t\t} else if (j === 1) {\n\t\t\t\tfrom = i1;\n\t\t\t\tto = i2;\n\t\t\t\tfromCanonical = b;\n\t\t\t\ttoCanonical = c;\n\t\t\t} else {\n\t\t\t\tfrom = i2;\n\t\t\t\tto = i0;\n\t\t\t\tfromCanonical = c;\n\t\t\t\ttoCanonical = a;\n\t\t\t}\n\n\t\t\tconst reverseKey = toCanonical * ID_BITS + fromCanonical;\n\t\t\tconst reverseSlot = edgeSlots.get(reverseKey);\n\t\t\tif (reverseSlot !== undefined && reverseSlot !== -1) {\n\t\t\t\tconst dot =\n\t\t\t\t\tnx * pendingNormals[3 * reverseSlot] +\n\t\t\t\t\tny * pendingNormals[3 * reverseSlot + 1] +\n\t\t\t\t\tnz * pendingNormals[3 * reverseSlot + 2];\n\t\t\t\tif (dot <= thresholdDot) emit(from, to);\n\t\t\t\tedgeSlots.set(reverseKey, -1);\n\t\t\t} else {\n\t\t\t\tconst forwardKey = fromCanonical * ID_BITS + toCanonical;\n\t\t\t\tif (!edgeSlots.has(forwardKey)) {\n\t\t\t\t\tconst slot = pendingIndex0.length;\n\t\t\t\t\tedgeSlots.set(forwardKey, slot);\n\t\t\t\t\tpendingIndex0.push(from);\n\t\t\t\t\tpendingIndex1.push(to);\n\t\t\t\t\tpendingNormals.push(nx, ny, nz);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Unmatched edges are boundaries — always kept ---------------------------------------\n\tfor (const slot of edgeSlots.values()) {\n\t\tif (slot !== -1) emit(pendingIndex0[slot], pendingIndex1[slot]);\n\t}\n\n\treturn out.slice(0, outLength);\n}\n\n/**\n * Build the source of a Worker that runs {@link extractEdgeSegments} off the main thread.\n * Protocol: receives `{id, positions, index, thresholdAngle}`, replies `{id, segments}` with the\n * segment buffer transferred, or `{id, error}` on failure.\n *\n * Relies on `extractEdgeSegments` stringifying to standalone code — guarded by a unit test that\n * evals this source in isolation.\n */\nexport function edgeExtractWorkerSource(): string {\n\treturn [\n\t\t`const extract = ${extractEdgeSegments.toString()};`,\n\t\t`self.onmessage = (event) => {`,\n\t\t` const { id, positions, index, thresholdAngle } = event.data;`,\n\t\t` try {`,\n\t\t` const segments = extract(positions, index, thresholdAngle);`,\n\t\t` self.postMessage({ id, segments }, [segments.buffer]);`,\n\t\t` } catch (error) {`,\n\t\t` self.postMessage({ id, error: String((error && error.message) || error) });`,\n\t\t` }`,\n\t\t`};`\n\t].join('\\n');\n}\n","import * as THREE from 'three';\nimport { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';\n\n/**\n * Screen-space edge detection: draws crease/silhouette lines by finding depth and normal\n * discontinuities, as a fullscreen pass — cost is O(pixels), independent of triangle count.\n *\n * This is the fallback look for scenes too heavy for geometry edge overlays (see\n * docs/plans/4.edge-overlay-performance.md Phase 3): meshes over `EdgeOptions.maxTriangles` skip\n * extraction, and this pass approximates the technical-drawing read at constant cost. Trade-offs\n * vs geometry edges: uniform pixel width, one global color (no per-object tinting), view-dependent\n * response, and gentle creases below the normal threshold don't register.\n *\n * Works like GTAOPass internally: the scene is re-rendered with a `MeshNormalMaterial` override\n * into a normal target carrying a depth texture (a pattern this scene already tolerates for AO),\n * then a fullscreen shader Roberts-crosses depth (relative view-Z difference, so far scenes don't\n * dissolve into noise) and normals, and blends the edge color over the composed image.\n *\n * The render target is allocated lazily on first enabled render, so constructing the pass\n * disabled costs nothing but the material.\n */\nexport interface EdgeDetectionOptions {\n\t/** Edge line color. Default 0x222222 — matches the geometry overlays' default. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** Edge blend strength 0–1. Default 1. */\n\topacity?: number;\n\t/**\n\t * Normal discontinuity threshold, in summed `1 - dot(n₁, n₂)` across the two diagonal pairs.\n\t * Lower catches gentler creases. Default 0.4 (≈ the 44° crease default of geometry edges).\n\t */\n\tnormalThreshold?: number;\n\t/** Relative view-depth discontinuity threshold. Default 0.02 (2% of the center depth). */\n\tdepthThreshold?: number;\n\t/** Sample offset in device px — line thickness. Default 1. */\n\tthickness?: number;\n}\n\nconst EDGE_SHADER = {\n\tuniforms: {\n\t\ttDiffuse: { value: null as THREE.Texture | null },\n\t\ttNormal: { value: null as THREE.Texture | null },\n\t\ttDepth: { value: null as THREE.Texture | null },\n\t\tuResolution: { value: new THREE.Vector2(1, 1) },\n\t\tuColor: { value: new THREE.Color(0x222222) },\n\t\tuOpacity: { value: 1 },\n\t\tuNormalThreshold: { value: 0.4 },\n\t\tuDepthThreshold: { value: 0.02 },\n\t\tuThickness: { value: 1 },\n\t\tuNear: { value: 0.1 },\n\t\tuFar: { value: 1000 },\n\t\tuPerspective: { value: 1 }\n\t},\n\tvertexShader: /* glsl */ `\n\t\tvarying vec2 vUv;\n\t\tvoid main() {\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n\t\t}\n\t`,\n\tfragmentShader: /* glsl */ `\n\t\tuniform sampler2D tDiffuse;\n\t\tuniform sampler2D tNormal;\n\t\tuniform sampler2D tDepth;\n\t\tuniform vec2 uResolution;\n\t\tuniform vec3 uColor;\n\t\tuniform float uOpacity;\n\t\tuniform float uNormalThreshold;\n\t\tuniform float uDepthThreshold;\n\t\tuniform float uThickness;\n\t\tuniform float uNear;\n\t\tuniform float uFar;\n\t\tuniform float uPerspective;\n\t\tvarying vec2 vUv;\n\n\t\tfloat viewZOf(const in float depth) {\n\t\t\tfloat perspective = (uNear * uFar) / ((uFar - uNear) * depth - uFar);\n\t\t\tfloat orthographic = -(depth * (uFar - uNear) + uNear);\n\t\t\treturn mix(orthographic, perspective, uPerspective);\n\t\t}\n\n\t\tvoid main() {\n\t\t\tvec4 color = texture2D(tDiffuse, vUv);\n\t\t\tvec2 texel = uThickness / uResolution;\n\n\t\t\t// Roberts cross over the two diagonal pairs.\n\t\t\tvec2 offsetA = vec2(texel.x, texel.y);\n\t\t\tvec2 offsetB = vec2(texel.x, -texel.y);\n\n\t\t\tfloat z0 = viewZOf(texture2D(tDepth, vUv + offsetA).x);\n\t\t\tfloat z1 = viewZOf(texture2D(tDepth, vUv - offsetA).x);\n\t\t\tfloat z2 = viewZOf(texture2D(tDepth, vUv + offsetB).x);\n\t\t\tfloat z3 = viewZOf(texture2D(tDepth, vUv - offsetB).x);\n\t\t\tfloat zCenter = viewZOf(texture2D(tDepth, vUv).x);\n\t\t\t// Relative difference: a constant threshold in absolute Z turns distant geometry into\n\t\t\t// noise (depth precision) and near geometry blind; normalizing by the center depth keeps\n\t\t\t// the response scale-invariant across the viewer's mm→m scenes.\n\t\t\tfloat depthDelta = (abs(z0 - z1) + abs(z2 - z3)) / max(abs(zCenter), 1e-6);\n\t\t\tfloat depthEdge = step(uDepthThreshold, depthDelta);\n\n\t\t\tvec3 n0 = texture2D(tNormal, vUv + offsetA).rgb * 2.0 - 1.0;\n\t\t\tvec3 n1 = texture2D(tNormal, vUv - offsetA).rgb * 2.0 - 1.0;\n\t\t\tvec3 n2 = texture2D(tNormal, vUv + offsetB).rgb * 2.0 - 1.0;\n\t\t\tvec3 n3 = texture2D(tNormal, vUv - offsetB).rgb * 2.0 - 1.0;\n\t\t\tfloat normalDelta = (1.0 - dot(n0, n1)) + (1.0 - dot(n2, n3));\n\t\t\tfloat normalEdge = step(uNormalThreshold, normalDelta);\n\n\t\t\tfloat edge = max(depthEdge, normalEdge) * uOpacity;\n\t\t\tgl_FragColor = vec4(mix(color.rgb, uColor, edge), color.a);\n\t\t}\n\t`\n};\n\nexport class EdgeDetectionPass extends Pass {\n\tcamera: THREE.Camera;\n\n\tprivate readonly scene: THREE.Scene;\n\tprivate readonly normalMaterial: THREE.MeshNormalMaterial;\n\tprivate readonly edgeMaterial: THREE.ShaderMaterial;\n\tprivate readonly fsQuad: FullScreenQuad;\n\tprivate normalTarget: THREE.WebGLRenderTarget | null = null;\n\tprivate width: number;\n\tprivate height: number;\n\n\tconstructor(\n\t\tscene: THREE.Scene,\n\t\tcamera: THREE.Camera,\n\t\twidth: number,\n\t\theight: number,\n\t\toptions: EdgeDetectionOptions = {}\n\t) {\n\t\tsuper();\n\t\tthis.scene = scene;\n\t\tthis.camera = camera;\n\t\tthis.width = Math.max(1, width);\n\t\tthis.height = Math.max(1, height);\n\n\t\tthis.normalMaterial = new THREE.MeshNormalMaterial();\n\t\tthis.normalMaterial.blending = THREE.NoBlending;\n\n\t\tthis.edgeMaterial = new THREE.ShaderMaterial({\n\t\t\tuniforms: THREE.UniformsUtils.clone(EDGE_SHADER.uniforms),\n\t\t\tvertexShader: EDGE_SHADER.vertexShader,\n\t\t\tfragmentShader: EDGE_SHADER.fragmentShader\n\t\t});\n\t\tconst uniforms = this.edgeMaterial.uniforms;\n\t\tuniforms.uColor.value = new THREE.Color(options.color ?? 0x222222);\n\t\tuniforms.uOpacity.value = options.opacity ?? 1;\n\t\tuniforms.uNormalThreshold.value = options.normalThreshold ?? 0.4;\n\t\tuniforms.uDepthThreshold.value = options.depthThreshold ?? 0.02;\n\t\tuniforms.uThickness.value = options.thickness ?? 1;\n\n\t\tthis.fsQuad = new FullScreenQuad(this.edgeMaterial);\n\t\tthis.needsSwap = true;\n\t}\n\n\tprivate acquireNormalTarget(): THREE.WebGLRenderTarget {\n\t\tif (!this.normalTarget) {\n\t\t\tconst depthTexture = new THREE.DepthTexture(this.width, this.height);\n\t\t\tthis.normalTarget = new THREE.WebGLRenderTarget(this.width, this.height, {\n\t\t\t\tminFilter: THREE.NearestFilter,\n\t\t\t\tmagFilter: THREE.NearestFilter,\n\t\t\t\tdepthTexture\n\t\t\t});\n\t\t}\n\t\treturn this.normalTarget;\n\t}\n\n\toverride setSize(width: number, height: number): void {\n\t\tthis.width = Math.max(1, width);\n\t\tthis.height = Math.max(1, height);\n\t\tthis.normalTarget?.setSize(this.width, this.height);\n\t}\n\n\toverride render(\n\t\trenderer: THREE.WebGLRenderer,\n\t\twriteBuffer: THREE.WebGLRenderTarget,\n\t\treadBuffer: THREE.WebGLRenderTarget\n\t): void {\n\t\tconst normalTarget = this.acquireNormalTarget();\n\n\t\t// --- Normals + depth prepass (override material, like GTAOPass's normal pass) ---\n\t\tconst previousTarget = renderer.getRenderTarget();\n\t\tconst previousAutoClear = renderer.autoClear;\n\t\tconst previousClearColor = renderer.getClearColor(new THREE.Color());\n\t\tconst previousClearAlpha = renderer.getClearAlpha();\n\t\tconst previousOverride = this.scene.overrideMaterial;\n\n\t\trenderer.setRenderTarget(normalTarget);\n\t\t// 0x7777ff ≈ packed +Z: background pixels get a uniform normal, so only depth silhouettes\n\t\t// (not normal noise) separate objects from empty space.\n\t\trenderer.setClearColor(0x7777ff, 1);\n\t\trenderer.autoClear = true;\n\t\tthis.scene.overrideMaterial = this.normalMaterial;\n\t\trenderer.render(this.scene, this.camera);\n\t\tthis.scene.overrideMaterial = previousOverride;\n\t\trenderer.setClearColor(previousClearColor, previousClearAlpha);\n\t\trenderer.autoClear = previousAutoClear;\n\n\t\t// --- Edge composite ---\n\t\tconst uniforms = this.edgeMaterial.uniforms;\n\t\tuniforms.tDiffuse.value = readBuffer.texture;\n\t\tuniforms.tNormal.value = normalTarget.texture;\n\t\tuniforms.tDepth.value = normalTarget.depthTexture;\n\t\tuniforms.uResolution.value.set(this.width, this.height);\n\t\tconst perspective = this.camera as Partial<THREE.PerspectiveCamera>;\n\t\tuniforms.uPerspective.value = perspective.isPerspectiveCamera ? 1 : 0;\n\t\tuniforms.uNear.value = (this.camera as THREE.PerspectiveCamera).near ?? 0.1;\n\t\tuniforms.uFar.value = (this.camera as THREE.PerspectiveCamera).far ?? 1000;\n\n\t\trenderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);\n\t\tthis.fsQuad.render(renderer);\n\t\trenderer.setRenderTarget(previousTarget);\n\t}\n\n\toverride dispose(): void {\n\t\tthis.normalTarget?.dispose();\n\t\tthis.normalMaterial.dispose();\n\t\tthis.edgeMaterial.dispose();\n\t\tthis.fsQuad.dispose();\n\t}\n}\n","import * as THREE from 'three';\nimport { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';\nimport { RenderPass } from 'three/addons/postprocessing/RenderPass.js';\nimport { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';\nimport { SMAAPass } from 'three/addons/postprocessing/SMAAPass.js';\nimport { OutputPass } from 'three/addons/postprocessing/OutputPass.js';\n\nimport { EdgeDetectionPass, type EdgeDetectionOptions } from './edge-detection-pass';\n\n/**\n * Optional postprocessing pipeline. Default-OFF: the viewer only constructs this when a\n * postprocessed feature (ambient occlusion, screen-space edges) is enabled, and otherwise renders\n * with a plain `renderer.render` so the cheap path stays cheap (the chosen tradeoff — see\n * cad-viewer-plan.md).\n *\n * Pipeline: RenderPass → GTAOPass? → EdgeDetectionPass? → SMAAPass → OutputPass. GTAO\n * (ground-truth AO) is the modern replacement for SSAO/SAO — better contact shadows in crevices,\n * the \"engineered\" depth cue. `screenSpaceRadius` is on so the AO radius is in screen space, which\n * keeps it scale-robust across the viewer's mm→m scenes without per-scene tuning.\n *\n * EdgeDetectionPass draws crease/silhouette lines in screen space at O(pixels) — the fallback for\n * scenes too triangle-heavy for geometry edge overlays (docs/plans/4.edge-overlay-performance.md).\n * It sits before SMAA so its 1px lines get antialiased. Always constructed (its render target is\n * lazy), so it can be toggled at runtime via {@link RenderPipeline.setEdgeDetection} without a\n * pipeline rebuild.\n *\n * SMAA restores antialiasing on this path. The EffectComposer renders into an offscreen target, so\n * the WebGLRenderer's own MSAA (`antialias: true`) does nothing here — without a dedicated AA pass,\n * enabling AO would visibly *worsen* edge quality. SMAA is chosen over TAA because TAA's temporal\n * jitter smears during OrbitControls drags; SMAA is single-frame, cheap, and stable while orbiting.\n *\n * OutputPass applies tone mapping + color space last (taking over the roles the renderer did\n * directly in the non-composer path), so SMAA operates on the pre-tonemapped image as intended.\n *\n * Camera swaps: the active camera can flip perspective↔ortho. Rather than rebuild the composer, we\n * retarget the passes' `camera` each render via {@link setCamera}.\n */\n\nexport interface RenderPipeline {\n\trender(deltaTime: number): void;\n\tsetSize(width: number, height: number, pixelRatio: number): void;\n\t/** Point the passes at the currently active camera (call when projection changes). */\n\tsetCamera(camera: THREE.Camera): void;\n\t/** Toggle the screen-space edge pass at runtime (no pipeline rebuild). */\n\tsetEdgeDetection(enabled: boolean): void;\n\t/** Whether the screen-space edge pass currently runs. */\n\tedgeDetectionEnabled(): boolean;\n\tdispose(): void;\n}\n\nexport interface RenderPipelineOptions {\n\t/** Tone mapping to apply in OutputPass (mirror the renderer's). */\n\ttoneMapping: THREE.ToneMapping;\n\ttoneMappingExposure: number;\n\t/** Build the pipeline with the GTAO ambient-occlusion pass. Default true. */\n\tambientOcclusion?: boolean;\n\t/** AO strength 0–1. Default 1. */\n\taoIntensity?: number;\n\t/**\n\t * Cap on the device-pixel-ratio used for the composer's (AO) buffers. AO is low-frequency, so\n\t * rendering below the display DPR is nearly invisible but far cheaper. `setSize`'s incoming\n\t * pixelRatio is clamped to this. Default 1.\n\t */\n\taoPixelRatio?: number;\n\t/**\n\t * Start with the screen-space edge pass enabled; pass an object to tune it. The pass itself is\n\t * always constructed (cheap while disabled) so it can be toggled later via `setEdgeDetection`.\n\t */\n\tedgeDetection?: boolean | EdgeDetectionOptions;\n}\n\nexport function createRenderPipeline(\n\trenderer: THREE.WebGLRenderer,\n\tscene: THREE.Scene,\n\tcamera: THREE.Camera,\n\twidth: number,\n\theight: number,\n\toptions: RenderPipelineOptions\n): RenderPipeline {\n\tconst composer = new EffectComposer(renderer);\n\n\tconst renderPass = new RenderPass(scene, camera);\n\tcomposer.addPass(renderPass);\n\n\tlet gtaoPass: GTAOPass | null = null;\n\tif (options.ambientOcclusion ?? true) {\n\t\tgtaoPass = new GTAOPass(scene, camera, width, height);\n\t\tgtaoPass.blendIntensity = options.aoIntensity ?? 1;\n\t\tgtaoPass.updateGtaoMaterial({ screenSpaceRadius: true });\n\t\tcomposer.addPass(gtaoPass);\n\t}\n\n\tconst edgeOptions = typeof options.edgeDetection === 'object' ? options.edgeDetection : {};\n\tconst edgePass = new EdgeDetectionPass(scene, camera, width, height, edgeOptions);\n\tedgePass.enabled = !!options.edgeDetection;\n\tcomposer.addPass(edgePass);\n\n\t// Restore antialiasing lost when rendering through the composer's offscreen target (see header).\n\t// Sized by composer.setSize below, like every other pass.\n\tconst smaaPass = new SMAAPass();\n\tcomposer.addPass(smaaPass);\n\n\tconst outputPass = new OutputPass();\n\tcomposer.addPass(outputPass);\n\n\t// OutputPass owns tone mapping in the composer path; match the renderer's settings.\n\trenderer.toneMapping = options.toneMapping;\n\trenderer.toneMappingExposure = options.toneMappingExposure;\n\n\t// Clamp the composer's DPR so GTAO's buffers don't render at the full display resolution (4× the\n\t// pixels on a DPR-2 Retina panel). AO is low-frequency; a 1× buffer upscales near-invisibly.\n\tconst aoPixelRatioCap = options.aoPixelRatio ?? 1;\n\tcomposer.setSize(width, height);\n\n\treturn {\n\t\trender: (deltaTime) => composer.render(deltaTime),\n\t\t// composer.setSize propagates the pixel-ratio-multiplied size to every pass; calling\n\t\t// pass.setSize(w, h) here again would knock the AO/AA targets back down to logical CSS size.\n\t\tsetSize: (w, h, pixelRatio) => {\n\t\t\tcomposer.setPixelRatio(Math.min(pixelRatio, aoPixelRatioCap));\n\t\t\tcomposer.setSize(w, h);\n\t\t},\n\t\tsetCamera: (cam) => {\n\t\t\trenderPass.camera = cam;\n\t\t\tedgePass.camera = cam;\n\t\t\tif (!gtaoPass) return;\n\t\t\tgtaoPass.camera = cam;\n\t\t\t// GTAOPass bakes the camera type into its AO shader as a define at construction; merely\n\t\t\t// reassigning `camera` leaves the old projection's depth/view-position reconstruction\n\t\t\t// active (garbage AO after a perspective ⇄ ortho toggle). Refresh the define — and force a\n\t\t\t// shader recompile — whenever the projection type actually changes. Near/far/projection\n\t\t\t// uniforms need no handling here: GTAOPass.render() re-reads them from `camera` per frame.\n\t\t\t// (EdgeDetectionPass needs none of this: it reads camera type + near/far per render.)\n\t\t\tconst isPerspective = (cam as Partial<THREE.PerspectiveCamera>).isPerspectiveCamera ? 1 : 0;\n\t\t\tif (gtaoPass.gtaoMaterial.defines.PERSPECTIVE_CAMERA !== isPerspective) {\n\t\t\t\tgtaoPass.gtaoMaterial.defines.PERSPECTIVE_CAMERA = isPerspective;\n\t\t\t\tgtaoPass.gtaoMaterial.needsUpdate = true;\n\t\t\t}\n\t\t},\n\t\tsetEdgeDetection: (enabled) => {\n\t\t\tedgePass.enabled = enabled;\n\t\t},\n\t\tedgeDetectionEnabled: () => edgePass.enabled,\n\t\t// composer.dispose() doesn't free added passes — dispose them explicitly.\n\t\tdispose: () => {\n\t\t\tcomposer.dispose();\n\t\t\tgtaoPass?.dispose();\n\t\t\tedgePass.dispose();\n\t\t\tsmaaPass.dispose();\n\t\t\toutputPass.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';\n\n/**\n * An HTML label layer that tracks 3D positions, via three's {@link CSS2DRenderer}. Labels are real\n * DOM nodes (crisp text, CSS-stylable) positioned each frame to follow points in the scene — the\n * foundation for measurement readouts, dimension annotations, and point tags.\n *\n * The CSS2D renderer draws into its own absolutely-positioned DOM overlay stacked on top of the\n * WebGL canvas (pointer-events disabled so it never steals clicks from the viewer). The viewer owns\n * one of these; features like the measure tool add/remove labels through it.\n */\n\nexport interface LabelHandle {\n\t/** The CSS2DObject in the scene graph. */\n\treadonly object: CSS2DObject;\n\t/** Move the label to a new world position. */\n\tsetPosition(position: THREE.Vector3): void;\n\t/** Replace the label's text/HTML. */\n\tsetText(text: string): void;\n\t/** Remove the label from the scene and the DOM. */\n\tremove(): void;\n}\n\nexport interface LabelLayer {\n\t/** Create a label at a world position. `className` lets callers theme groups of labels. */\n\taddLabel(text: string, position: THREE.Vector3, className?: string): LabelHandle;\n\t/** Render the DOM overlay. Call each frame after the WebGL render, with the active camera. */\n\trender(scene: THREE.Scene, camera: THREE.Camera): void;\n\tsetSize(width: number, height: number): void;\n\tdispose(): void;\n}\n\n/**\n * @param container element to overlay labels onto — normally the canvas's parent, so the overlay and\n * canvas share a positioning context. The overlay is appended here and absolutely positioned.\n * @param scene labels are parented to a group added to this scene, so they render and follow the\n * camera without the caller wiring scene-graph parenting.\n */\nexport function createLabelLayer(container: HTMLElement, scene: THREE.Scene): LabelLayer {\n\tconst renderer = new CSS2DRenderer();\n\tconst dom = renderer.domElement;\n\tdom.style.position = 'absolute';\n\tdom.style.top = '0';\n\tdom.style.left = '0';\n\t// The overlay must never intercept viewer interaction. CSS2DRenderer sizes its root div to the\n\t// renderer size and stacks it above the canvas; without an explicit non-interactive, clipped box\n\t// it can cover the canvas and swallow orbit/clicks. Note the box is sized in PIXELS by\n\t// `setSize` (CSS2DRenderer overwrites width/height styles and bases its projection math on the\n\t// same values, so percentage sizing can't work here) — the host's resize handling must call\n\t// `setSize` whenever the container resizes, exactly as it does for the WebGL renderer.\n\tdom.style.overflow = 'hidden';\n\tdom.style.pointerEvents = 'none';\n\t// Stack above the canvas and any host overlays (e.g. blur/loading scrims) that share the\n\t// container's positioning context — without an explicit z-index the overlay sits at z-auto and\n\t// such scrims paint over the labels. Kept below typical menu/popover layers.\n\tdom.style.zIndex = '30';\n\t// The container is the canvas's positioning context; make sure it actually establishes one.\n\tif (getComputedStyle(container).position === 'static') {\n\t\tcontainer.style.position = 'relative';\n\t}\n\tcontainer.appendChild(dom);\n\n\tconst size = { width: container.clientWidth || 1, height: container.clientHeight || 1 };\n\trenderer.setSize(size.width, size.height);\n\n\t// Labels live under a dedicated group so they're easy to find/exclude and removed en masse on\n\t// dispose. Tagged so pick/fit logic ignores it.\n\tconst group = new THREE.Group();\n\tgroup.name = 'label-layer';\n\tgroup.userData.id = 'label-layer';\n\tscene.add(group);\n\n\tconst labels = new Set<CSS2DObject>();\n\n\tconst addLabel = (text: string, position: THREE.Vector3, className?: string): LabelHandle => {\n\t\tconst el = document.createElement('div');\n\t\tel.textContent = text;\n\t\tif (className) {\n\t\t\tel.className = className;\n\t\t} else {\n\t\t\t// Default styling that stays legible on any background (light or dark scene/page): a dark\n\t\t\t// translucent pill with light text. Callers wanting their own look pass a className, which\n\t\t\t// opts out of all of this. Kept inline so the layer needs no external stylesheet.\n\t\t\tObject.assign(el.style, {\n\t\t\t\tpadding: '2px 6px',\n\t\t\t\tborderRadius: '4px',\n\t\t\t\tbackground: 'rgba(20, 20, 20, 0.78)',\n\t\t\t\tcolor: '#fff',\n\t\t\t\tfont: '12px/1.3 system-ui, sans-serif',\n\t\t\t\t// `pre` so a multi-line readout (e.g. total + per-axis deltas) keeps its line breaks.\n\t\t\t\twhiteSpace: 'pre',\n\t\t\t\ttextAlign: 'center',\n\t\t\t\tuserSelect: 'none'\n\t\t\t} satisfies Partial<CSSStyleDeclaration>);\n\t\t}\n\t\t// Individual labels stay non-interactive by default (the overlay is too, but be explicit so a\n\t\t// caller that opts a label into pointer-events doesn't get surprised by inherited none).\n\t\tel.style.pointerEvents = 'none';\n\n\t\tconst object = new CSS2DObject(el);\n\t\tobject.position.copy(position);\n\t\tgroup.add(object);\n\t\tlabels.add(object);\n\n\t\treturn {\n\t\t\tobject,\n\t\t\tsetPosition: (p) => object.position.copy(p),\n\t\t\tsetText: (t) => {\n\t\t\t\tel.textContent = t;\n\t\t\t},\n\t\t\tremove: () => {\n\t\t\t\tobject.removeFromParent();\n\t\t\t\tel.remove();\n\t\t\t\tlabels.delete(object);\n\t\t\t}\n\t\t};\n\t};\n\n\treturn {\n\t\taddLabel,\n\t\trender: (scene, camera) => renderer.render(scene, camera),\n\t\tsetSize: (width, height) => renderer.setSize(width, height),\n\t\tdispose: () => {\n\t\t\tlabels.forEach((object) => {\n\t\t\t\tobject.removeFromParent();\n\t\t\t\t(object.element as HTMLElement).remove();\n\t\t\t});\n\t\t\tlabels.clear();\n\t\t\tgroup.removeFromParent();\n\t\t\tdom.remove();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { Line2 } from 'three/addons/lines/Line2.js';\nimport { LineGeometry } from 'three/addons/lines/LineGeometry.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport type { LabelLayer, LabelHandle } from './label-layer';\n\n/**\n * A two-click distance measurement tool — the CAD verb users expect. Click a point, click a second,\n * read the distance off a label on the connecting line; a third click starts a new measurement.\n *\n * Picking snaps to geometry so measurements are exact, not \"wherever the ray happened to land\":\n * on a mesh hit we snap to the nearest vertex of the struck triangle if it's within\n * {@link MeasureOptions.snapPixels} on screen, else use the raw hit point. This is a cheap local\n * snap (three candidate vertices), no spatial index — enough for clean vertex-to-vertex measurement\n * without the cost/complexity of full edge/midpoint snapping (a later refinement).\n *\n * The tool is dormant until {@link MeasureTool.setEnabled}(true). While enabled it intercepts clicks\n * (the caller forwards them and swallows the event when {@link MeasureTool.handleClick} returns\n * true) so measuring doesn't also select objects.\n */\n\nexport interface MeasureTool {\n\tsetEnabled(enabled: boolean): void;\n\tisEnabled(): boolean;\n\t/** Process a click. Returns true if the tool consumed it (caller should not also select). */\n\thandleClick(event: MouseEvent): boolean;\n\t/**\n\t * Process pointer movement to preview the next snap point — a ghost marker tracks the cursor and\n\t * jumps to the vertex a click would snap to, so users can aim before committing. No-op when the\n\t * tool is disabled. The caller forwards mousemove; nothing is consumed.\n\t */\n\thandleMove(event: MouseEvent): void;\n\t/** Clear the current measurement (markers, line, label). */\n\tclear(): void;\n\tdispose(): void;\n}\n\nexport interface MeasureOptions {\n\t/** Snap to a vertex when the cursor is within this many screen pixels of it. Default 12. */\n\tsnapPixels?: number;\n\t/** Marker + line color. Default yellow. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** CSS class applied to the distance label, for styling. */\n\tlabelClassName?: string;\n\t/**\n\t * The model's unit (pass `data.modelunits`). The scene is in meters, so the default formatter\n\t * converts and labels in this unit — e.g. a mm model reads \"25.0 mm\", not \"0.025 m\". Defaults\n\t * to meters. Ignored when a custom `format` is supplied.\n\t */\n\tdisplayUnit?: string;\n\t/**\n\t * Format the measurement → label text. Receives the straight-line `distance` and the per-axis\n\t * `delta` (|b − a| on each axis), both in **meters**. May return multi-line text or HTML; the\n\t * default renders the total plus a Δx/Δy/Δz breakdown in `displayUnit`. Overrides `displayUnit`.\n\t */\n\tformat?: (distance: number, delta: THREE.Vector3) => string;\n}\n\ninterface MeasureDeps {\n\tcanvas: HTMLCanvasElement;\n\tscene: THREE.Scene;\n\tgetActiveCamera: () => THREE.Camera;\n\t/**\n\t * The current orbit target (e.g. `controls.target`). Used to scale the line/point pick\n\t * threshold with the view: the tolerance is a fraction of the camera→target distance, so it\n\t * stays roughly constant on screen wherever the user has framed the model. Optional for\n\t * backward compatibility — without it the perspective fallback is the camera's distance to the\n\t * world origin, which misjudges the threshold for off-origin content. Thread it in when you can.\n\t */\n\tgetViewTarget?: () => THREE.Vector3;\n\tlabelLayer: LabelLayer;\n\toptions?: MeasureOptions;\n}\n\nconst DEFAULT_SNAP_PIXELS = 12;\nconst DEFAULT_COLOR = 0xffcc00;\n// Line/Points raycast threshold as a fraction of the view distance (camera→target). ~1.5% gives a\n// comfortable few-pixel grab band at typical framing without snapping to far-off geometry.\nconst LINE_PICK_FRACTION = 0.015;\n\n/**\n * Scene geometry is loaded in meters (the webdisplay parser scales to meters when\n * `allowScaling` is on), so distances come out in meters. To label in the model's\n * own unit, convert with `metersPerUnit` and append `suffix`. Keep this in sync\n * with the webdisplay parser's SCALE_FACTORS.\n */\nconst UNIT_DISPLAY: Record<string, { metersPerUnit: number; suffix: string }> = {\n\tMillimeters: { metersPerUnit: 1 / 1000, suffix: 'mm' },\n\tCentimeters: { metersPerUnit: 1 / 100, suffix: 'cm' },\n\tMeters: { metersPerUnit: 1, suffix: 'm' },\n\tInches: { metersPerUnit: 1 / 39.37, suffix: 'in' },\n\tFeet: { metersPerUnit: 1 / 3.28084, suffix: 'ft' }\n};\n\n/**\n * Build a `meters → label` formatter for the given display unit (defaults to meters).\n * @internal exported for tests\n */\nexport function makeFormatter(displayUnit?: string): (n: number) => string {\n\tconst unit = (displayUnit && UNIT_DISPLAY[displayUnit]) || UNIT_DISPLAY.Meters;\n\treturn (meters: number) => `${(meters / unit.metersPerUnit).toPrecision(3)} ${unit.suffix}`;\n}\n\n/**\n * World-space raycast threshold for picking lines/points (which have no surface area and are only\n * \"hit\" when the ray passes within this distance of them). A fixed fraction of the view size keeps\n * the grab band roughly constant on screen as the user zooms:\n * - perspective: fraction of the camera→target distance (the framed view size). Falls back to the\n * camera's distance to the world origin when no target is supplied — see `MeasureDeps.getViewTarget`.\n * - orthographic: fraction of the visible frustum height, `(top − bottom) / zoom`. Ortho zoom\n * changes `camera.zoom`, not the camera position, so distance-based scaling would never react.\n * @internal exported for tests\n */\nexport function pickThreshold(camera: THREE.Camera, viewTarget?: THREE.Vector3): number {\n\tif ((camera as THREE.OrthographicCamera).isOrthographicCamera) {\n\t\tconst ortho = camera as THREE.OrthographicCamera;\n\t\tconst visibleHeight = Math.abs(ortho.top - ortho.bottom) / (ortho.zoom || 1);\n\t\treturn visibleHeight * LINE_PICK_FRACTION;\n\t}\n\tconst viewScale = viewTarget ? camera.position.distanceTo(viewTarget) : camera.position.length();\n\treturn (viewScale || 1) * LINE_PICK_FRACTION;\n}\n\n/**\n * The vertex indices to consider snapping to for a given hit, by object type:\n * - Mesh: the three vertices of the struck triangle (`hit.face`).\n * - Line / LineSegments: the two endpoints of the struck segment (`hit.index`, `hit.index + 1`).\n * - Points: the struck vertex (`hit.index`).\n * Returns null when the hit carries no usable index info (e.g. a fat `Line2`), so the caller keeps\n * the raw hit point.\n */\nfunction snapCandidateIndices(hit: THREE.Intersection): number[] | null {\n\tconst obj = hit.object;\n\tif (obj instanceof THREE.Mesh) {\n\t\treturn hit.face ? [hit.face.a, hit.face.b, hit.face.c] : null;\n\t}\n\tif (obj instanceof THREE.Points) {\n\t\t// Points.raycast resolves indexed geometry itself: `hit.index` is always a position index.\n\t\treturn hit.index != null ? [hit.index] : null;\n\t}\n\t// THREE.Line / LineSegments / LineLoop. For non-indexed geometry `hit.index` is the first\n\t// vertex of the struck segment; for INDEXED geometry it is a cursor into the index buffer\n\t// (three r184 Line.raycast reports the loop counter, not the resolved vertex), so the segment's\n\t// endpoints must be looked up through the index before reading the position attribute.\n\tif (obj instanceof THREE.Line) {\n\t\tif (hit.index == null) return null;\n\t\tconst index = obj.geometry.index;\n\t\tif (index) {\n\t\t\tif (hit.index + 1 >= index.count) return null; // stale/inconsistent hit; keep raw point\n\t\t\treturn [index.getX(hit.index), index.getX(hit.index + 1)];\n\t\t}\n\t\treturn [hit.index, hit.index + 1];\n\t}\n\treturn null;\n}\n\n/**\n * Snap a raycast hit to the nearest geometry vertex within `snapPixels` on screen; otherwise return\n * the raw hit point. Works for meshes (triangle vertices), lines (segment endpoints), and points\n * (the vertex itself). Pure (no DOM) so it's unit-testable: it takes the screen size explicitly\n * rather than reading the canvas. Exported for that reason.\n *\n * Falls back to the raw point for hits without usable vertex indices or positions.\n */\nexport function snapToVertex(\n\thit: THREE.Intersection,\n\tcamera: THREE.Camera,\n\tscreenSize: { width: number; height: number },\n\tsnapPixels: number\n): THREE.Vector3 {\n\tconst raw = hit.point.clone();\n\tconst obj = hit.object as THREE.Object3D & { geometry?: THREE.BufferGeometry };\n\tconst indices = snapCandidateIndices(hit);\n\tif (!indices || !obj.geometry) return raw;\n\n\tconst pos = obj.geometry.attributes.position as THREE.BufferAttribute | undefined;\n\tif (!pos) return raw;\n\n\tconst toScreen = (worldP: THREE.Vector3): THREE.Vector2 => {\n\t\tconst ndc = worldP.clone().project(camera);\n\t\treturn new THREE.Vector2(\n\t\t\t((ndc.x + 1) / 2) * screenSize.width,\n\t\t\t((1 - ndc.y) / 2) * screenSize.height\n\t\t);\n\t};\n\tconst rawScreen = toScreen(raw);\n\n\tlet best = raw;\n\tlet bestPx = snapPixels;\n\tfor (const idx of indices) {\n\t\tif (idx >= pos.count) continue; // guard the line `index + 1` against the geometry end\n\t\tconst local = new THREE.Vector3().fromBufferAttribute(pos, idx);\n\t\tconst world = local.applyMatrix4(obj.matrixWorld);\n\t\tconst px = toScreen(world).distanceTo(rawScreen);\n\t\tif (px < bestPx) {\n\t\t\tbestPx = px;\n\t\t\tbest = world;\n\t\t}\n\t}\n\treturn best;\n}\n\nexport function createMeasureTool(deps: MeasureDeps): MeasureTool {\n\tconst { canvas, scene, getActiveCamera, getViewTarget, labelLayer, options = {} } = deps;\n\tconst snapPixels = options.snapPixels ?? DEFAULT_SNAP_PIXELS;\n\tconst color = new THREE.Color(options.color ?? DEFAULT_COLOR);\n\tconst fmt = makeFormatter(options.displayUnit);\n\tconst defaultFormat = (d: number, delta: THREE.Vector3) =>\n\t\t`${fmt(d)}\\nΔx ${fmt(delta.x)} Δy ${fmt(delta.y)} Δz ${fmt(delta.z)}`;\n\tconst format = options.format ?? defaultFormat;\n\n\tconst raycaster = new THREE.Raycaster();\n\tconst pointer = new THREE.Vector2();\n\n\tlet enabled = false;\n\tconst points: THREE.Vector3[] = [];\n\n\t// Visuals, created lazily and reused. Markers are small always-on-top points; the line connects\n\t// them; the label rides the line's midpoint.\n\tconst markers: THREE.Points[] = [];\n\tlet line: Line2 | null = null;\n\tlet label: LabelHandle | null = null;\n\n\tconst markerMaterial = new THREE.PointsMaterial({\n\t\tcolor,\n\t\tsize: 8,\n\t\tsizeAttenuation: false,\n\t\tdepthTest: false // markers stay visible through geometry, like CAD snap dots\n\t});\n\n\t// A hollow-feeling preview dot: dimmer + bigger than a committed marker so the snap target the\n\t// next click will lock onto is obvious before clicking. Shown only while hovering geometry.\n\tconst hoverMaterial = new THREE.PointsMaterial({\n\t\tcolor,\n\t\tsize: 11,\n\t\tsizeAttenuation: false,\n\t\tdepthTest: false,\n\t\ttransparent: true,\n\t\topacity: 0.5\n\t});\n\tlet hoverMarker: THREE.Points | null = null;\n\n\tconst showHover = (p: THREE.Vector3 | null) => {\n\t\tif (!p) {\n\t\t\tif (hoverMarker) hoverMarker.visible = false;\n\t\t\treturn;\n\t\t}\n\t\tif (!hoverMarker) {\n\t\t\tconst geometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0], 3));\n\t\t\thoverMarker = new THREE.Points(geometry, hoverMaterial);\n\t\t\thoverMarker.renderOrder = 1000;\n\t\t\thoverMarker.userData.id = 'measure';\n\t\t\thoverMarker.raycast = () => {};\n\t\t\tscene.add(hoverMarker);\n\t\t}\n\t\thoverMarker.position.copy(p);\n\t\thoverMarker.visible = true;\n\t};\n\n\tconst makeMarker = (p: THREE.Vector3): THREE.Points => {\n\t\tconst geometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([p.x, p.y, p.z], 3));\n\t\tconst marker = new THREE.Points(geometry, markerMaterial);\n\t\tmarker.renderOrder = 999;\n\t\tmarker.userData.id = 'measure'; // excluded from pick/fit\n\t\tmarker.raycast = () => {}; // don't let markers be measure targets themselves\n\t\tscene.add(marker);\n\t\treturn marker;\n\t};\n\n\tconst clear = () => {\n\t\tpoints.length = 0;\n\t\tmarkers.forEach((m) => {\n\t\t\tm.geometry.dispose();\n\t\t\tm.removeFromParent();\n\t\t});\n\t\tmarkers.length = 0;\n\t\tif (line) {\n\t\t\tline.geometry.dispose();\n\t\t\t(line.material as LineMaterial).dispose();\n\t\t\tline.removeFromParent();\n\t\t\tline = null;\n\t\t}\n\t\tlabel?.remove();\n\t\tlabel = null;\n\t};\n\n\tconst drawMeasurement = () => {\n\t\tif (points.length !== 2) return;\n\t\tconst [a, b] = points;\n\n\t\tconst geometry = new LineGeometry();\n\t\tgeometry.setPositions([a.x, a.y, a.z, b.x, b.y, b.z]);\n\t\tconst material = new LineMaterial({ color });\n\t\t(material as LineMaterial & { linewidth: number; depthTest: boolean }).linewidth = 2;\n\t\tmaterial.depthTest = false;\n\n\t\tline = new Line2(geometry, material);\n\t\tline.renderOrder = 998;\n\t\tline.userData.id = 'measure';\n\t\tline.raycast = () => {};\n\t\tscene.add(line);\n\n\t\tconst mid = a.clone().add(b).multiplyScalar(0.5);\n\t\tconst delta = new THREE.Vector3(Math.abs(b.x - a.x), Math.abs(b.y - a.y), Math.abs(b.z - a.z));\n\t\tlabel = labelLayer.addLabel(format(a.distanceTo(b), delta), mid, options.labelClassName);\n\t};\n\n\t/** Raycast the cursor and return the snapped pick point, or null if it hit no measurable geometry. */\n\tconst pickPoint = (event: MouseEvent): THREE.Vector3 | null => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tpointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tpointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tconst camera = getActiveCamera();\n\t\traycaster.setFromCamera(pointer, camera);\n\n\t\t// Lines and points have no surface area, so they're only \"hit\" when the ray passes within a\n\t\t// world-space threshold of them — left at the default ~1 unit they're nearly impossible to\n\t\t// click. Scale the threshold with the view (camera→target distance, or the ortho frustum\n\t\t// height under zoom) so the pick tolerance stays roughly constant on screen — see pickThreshold.\n\t\tconst threshold = pickThreshold(camera, getViewTarget?.());\n\t\traycaster.params.Line!.threshold = threshold;\n\t\traycaster.params.Points!.threshold = threshold;\n\n\t\tconst hits = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => i.object.userData.id !== 'measure' && i.object.userData.id !== 'grid');\n\n\t\tif (hits.length === 0) return null;\n\t\treturn snapToVertex(hits[0], camera, { width: rect.width, height: rect.height }, snapPixels);\n\t};\n\n\t// Coalesce hover raycasts to one per animation frame: mousemove can fire far more often than\n\t// the display refreshes, and a full-scene recursive raycast per event hitches on large models.\n\t// Only the latest event matters for the preview, so intermediate ones are simply dropped.\n\tlet pendingMove: MouseEvent | null = null;\n\tlet moveRaf = 0;\n\n\tconst cancelPendingMove = () => {\n\t\tif (moveRaf) {\n\t\t\tcancelAnimationFrame(moveRaf);\n\t\t\tmoveRaf = 0;\n\t\t}\n\t\tpendingMove = null;\n\t};\n\n\tconst handleMove = (event: MouseEvent): void => {\n\t\tif (!enabled) return;\n\t\tpendingMove = event;\n\t\tif (moveRaf) return;\n\t\tmoveRaf = requestAnimationFrame(() => {\n\t\t\tmoveRaf = 0;\n\t\t\tconst latest = pendingMove;\n\t\t\tpendingMove = null;\n\t\t\tif (!enabled || !latest) return;\n\t\t\tshowHover(pickPoint(latest));\n\t\t});\n\t};\n\n\tconst handleClick = (event: MouseEvent): boolean => {\n\t\tif (!enabled) return false;\n\n\t\t// A third click after a completed measurement starts fresh.\n\t\tif (points.length === 2) clear();\n\n\t\tconst point = pickPoint(event);\n\t\tif (point === null) return true; // consumed: a measuring click that missed still isn't a select\n\n\t\tpoints.push(point);\n\t\tmarkers.push(makeMarker(point));\n\n\t\tif (points.length === 2) drawMeasurement();\n\t\treturn true;\n\t};\n\n\treturn {\n\t\tsetEnabled: (value) => {\n\t\t\tenabled = value;\n\t\t\tif (!value) {\n\t\t\t\tcancelPendingMove();\n\t\t\t\tclear();\n\t\t\t\tshowHover(null);\n\t\t\t}\n\t\t},\n\t\tisEnabled: () => enabled,\n\t\thandleClick,\n\t\thandleMove,\n\t\tclear,\n\t\tdispose: () => {\n\t\t\tcancelPendingMove();\n\t\t\tclear();\n\t\t\tif (hoverMarker) {\n\t\t\t\thoverMarker.geometry.dispose();\n\t\t\t\thoverMarker.removeFromParent();\n\t\t\t\thoverMarker = null;\n\t\t\t}\n\t\t\tmarkerMaterial.dispose();\n\t\t\thoverMaterial.dispose();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\n\nimport { getLogger } from '@/core';\n\n/**\n * Maximum number of decoded textures retained by the module-level cache. When a fresh load pushes\n * the cache past this bound, the least-recently-used entry is evicted and its GPU texture disposed.\n * Sized generously above any realistic per-scene texture count (a solve's materials re-touch their\n * textures on every re-parse, keeping live entries recent), so eviction only ever trims textures\n * that no current scene references — e.g. a workflow regenerating a data-URI texture per solve.\n */\nexport const TEXTURE_CACHE_MAX_ENTRIES = 64;\n\n/**\n * Cache keys longer than this are replaced by a compact hash. Content-hashed asset URLs and normal\n * http(s) URLs stay comfortably below it; multi-KB/MB data URIs (whose full string would otherwise\n * be retained as the Map key for as long as the texture lives) exceed it and get hashed.\n */\nconst MAX_KEY_LENGTH = 256;\n\n/**\n * Module-level texture cache keyed by URL (or a hash of it — see {@link cacheKeyFor}).\n *\n * Material texture references are immutable by construction — the plugin serves bitmap/file\n * textures at content-hashed URLs (`/assets/{hash}`) and http(s)/data URIs identify their own\n * content — so each URL is fetched and GPU-decoded exactly once per session no matter how many\n * solves or materials reference it. Selva's hot loop re-parses batches on every slider nudge;\n * without this cache every solve would re-decode every texture.\n *\n * The Map doubles as the LRU order: hits re-insert their entry, so iteration order is\n * least-recently-used first and eviction pops the first key.\n */\nconst textureCache = new Map<string, THREE.Texture>();\nconst inFlight = new Map<string, Promise<THREE.Texture>>();\n\n/**\n * Bumped by {@link clearTextureCache}. A load that started before a clear compares its captured\n * generation on resolve: if the cache was cleared meanwhile, the freshly decoded texture is\n * disposed instead of repopulating the just-emptied cache (which would leak it past viewer\n * teardown and silently serve it to future materials despite the intended full reset).\n */\nlet cacheGeneration = 0;\n\n/**\n * Rejection used when a load resolves after {@link clearTextureCache} wiped the cache. Expected\n * during viewer teardown, so {@link applyTextureMap} swallows it silently instead of warning.\n */\nclass StaleTextureLoadError extends Error {\n\tconstructor(url: string) {\n\t\tsuper(`Texture load for ${url} resolved after clearTextureCache(); texture disposed.`);\n\t\tthis.name = 'StaleTextureLoadError';\n\t}\n}\n\n/**\n * Max anisotropic-filtering samples applied to color maps, keeping textures sharp at grazing angles\n * (floors, long walls receding to the horizon) instead of blurring. The ceiling is hardware-defined\n * (`renderer.capabilities.getMaxAnisotropy()`, typically 16); the viewer reports it once at init via\n * {@link setTextureAnisotropy}. Defaults to 1 (three's default — no anisotropy) so the module is\n * correct even if the viewer never calls in.\n */\nlet maxAnisotropy = 1;\n\n/**\n * Set the anisotropy applied to all color-map textures. Call once from the viewer with\n * `renderer.capabilities.getMaxAnisotropy()`. Retroactively updates already-cached textures so\n * textures decoded before this call still benefit.\n */\nexport function setTextureAnisotropy(value: number): void {\n\tmaxAnisotropy = Math.max(1, value);\n\tfor (const texture of textureCache.values()) {\n\t\tif (texture.anisotropy !== maxAnisotropy) {\n\t\t\ttexture.anisotropy = maxAnisotropy;\n\t\t\ttexture.needsUpdate = true;\n\t\t}\n\t}\n}\n\n/**\n * Assigns a texture to `material.map`, synchronously when cached, otherwise asynchronously once\n * the image is fetched and decoded (flagging `needsUpdate` — the mesh renders untextured for at\n * most the first frames). Load failures log a warning and leave the material untextured rather\n * than breaking the batch. A load that resolves after {@link clearTextureCache} is discarded\n * silently (its texture disposed) — the clear signals the viewer no longer wants it.\n */\nexport function applyTextureMap(material: THREE.MeshPhysicalMaterial, url: string): void {\n\tconst key = cacheKeyFor(url);\n\tconst cached = textureCache.get(key);\n\tif (cached) {\n\t\t// Refresh LRU recency: re-insert so this entry moves to the back of the eviction order.\n\t\ttextureCache.delete(key);\n\t\ttextureCache.set(key, cached);\n\t\tmaterial.map = cached;\n\t\tmaterial.needsUpdate = true;\n\t\treturn;\n\t}\n\n\t// No DOM (SSR / tests): textures can't decode without an image element; skip quietly.\n\tif (typeof document === 'undefined') {\n\t\treturn;\n\t}\n\n\tloadTexture(url, key)\n\t\t.then((texture) => {\n\t\t\tmaterial.map = texture;\n\t\t\tmaterial.needsUpdate = true;\n\t\t})\n\t\t.catch((error) => {\n\t\t\tif (error instanceof StaleTextureLoadError) {\n\t\t\t\treturn; // Cache cleared mid-load (teardown/reset) — untextured is the intended state.\n\t\t\t}\n\t\t\tgetLogger().warn(`Failed to load material texture ${url}:`, error);\n\t\t});\n}\n\n/**\n * Disposes all cached textures and empties the cache (e.g. on viewer teardown). Loads still in\n * flight are orphaned: when they resolve they see the bumped generation, dispose their texture,\n * and do not repopulate the cache.\n */\nexport function clearTextureCache(): void {\n\tcacheGeneration++;\n\tfor (const texture of textureCache.values()) {\n\t\ttexture.dispose();\n\t}\n\ttextureCache.clear();\n\tinFlight.clear();\n}\n\n/**\n * Maps a texture URL to its cache key. Short URLs key by themselves; oversized ones (data URIs)\n * key by a 32-bit FNV-1a hash plus length so the multi-KB/MB URI string isn't retained as a Map\n * key. The `data-uri:` prefix keeps hashed keys disjoint from literal URL keys.\n */\nfunction cacheKeyFor(url: string): string {\n\tif (url.length <= MAX_KEY_LENGTH) {\n\t\treturn url;\n\t}\n\treturn `data-uri:${fnv1aString(url).toString(16)}:${url.length}`;\n}\n\n/** 32-bit FNV-1a over the string's UTF-16 code units. */\nfunction fnv1aString(s: string): number {\n\tlet hash = 0x811c9dc5;\n\tfor (let i = 0; i < s.length; i++) {\n\t\thash ^= s.charCodeAt(i);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn hash >>> 0;\n}\n\n/** Inserts a texture, evicting (and disposing) least-recently-used entries past the bound. */\nfunction storeTexture(key: string, texture: THREE.Texture): void {\n\ttextureCache.set(key, texture);\n\twhile (textureCache.size > TEXTURE_CACHE_MAX_ENTRIES) {\n\t\tconst oldestKey = textureCache.keys().next().value as string;\n\t\tconst evicted = textureCache.get(oldestKey)!;\n\t\ttextureCache.delete(oldestKey);\n\t\tevicted.dispose();\n\t}\n}\n\nfunction loadTexture(url: string, key: string): Promise<THREE.Texture> {\n\tlet pending = inFlight.get(key);\n\tif (!pending) {\n\t\tconst generation = cacheGeneration;\n\t\tpending = new Promise<THREE.Texture>((resolve, reject) => {\n\t\t\tnew THREE.TextureLoader().load(\n\t\t\t\turl,\n\t\t\t\t(texture) => {\n\t\t\t\t\tif (generation !== cacheGeneration) {\n\t\t\t\t\t\t// clearTextureCache() ran while this load was in flight: the cache (and the\n\t\t\t\t\t\t// viewer that wanted this texture) is gone. Repopulating would leak a live GPU\n\t\t\t\t\t\t// texture past teardown, so dispose it and reject as stale.\n\t\t\t\t\t\ttexture.dispose();\n\t\t\t\t\t\treject(new StaleTextureLoadError(url));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Color maps are sRGB; without this the render is washed out.\n\t\t\t\t\ttexture.colorSpace = THREE.SRGBColorSpace;\n\t\t\t\t\t// Keep textures crisp at grazing angles (see maxAnisotropy).\n\t\t\t\t\ttexture.anisotropy = maxAnisotropy;\n\t\t\t\t\tstoreTexture(key, texture);\n\t\t\t\t\tinFlight.delete(key);\n\t\t\t\t\tresolve(texture);\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\t(error) => {\n\t\t\t\t\t// Guarded so a failure resolving after a clear can't delete a *newer* in-flight\n\t\t\t\t\t// entry for the same key (the clear already wiped this one).\n\t\t\t\t\tif (generation === cacheGeneration) {\n\t\t\t\t\t\tinFlight.delete(key);\n\t\t\t\t\t}\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t\tinFlight.set(key, pending);\n\t}\n\n\treturn pending;\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { HDRLoader } from 'three/addons/loaders/HDRLoader.js';\n\nimport { getLogger } from '@/core';\nimport type { ThreeInitializerOptions, Look, LookPreset } from '../types';\nimport type { MaterialAppearanceOptions } from '../webdisplay/types';\nimport { createCameraController, type CameraController } from './camera-controller';\nimport { createGrid, type Grid } from './grid';\nimport { createViewGizmo, type ViewGizmo } from './view-gizmo';\nimport { EDGES_SKIPPED_TRIANGLE_CAP, addEdgesAsync, removeEdges } from './edges';\nimport { createNearPlaneFitter, type NearPlaneFitter } from './near-plane';\nimport { createRenderPipeline, type RenderPipeline } from './render-pipeline';\nimport { createLabelLayer, type LabelLayer } from './label-layer';\nimport { createMeasureTool, type MeasureTool } from './measure';\nimport { computeContentBounds } from './three-helpers';\nimport { environmentRotationFor, isoOffset, sunOffset, upToAxis } from './up-axis';\nimport { setTextureAnisotropy } from '../webdisplay/texture-cache';\n\n/** Rhino's convention, and the frame all geometry arrives in — see `coordinate-transform.ts`. */\nconst defaultUp = new THREE.Vector3(0, 0, 1);\n\n/** The look applied when the caller passes no `look` option. */\nconst DEFAULT_LOOK: Look = 'technical';\n\n/**\n * The ready-to-go looks, as concrete lighting/material dial values. Single source of truth: consumed\n * by `applyDefaults` to seed construction-time defaults AND by `setLook` to re-apply a look at\n * runtime, so the two paths can never drift. A look carries ONLY lighting/material — never edges or\n * grid (those are independent overlays). See {@link Look} for what each reads like.\n *\n * Every look ships with `ambientOcclusion: false`: GTAO is a heavy full-screen postprocessing path\n * that can dominate frame time, so it stays opt-in (via `render.ambientOcclusion` or the runtime\n * `setAmbientOcclusion(true)`) rather than costing every viewer 60fps by default.\n */\nexport const LOOK_PRESETS: Record<Look, LookPreset> = {\n\t// Soft, even product shot: ACES with generous, balanced fill (hemisphere + a little flat ambient)\n\t// so the whole object stays legible and shadows read open — the safe, neutral default. IBL and fill\n\t// are kept modest so their contributions don't triple-stack (env + hemisphere + ambient) and push\n\t// midtones toward white — ACES then desaturates that lift, which reads as \"washed out\". Distinct\n\t// from `showcase`: this fills the shadows in; showcase deliberately lets them fall off for drama.\n\tstudio: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.75,\n\t\tambientIntensity: 0.4,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Clean shaded CAD look: neutral tone mapping, IBL-led so the object keeps FORM. The old dial\n\t// (ambient 1 + IBL 0.5) was the classic PBR wash — a full flat ambient adds the same value to\n\t// every face regardless of orientation, flattening shading toward a milky grey, while the one\n\t// light that actually shapes the surface (the HDR env) was cut to half. Rebalanced per the\n\t// community rule \"let the env map carry the fill, keep flat ambient low\": IBL back up to near\n\t// full, a little direction-aware hemisphere fill to lift under-facing surfaces (what ambient was\n\t// really being used for), and flat ambient dropped to a thin floor so nothing goes pure black.\n\t// Still a flat, even, edge-friendly read — just with shape and a hint of material response back.\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.9,\n\t\tenvironmentIntensity: 1,\n\t\themisphereIntensity: 0.35,\n\t\tambientIntensity: 0.25,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Dramatic hero shot: pushes exposure and reflective IBL for glossy pop, but deliberately pulls the\n\t// flat fill DOWN (low ambient, lean hemisphere) so light-to-shadow falloff stays strong and form\n\t// reads with contrast. Where `studio` fills the shadows in for even legibility, showcase lets them\n\t// fall off. Still trimmed below the old triple-stacked values so the punch doesn't tip into the\n\t// ACES wash — the drama comes from higher exposure + IBL against lower fill, not from stacking lift.\n\tshowcase: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1.15,\n\t\tenvMapIntensity: 1.4,\n\t\tenvironmentIntensity: 1.25,\n\t\themisphereIntensity: 0.35,\n\t\tambientIntensity: 0.15,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t}\n};\n\n/**\n * The material-parse options implied by a look — feed these into the batch parser's `material` option\n * so meshes are built to match it (backface culling, IBL strength). Kept out of the viewer's runtime\n * dials because they're baked at parse time, not toggleable in place.\n */\nexport function materialAppearanceForLook(look: Look): MaterialAppearanceOptions {\n\tconst preset = LOOK_PRESETS[look];\n\treturn {\n\t\tenvMapIntensity: preset.envMapIntensity,\n\t\tcullBackfaces: preset.cullBackfaces\n\t};\n}\n\n/**\n * Initializes a Three.js environment with scene, camera, renderer, and event handling.\n */\nexport const initThree = function (\n\tcanvas: HTMLCanvasElement,\n\toptions?: ThreeInitializerOptions\n): {\n\tscene: THREE.Scene;\n\tcamera: THREE.PerspectiveCamera;\n\tcontrols: OrbitControls;\n\trenderer: THREE.WebGLRenderer;\n\tcameraController: CameraController;\n\tgrid: Grid | null;\n\tgizmo: ViewGizmo | null;\n\t/** Two-click distance measurement tool. Null unless `measure.enabled`; `setEnabled(true)` to use. */\n\tmeasureTool: MeasureTool | null;\n\t/**\n\t * Attach edge overlays to the meshes under `root` (no-op unless `edges.enabled`). Call after\n\t * loading meshes via `updateScene`, since meshes arrive after init. Extraction for large meshes\n\t * runs off-thread — their overlays attach a beat later; meshes over `edges.maxTriangles` are\n\t * skipped and (by default) covered by the screen-space edge fallback instead.\n\t */\n\tapplyEdges: (root: THREE.Object3D) => void;\n\t/**\n\t * Remove edge overlays under `root` — the toggle-off counterpart of `applyEdges`. Prefer this\n\t * over calling `removeEdges` directly: it also cancels in-flight async attaches' fallout and\n\t * stands down the screen-space edge fallback if it was active.\n\t */\n\tclearEdges: (root: THREE.Object3D) => void;\n\t/**\n\t * Request a repaint from the on-demand render loop. Camera motion, resizes, pointer input, and\n\t * the built-in setters invalidate automatically; call this after mutating the scene externally\n\t * (e.g. `updateScene`, adding user geometry) so the change shows immediately rather than on the\n\t * next safety repaint. No-op (harmless) when `render.onDemand` is false.\n\t */\n\tinvalidate: () => void;\n\t/** Toggle ambient occlusion at runtime — builds or tears down the postprocessing pipeline. */\n\tsetAmbientOcclusion: (enabled: boolean) => void;\n\t/**\n\t * Apply a coherent look to the already-loaded scene: 'technical' (matte/CAD — edges, grid, low\n\t * IBL, neutral tone mapping) or 'rendered' (presentation — stronger IBL, ACES tone mapping, no\n\t * edges). Retunes viewer-owned dials only; per-material parse choices are set via the batch\n\t * parser's `material` option. Handy for comparing the two looks in a live viewer.\n\t */\n\t/**\n\t * Switch the viewer to a ready-to-go look at runtime ('studio' | 'technical' | 'showcase'). Retunes\n\t * lighting/material only (tone mapping, fill, IBL, AO) — never edges/grid. A straight preset apply:\n\t * overwrites any granular lighting dials you set earlier.\n\t */\n\tsetLook: (look: 'studio' | 'technical' | 'showcase') => void;\n\t/**\n\t * Retune the fill lights at runtime: the direction-aware hemisphere fill (sky/ground) and the flat\n\t * ambient. Raising `hemisphereIntensity` is the most effective way to lift shadowed / under-facing\n\t * surfaces a dark HDR leaves black. A positive `hemisphereIntensity` lazily creates the hemisphere\n\t * light if the viewer was built without one; `0` switches it off.\n\t */\n\tsetFillLights: (opts: {\n\t\themisphereIntensity?: number;\n\t\themisphereSkyColor?: THREE.Color | number;\n\t\themisphereGroundColor?: THREE.Color | number;\n\t\tambientIntensity?: number;\n\t}) => void;\n\t/**\n\t * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`) at\n\t * runtime — normalizes brightness across HDRs of differing exposure so the scene isn't at the\n\t * mercy of whichever HDR is loaded. Applies immediately, even before the HDR finishes decoding.\n\t */\n\tsetEnvironmentIntensity: (intensity: number) => void;\n\t/** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */\n\tsetToneMappingExposure: (exposure: number) => void;\n\t/** Set GTAO strength at runtime (0–1). No-op when ambient occlusion isn't active. */\n\tsetAoIntensity: (intensity: number) => void;\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) matching the active look — feed\n\t * into the batch parser's `material` option so freshly-loaded meshes are built to match it. See\n\t * `setLook`.\n\t */\n\tgetMaterialAppearance: () => MaterialAppearanceOptions;\n\t/**\n\t * Refit the sun's shadow frustum to the current scene content for crisp shadows. Call after\n\t * loading or replacing geometry (e.g. after `updateScene`). No-op when sunlight/shadows are off.\n\t */\n\tupdateShadowBounds: () => void;\n\t/**\n\t * Rescale the grid's cell spacing and fade radius to the current scene content, so parts of any\n\t * size get readable cells and a fade that reaches past the model. Call after loading or replacing\n\t * geometry (e.g. after `updateScene`). No-op when the grid is off or there's no content.\n\t */\n\tupdateGridScale: () => void;\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n\t/**\n\t * Add caller-owned geometry (lines, annotations, construction aids) to the scene. The object is\n\t * tagged `userData.source = 'user'` so it persists across `updateScene` solves instead of being\n\t * cleared with compute content. It is treated as normal content for fit-to-view framing.\n\t */\n\taddUserGeometry: (object: THREE.Object3D) => void;\n\t/** Remove a single user-added object and dispose its geometry/materials. */\n\tremoveUserGeometry: (object: THREE.Object3D) => void;\n\t/** Remove and dispose all user-added geometry (every object tagged `source === 'user'`). */\n\tclearUserGeometry: () => void;\n} {\n\tconst config = applyDefaults(options || {});\n\n\tconst sceneUp = config.environment?.sceneUp || defaultUp;\n\n\t// The configured pixel ratio is the single source of truth for every DPR consumer — renderer\n\t// setup, the per-frame resize check, and the AO pipeline. Resolving it once here means a\n\t// host-configured value (e.g. `pixelRatio: 1` for performance) is never silently overridden\n\t// after the first resize check. (applyDefaults always sets it; the fallback is type narrowing.)\n\tconst pixelRatio = config.render.pixelRatio ?? Math.min(window.devicePixelRatio, 2);\n\n\tconst scene = createScene(config);\n\tconst camera = createCamera(config, canvas);\n\t// Set the camera's up to the scene up BEFORE OrbitControls/the controller read it — OrbitControls\n\t// captures the orbit basis from camera.up at construction, and the controller derives its presets\n\t// and ortho camera from it. Without this, a Z-up scene would orbit and frame as if Y-up.\n\tcamera.up.copy(sceneUp);\n\tconst renderer = setupRenderer(canvas, config, pixelRatio);\n\t// Report the GPU's max anisotropy to the texture cache so color maps stay sharp at grazing angles.\n\t// One-time; retroactively upgrades any texture already decoded this session.\n\tsetTextureAnisotropy(renderer.capabilities.getMaxAnisotropy());\n\tconst controls = setupControls(camera, canvas, config);\n\n\t// Tracks whichever camera (perspective or orthographic) is live; the controller swaps it.\n\t// Render loop, resize, and raycasting all read through getActiveCamera so 2D/3D stays coherent.\n\tconst cameraController = createCameraController({\n\t\tscene,\n\t\tperspective: camera,\n\t\tcontrols,\n\t\tonActiveCameraChange: () => {},\n\t\tup: sceneUp\n\t});\n\tconst getActiveCamera = () => cameraController.getActiveCamera();\n\n\t// The HDR environment decodes asynchronously; if the viewer is disposed before it lands, the\n\t// load callback must drop (and dispose) the texture instead of attaching it to a swept scene.\n\tlet disposed = false;\n\tsetupEnvironment(scene, renderer, config, () => disposed);\n\t// Scene lights. The shadow-casting sun (null when sunlight or shadows are off) has its shadow\n\t// frustum fitted to the scene content below and again whenever the host calls updateShadowBounds\n\t// after a geometry change — keeping shadow-map texels packed onto the model for crisp shadows at\n\t// any scale. The ambient + optional hemisphere fill are retunable at runtime via the setters below.\n\tconst lights = setupLighting(scene, config);\n\tconst sunlight = lights.sun;\n\n\t/**\n\t * Refit the sun's shadow frustum to the current scene content. Call after loading or replacing\n\t * geometry (e.g. right after `updateScene`). No-op when there is no shadow-casting sun or no\n\t * content. Cheap: one bounds traversal, no per-frame cost.\n\t */\n\tconst updateShadowBounds = () => {\n\t\tif (sunlight) fitShadowToContent(sunlight, computeContentBounds(scene));\n\t};\n\n\tif (config.floor?.enabled) {\n\t\taddFloor(scene, config);\n\t}\n\t// Tagged by addFloor; grabbed here so the near-plane fitter can consult its live visibility.\n\tconst floorMesh = config.floor?.enabled\n\t\t? (scene.children.find((child) => child.userData.id === 'floor') ?? null)\n\t\t: null;\n\n\t// Optional CAD aids: an infinite fading grid and the corner nav-cube gizmo. Both opt-in.\n\tconst grid = config.grid.enabled\n\t\t? createGrid({\n\t\t\t\tcellSize: config.grid.cellSize,\n\t\t\t\tmajorEvery: config.grid.majorEvery,\n\t\t\t\tcellColor: config.grid.cellColor,\n\t\t\t\tmajorColor: config.grid.majorColor,\n\t\t\t\tfadeDistance: config.grid.fadeDistance,\n\t\t\t\tplane: config.grid.plane\n\t\t\t})\n\t\t: null;\n\tif (grid) scene.add(grid.object);\n\n\t/**\n\t * Rescale the grid's cell spacing and fade radius to the current scene content, so a part that is\n\t * a few units or a few thousand units wide both get sensibly-sized cells and a fade that reaches\n\t * past the model. Call after loading or replacing geometry (e.g. right after `updateScene`). No-op\n\t * when there's no grid or no content. Cheap: one bounds traversal, no per-frame cost.\n\t */\n\tconst updateGridScale = () => {\n\t\tif (grid) grid.fitToContent(computeContentBounds(scene));\n\t};\n\n\tconst gizmo = config.gizmo.enabled\n\t\t? createViewGizmo({ camera, domElement: canvas, controller: cameraController })\n\t\t: null;\n\n\t// Per-frame near-plane fitting: recovers depth precision when zoomed out (see near-plane.ts).\n\t// Ground-plane normals cap the fit where a ground aid (grid under the camera, floor) would\n\t// otherwise be clipped at grazing views.\n\t//\n\t// Resolved per frame, and only for aids actually VISIBLE: the grid is commonly built up-front so\n\t// hosts can toggle it, yet started hidden. Since this clamp is the camera's height above the\n\t// plane, letting a hidden grid contribute drives near→0 at grazing views and craters depth\n\t// precision (ULP ∝ 1/near) — which shows up as hidden edges punching through solid geometry.\n\t// applyDefaults always fills `plane` (from the scene up axis); the fallback derives from the same\n\t// source rather than assuming 'z', so the two can't disagree in a non-Z-up scene.\n\tconst gridPlane = config.grid.plane ?? upToAxis(sceneUp);\n\tconst gridNormal = new THREE.Vector3(\n\t\tgridPlane === 'x' ? 1 : 0,\n\t\tgridPlane === 'y' ? 1 : 0,\n\t\tgridPlane === 'z' ? 1 : 0\n\t);\n\tconst floorNormal = sceneUp.clone().normalize();\n\tconst groundNormals = (): THREE.Vector3[] => {\n\t\tconst normals: THREE.Vector3[] = [];\n\t\tif (grid?.object.visible) normals.push(gridNormal);\n\t\tif (config.floor.enabled && floorMesh?.visible) normals.push(floorNormal);\n\t\treturn normals;\n\t};\n\tconst nearFitter: NearPlaneFitter | null = config.camera.dynamicNear\n\t\t? createNearPlaneFitter({ camera, scene, groundNormals })\n\t\t: null;\n\n\t// HTML label overlay (CSS2D) and the measurement tool built on it. Both opt-in; the label layer\n\t// is only created when something needs it (currently the measure tool).\n\tconst labelContainer = canvas.parentElement ?? canvas;\n\tconst labelLayer: LabelLayer | null = config.measure.enabled\n\t\t? createLabelLayer(labelContainer, scene)\n\t\t: null;\n\tconst measureTool: MeasureTool | null =\n\t\tconfig.measure.enabled && labelLayer\n\t\t\t? createMeasureTool({\n\t\t\t\t\tcanvas,\n\t\t\t\t\tscene,\n\t\t\t\t\tgetActiveCamera,\n\t\t\t\t\tlabelLayer,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tsnapPixels: config.measure.snapPixels,\n\t\t\t\t\t\tcolor: config.measure.color,\n\t\t\t\t\t\tlabelClassName: config.measure.labelClassName,\n\t\t\t\t\t\tdisplayUnit: config.measure.displayUnit,\n\t\t\t\t\t\tformat: config.measure.format\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: null;\n\n\tconst eventHandlers =\n\t\tconfig.events.enableEventHandlers !== false\n\t\t\t? setupEventHandlers(canvas, scene, cameraController, config)\n\t\t\t: { dispose: () => {}, fitToView: () => {}, clearSelection: () => {} };\n\n\t// A drag to orbit/pan ends with a `click` on mouseup. Without guarding, that release click would\n\t// be taken as a measurement point (placing a stray point or clearing a finished measurement when\n\t// the user only meant to rotate). Record where the press started and treat the release as a click\n\t// only if the pointer barely moved — a real click, not a drag.\n\tconst DRAG_SLOP_PX = 5;\n\tlet pressX = 0;\n\tlet pressY = 0;\n\tconst handlePointerDown = (event: MouseEvent) => {\n\t\tpressX = event.clientX;\n\t\tpressY = event.clientY;\n\t};\n\tconst wasDrag = (event: MouseEvent) =>\n\t\tMath.hypot(event.clientX - pressX, event.clientY - pressY) > DRAG_SLOP_PX;\n\n\t// Capture-phase interceptors that pre-empt scene selection. Order: an active measurement claims\n\t// the click first, then the gizmo. stopImmediatePropagation keeps the selection handler from\n\t// also firing. (Both run in capture so they see the event before the bubble-phase selection.)\n\tconst handleToolClick = (event: MouseEvent) => {\n\t\tif (wasDrag(event)) return; // an orbit/pan release, not a measurement click — leave it alone\n\t\tif (measureTool?.handleClick(event)) {\n\t\t\tevent.stopImmediatePropagation();\n\t\t\treturn;\n\t\t}\n\t\tif (gizmo?.handleClick(event)) {\n\t\t\tevent.stopImmediatePropagation();\n\t\t}\n\t};\n\tif (gizmo || measureTool) {\n\t\tcanvas.addEventListener('mousedown', handlePointerDown, { capture: true });\n\t\tcanvas.addEventListener('click', handleToolClick, { capture: true });\n\t}\n\t// Forward movement to the measure tool so it can preview the snap point under the cursor. Passive:\n\t// it only reads, never consumes, so it never interferes with orbit/pan.\n\tconst handleToolMove = (event: MouseEvent) => measureTool?.handleMove(event);\n\tif (measureTool) {\n\t\tcanvas.addEventListener('mousemove', handleToolMove, { passive: true });\n\t}\n\n\t// Repaint request for the on-demand render loop (audit P4). Forward-declared so setters defined\n\t// before the loop exists can call it; rebound to the loop's real invalidate once it's created.\n\tlet requestRender: () => void = () => {};\n\n\t// Edge overlays: bind the configured options into a closure the consumer calls after loading\n\t// meshes. Always applies when called explicitly (the `edges.enabled` flag governs whether the\n\t// host *intends* edges, but an explicit call should never be silently ignored).\n\t// Async path: extraction for large meshes runs in a worker, so a heavy solve never stalls the\n\t// main thread — their overlays pop in a beat later; small meshes still attach synchronously.\n\t// Cancellation (scene cleared by the next solve, clearEdges toggles) is handled inside.\n\t// Once attached, meshes skipped for exceeding the triangle cap switch the screen-space edge\n\t// fallback on (and a later solve without such meshes switches it back off).\n\tconst applyEdges = (root: THREE.Object3D) => {\n\t\tvoid addEdgesAsync(root, {\n\t\t\tcolor: config.edges.color, // undefined → derive from each mesh's surface color\n\t\t\tdarken: config.edges.darken,\n\t\t\twidth: config.edges.width,\n\t\t\tthresholdAngle: config.edges.thresholdAngle,\n\t\t\tdistanceFade: config.edges.distanceFade,\n\t\t\tmaxTriangles: config.edges.maxTriangles,\n\t\t\tmaxSegments: config.edges.maxSegments\n\t\t}).then(() => {\n\t\t\tupdateEdgeFallback(root);\n\t\t\trequestRender(); // overlays may have attached after the solve's own repaint\n\t\t});\n\t};\n\n\t/** Turn the screen-space fallback on/off to match whether capped-out meshes are present. */\n\tconst updateEdgeFallback = (root: THREE.Object3D) => {\n\t\tif (config.edges.screenSpaceFallback === false) return;\n\t\tlet hasSkippedMeshes = false;\n\t\troot.traverse((object) => {\n\t\t\tif (object.userData?.edgesSkipped === EDGES_SKIPPED_TRIANGLE_CAP) hasSkippedMeshes = true;\n\t\t});\n\t\tif (hasSkippedMeshes !== edgeFallbackActive) {\n\t\t\tedgeFallbackActive = hasSkippedMeshes;\n\t\t\tsyncPipeline();\n\t\t}\n\t};\n\n\t// The inverse of applyEdges: removes overlays (cancelling in-flight attaches) and stands down\n\t// the screen-space fallback. Hosts toggling edges off should call this rather than bare\n\t// removeEdges, or the fallback pass would keep drawing lines for capped meshes.\n\tconst clearEdges = (root: THREE.Object3D) => {\n\t\tremoveEdges(root);\n\t\tif (edgeFallbackActive) {\n\t\t\tedgeFallbackActive = false;\n\t\t\tsyncPipeline();\n\t\t}\n\t\trequestRender();\n\t};\n\n\tconst parent = canvas.parentElement;\n\tconst getCanvasSize = () =>\n\t\tparent\n\t\t\t? { width: parent.clientWidth, height: parent.clientHeight }\n\t\t\t: { width: window.innerWidth, height: window.innerHeight };\n\n\t// Optional postprocessing pipeline (AO and/or the screen-space edge fallback). Held in a mutable\n\t// so it can be toggled at runtime; the loop reads it through getRenderPipeline each frame. When\n\t// null, the loop uses the plain renderer.render path. Retargeted to the active camera every frame.\n\tlet renderPipeline: RenderPipeline | null = null;\n\tlet aoEnabled = !!config.render.ambientOcclusion;\n\t// True while meshes over the edge triangle cap are in the scene and the config wants the\n\t// screen-space approximation for them (see EdgesConfig.screenSpaceFallback).\n\tlet edgeFallbackActive = false;\n\tlet builtWithAo = false;\n\n\tconst buildPipeline = (withAo: boolean): RenderPipeline => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tconst pipeline = createRenderPipeline(\n\t\t\trenderer,\n\t\t\tscene,\n\t\t\tgetActiveCamera(),\n\t\t\tMath.max(1, width),\n\t\t\tMath.max(1, height),\n\t\t\t{\n\t\t\t\ttoneMapping: config.render.toneMapping ?? THREE.NeutralToneMapping,\n\t\t\t\ttoneMappingExposure: config.render.toneMappingExposure ?? 1,\n\t\t\t\tambientOcclusion: withAo,\n\t\t\t\taoIntensity: config.render.aoIntensity,\n\t\t\t\taoPixelRatio: config.render.aoPixelRatio,\n\t\t\t\t// Constructed disabled (cheap until toggled); syncPipeline flips it via setEdgeDetection.\n\t\t\t\tedgeDetection: false\n\t\t\t}\n\t\t);\n\t\tpipeline.setSize(Math.max(1, width), Math.max(1, height), pixelRatio);\n\t\treturn pipeline;\n\t};\n\n\t/** Reconcile the pipeline with what's wanted: AO presence is baked at construction, edges toggle live. */\n\tconst syncPipeline = () => {\n\t\tconst wantPipeline = aoEnabled || edgeFallbackActive;\n\t\tif (!wantPipeline) {\n\t\t\trenderPipeline?.dispose();\n\t\t\trenderPipeline = null;\n\t\t\trequestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (!renderPipeline || builtWithAo !== aoEnabled) {\n\t\t\trenderPipeline?.dispose();\n\t\t\trenderPipeline = buildPipeline(aoEnabled);\n\t\t\tbuiltWithAo = aoEnabled;\n\t\t}\n\t\trenderPipeline.setEdgeDetection(edgeFallbackActive);\n\t\trequestRender();\n\t};\n\n\t/** Dispose and rebuild the pipeline (if one is wanted) so construction-time options re-apply. */\n\tconst rebuildPipeline = () => {\n\t\trenderPipeline?.dispose();\n\t\trenderPipeline = null;\n\t\tsyncPipeline();\n\t};\n\n\tconst setAmbientOcclusion = (enabled: boolean) => {\n\t\taoEnabled = enabled;\n\t\tsyncPipeline();\n\t};\n\n\tsyncPipeline();\n\n\t/**\n\t * Retune the fill lights at runtime — the direction-aware hemisphere fill and the flat ambient.\n\t * Raising the hemisphere intensity is the most effective way to lift shadowed/under-facing\n\t * surfaces that a dark HDR leaves black, without washing the whole scene flat the way ambient does.\n\t * Pass `hemisphereIntensity: 0` to switch the fill off; a positive value creates the light lazily\n\t * if the viewer was built without one.\n\t */\n\tconst setFillLights = (opts: {\n\t\themisphereIntensity?: number;\n\t\themisphereSkyColor?: THREE.Color | number;\n\t\themisphereGroundColor?: THREE.Color | number;\n\t\tambientIntensity?: number;\n\t}) => {\n\t\tif (opts.ambientIntensity !== undefined) {\n\t\t\tlights.ambient.intensity = opts.ambientIntensity;\n\t\t}\n\t\tif (\n\t\t\topts.hemisphereIntensity !== undefined &&\n\t\t\t!lights.hemisphere &&\n\t\t\topts.hemisphereIntensity > 0\n\t\t) {\n\t\t\t// Built without a hemisphere light — create one on first positive intensity so hosts can\n\t\t\t// enable the fill purely at runtime.\n\t\t\tlights.hemisphere = new THREE.HemisphereLight(\n\t\t\t\topts.hemisphereSkyColor ?? config.lighting.hemisphereSkyColor,\n\t\t\t\topts.hemisphereGroundColor ?? config.lighting.hemisphereGroundColor,\n\t\t\t\topts.hemisphereIntensity\n\t\t\t);\n\t\t\tlights.hemisphere.position.copy(config.environment.sceneUp ?? defaultUp);\n\t\t\tscene.add(lights.hemisphere);\n\t\t}\n\t\tif (lights.hemisphere) {\n\t\t\tif (opts.hemisphereIntensity !== undefined)\n\t\t\t\tlights.hemisphere.intensity = opts.hemisphereIntensity;\n\t\t\tif (opts.hemisphereSkyColor !== undefined)\n\t\t\t\tlights.hemisphere.color.set(opts.hemisphereSkyColor);\n\t\t\tif (opts.hemisphereGroundColor !== undefined)\n\t\t\t\tlights.hemisphere.groundColor.set(opts.hemisphereGroundColor);\n\t\t}\n\t\trequestRender();\n\t};\n\n\t/**\n\t * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`).\n\t * Normalizes brightness across HDRs of differing exposure — lift a dim HDR or tame a bright one —\n\t * so the scene isn't at the mercy of whichever HDR is loaded. Applies immediately, even before the\n\t * HDR has finished decoding.\n\t */\n\tconst setEnvironmentIntensity = (intensity: number) => {\n\t\tconfig.environment.environmentIntensity = intensity;\n\t\tscene.environmentIntensity = intensity;\n\t\trequestRender();\n\t};\n\n\t/** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */\n\tconst setToneMappingExposure = (exposure: number) => {\n\t\tconfig.render.toneMappingExposure = exposure;\n\t\trenderer.toneMappingExposure = exposure;\n\t\t// When the composer path is active, tone mapping is applied by its OutputPass — rebuild so it\n\t\t// adopts the new exposure.\n\t\tif (renderPipeline) rebuildPipeline();\n\t};\n\n\t/** Set GTAO strength at runtime (0 = off-looking, 1 = full). No-op when AO isn't active. */\n\tconst setAoIntensity = (intensity: number) => {\n\t\tconfig.render.aoIntensity = intensity;\n\t\tif (renderPipeline) rebuildPipeline();\n\t};\n\n\t/**\n\t * Apply a ready-to-go look to the *already-built* scene at runtime — a quick way to switch looks in\n\t * a live viewer. It retunes only LIGHTING/MATERIAL: tone mapping/exposure, hemisphere fill +\n\t * ambient, HDR environment intensity, AO on/off, and `envMapIntensity` on every compute material\n\t * currently in the scene. It deliberately does NOT touch edges or grid (those are independent\n\t * overlays — toggle them via `grid.setVisible()` / `applyEdges`). It does not rebuild geometry, so\n\t * parse-time material choices (backface culling, vertex-color decode) are unaffected — set those via\n\t * the batch parser's `material` option (see `getMaterialAppearance`).\n\t *\n\t * Note: this is a straight preset apply. Any dial you set earlier via a granular setter\n\t * (`setToneMappingExposure`, `setFillLights`, …) is overwritten to the new look's value.\n\t */\n\tconst setLook = (look: Look) => {\n\t\tconst preset = LOOK_PRESETS[look];\n\t\tactiveLook = look;\n\n\t\t// Tone mapping lives on the renderer (plain path) and is mirrored into the composer's OutputPass\n\t\t// when AO is active. Rebuild the pipeline so the composer picks up the new tone mapping.\n\t\trenderer.toneMapping = preset.toneMapping;\n\t\trenderer.toneMappingExposure = preset.toneMappingExposure;\n\t\tconfig.render.toneMapping = preset.toneMapping;\n\t\tconfig.render.toneMappingExposure = preset.toneMappingExposure;\n\n\t\t// Fill lighting + HDR normalization: studio/showcase add hemisphere fill and lift the environment\n\t\t// so shadowed surfaces read well regardless of the HDR; technical zeroes the fill back to a flat\n\t\t// CAD look. Applied through the same setters a host would call.\n\t\tsetFillLights({\n\t\t\themisphereIntensity: preset.hemisphereIntensity,\n\t\t\tambientIntensity: preset.ambientIntensity\n\t\t});\n\t\tsetEnvironmentIntensity(preset.environmentIntensity);\n\n\t\t// Rebuild (if a pipeline is active) so the composer's OutputPass adopts the new tone mapping,\n\t\t// honoring the look's AO choice.\n\t\taoEnabled = preset.ambientOcclusion;\n\t\tif (renderPipeline) rebuildPipeline();\n\t\telse syncPipeline();\n\n\t\t// Retune IBL reflection strength on every compute mesh material in the scene.\n\t\tscene.traverse((object) => {\n\t\t\tif (object.userData.source !== 'compute') return;\n\t\t\tconst mesh = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tconst materials = Array.isArray(mesh.material)\n\t\t\t\t? mesh.material\n\t\t\t\t: mesh.material\n\t\t\t\t\t? [mesh.material]\n\t\t\t\t\t: [];\n\t\t\tfor (const material of materials) {\n\t\t\t\tif ('envMapIntensity' in material) {\n\t\t\t\t\t(material as THREE.MeshStandardMaterial).envMapIntensity = preset.envMapIntensity;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\trequestRender();\n\t};\n\n\t// The look currently applied. Always a real look (the default is 'studio'), seeded from the same\n\t// resolved value as the construction defaults. Drives `getMaterialAppearance()`.\n\tlet activeLook: Look = config.look;\n\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) that match the active look —\n\t * pass into the batch parser's `material` option so newly-loaded meshes are built to match it.\n\t */\n\tconst getMaterialAppearance = (): MaterialAppearanceOptions =>\n\t\tmaterialAppearanceForLook(activeLook);\n\n\t// Resize checked every frame so buffer resize and render happen in the same frame,\n\t// preventing visible blank frames on resize\n\tconst {\n\t\tanimate,\n\t\tdispose: disposeAnimation,\n\t\tinvalidate\n\t} = createAnimationLoop(\n\t\trenderer,\n\t\tscene,\n\t\tcamera,\n\t\tgetActiveCamera,\n\t\tcameraController,\n\t\tcontrols,\n\t\tgetCanvasSize,\n\t\tpixelRatio,\n\t\tconfig.events.onFrame,\n\t\tgrid,\n\t\tgizmo,\n\t\t() => renderPipeline,\n\t\tlabelLayer,\n\t\tnearFitter,\n\t\tconfig.render.onDemand ?? true\n\t);\n\trequestRender = invalidate;\n\tanimate();\n\n\tscene.up.set(sceneUp.x, sceneUp.y, sceneUp.z);\n\n\t// Initial fit so any geometry already present at construction casts crisp shadows and the grid is\n\t// scaled to it. Hosts that add geometry later (via updateScene) should call updateShadowBounds and\n\t// updateGridScale again afterwards.\n\tupdateShadowBounds();\n\tupdateGridScale();\n\n\t// Dispose one object's renderable resources (geometry + materials + their textures), recursing\n\t// into children so Groups of lines/points clean up fully.\n\tconst disposeObjectTree = (root: THREE.Object3D) => {\n\t\troot.traverse((object) => {\n\t\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\t\t\trenderable.geometry?.dispose();\n\t\t\tif (Array.isArray(renderable.material)) {\n\t\t\t\trenderable.material.forEach(disposeMaterialWithTextures);\n\t\t\t} else if (renderable.material) {\n\t\t\t\tdisposeMaterialWithTextures(renderable.material);\n\t\t\t}\n\t\t});\n\t};\n\n\tconst addUserGeometry = (object: THREE.Object3D) => {\n\t\tobject.userData.source = 'user';\n\t\tscene.add(object);\n\t};\n\n\tconst removeUserGeometry = (object: THREE.Object3D) => {\n\t\tobject.removeFromParent();\n\t\tdisposeObjectTree(object);\n\t};\n\n\tconst clearUserGeometry = () => {\n\t\t// Snapshot first — removeFromParent mutates scene.children during iteration.\n\t\tconst userObjects = scene.children.filter((child) => child.userData.source === 'user');\n\t\tuserObjects.forEach((object) => {\n\t\t\tobject.removeFromParent();\n\t\t\tdisposeObjectTree(object);\n\t\t});\n\t};\n\n\tconst dispose = () => {\n\t\t// Idempotent: a second call would re-run forceContextLoss() on an already-lost\n\t\t// context, throwing \"INVALID_OPERATION: loseContext: context already lost\".\n\t\t// Double-dispose happens naturally (React StrictMode effect double-invoke, hosts\n\t\t// that unmount twice), so guard on the flag we already track.\n\t\tif (disposed) return;\n\t\tdisposed = true;\n\t\tdisposeAnimation();\n\t\teventHandlers.dispose();\n\t\tif (gizmo || measureTool) {\n\t\t\tcanvas.removeEventListener('mousedown', handlePointerDown, { capture: true });\n\t\t\tcanvas.removeEventListener('click', handleToolClick, { capture: true });\n\t\t}\n\t\tif (measureTool) {\n\t\t\tcanvas.removeEventListener('mousemove', handleToolMove);\n\t\t}\n\t\tmeasureTool?.dispose();\n\t\tlabelLayer?.dispose();\n\t\tgizmo?.dispose();\n\t\tgrid?.dispose();\n\t\trenderPipeline?.dispose();\n\t\t// Stop any in-flight camera tween — its rAF ticks would otherwise keep touching the disposed\n\t\t// controls for up to the tween duration after teardown.\n\t\tcameraController.dispose();\n\t\tcontrols.dispose();\n\t\trenderer.dispose();\n\t\t// Free the GL context itself, not just its objects — browsers cap live WebGL contexts\n\t\t// (~16) and won't otherwise reclaim this one until GC, which can lag across rapid\n\t\t// mount/unmount cycles (e.g. navigating between definitions) and hit that cap.\n\t\trenderer.forceContextLoss();\n\n\t\tscene.traverse((object) => {\n\t\t\t// Dispose any renderable (mesh, line, points), not just meshes.\n\t\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\t\trenderable.geometry?.dispose();\n\t\t\tif (Array.isArray(renderable.material)) {\n\t\t\t\trenderable.material.forEach(disposeMaterialWithTextures);\n\t\t\t} else if (renderable.material) {\n\t\t\t\tdisposeMaterialWithTextures(renderable.material);\n\t\t\t}\n\t\t});\n\n\t\t// Scene-level textures the traversal above can't reach.\n\t\tscene.environment?.dispose();\n\t\tif (scene.background instanceof THREE.Texture) {\n\t\t\tscene.background.dispose();\n\t\t}\n\t};\n\n\treturn {\n\t\tscene,\n\t\tcamera,\n\t\tcontrols,\n\t\trenderer,\n\t\tcameraController,\n\t\tgrid,\n\t\tgizmo,\n\t\tmeasureTool,\n\t\tapplyEdges,\n\t\tclearEdges,\n\t\tinvalidate,\n\t\tsetAmbientOcclusion,\n\t\tsetLook,\n\t\tsetFillLights,\n\t\tsetEnvironmentIntensity,\n\t\tsetToneMappingExposure,\n\t\tsetAoIntensity,\n\t\tgetMaterialAppearance,\n\t\tupdateShadowBounds,\n\t\tupdateGridScale,\n\t\tdispose,\n\t\tfitToView: eventHandlers.fitToView,\n\t\tclearSelection: eventHandlers.clearSelection,\n\t\taddUserGeometry,\n\t\tremoveUserGeometry,\n\t\tclearUserGeometry\n\t};\n};\n\n// Exported for unit testing the option-precedence logic (initThree itself needs a real WebGL canvas).\nexport function applyDefaults(options: ThreeInitializerOptions): Required<ThreeInitializerOptions> {\n\tconst scale = options.sceneScale || 'm';\n\n\t// All Rhino geometry is normalized to METERS (1 unit = 1 meter), sceneScale just changes the viewing perspective\n\tconst scaleDefaults = {\n\t\tmm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 10,\n\t\t\tlightHeight: 20,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1000\n\t\t},\n\t\tcm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 100\n\t\t},\n\t\tm: {\n\t\t\tcameraDistance: 10,\n\t\t\tnear: 0.01,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 50,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.001,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1\n\t\t},\n\t\tinches: {\n\t\t\tcameraDistance: 15,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 80,\n\t\t\tlightDistance: 20,\n\t\t\tlightHeight: 40,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 80,\n\t\t\tscaleFactor: 39.37\n\t\t},\n\t\tfeet: {\n\t\t\tcameraDistance: 8,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 40,\n\t\t\tlightDistance: 15,\n\t\t\tlightHeight: 30,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 60,\n\t\t\tscaleFactor: 3.28084\n\t\t}\n\t};\n\n\tconst defaults = scaleDefaults[scale];\n\n\t// The chosen look seeds the lighting/material defaults (tone mapping, AO, IBL, fill). It sits BELOW\n\t// explicit per-field options (those still win) and ABOVE the plain per-field defaults — so it only\n\t// fills what the caller left unspecified. Always a real preset: the default IS a look ('studio'),\n\t// so there's no \"no look\" state to represent. A look never touches edges/grid — those resolve from\n\t// their own configs below.\n\tconst look = options.look ?? DEFAULT_LOOK;\n\tconst preset = LOOK_PRESETS[look];\n\n\treturn {\n\t\tsceneScale: scale,\n\t\tlook,\n\t\tcamera: {\n\t\t\t// Default 3/4 iso: behind-left and ABOVE the model. Derived from the scene up axis rather\n\t\t\t// than a literal Z-up vector, so a Y-up scene gets an overhead iso instead of a\n\t\t\t// below-horizon view.\n\t\t\t// `cameraDistance` was historically a PER-COMPONENT magnitude on a (-d, -d, d) vector, so the\n\t\t\t// effective orbit radius is d*sqrt(3). Preserved exactly so this change reorients the default\n\t\t\t// view without also changing how zoomed-in every scene starts.\n\t\t\tposition:\n\t\t\t\toptions.camera?.position ||\n\t\t\t\tisoOffset(\n\t\t\t\t\toptions.environment?.sceneUp ?? defaultUp,\n\t\t\t\t\tdefaults.cameraDistance * Math.sqrt(3)\n\t\t\t\t),\n\t\t\tfov: options.camera?.fov || 20,\n\t\t\tnear: options.camera?.near || defaults.near,\n\t\t\tfar: options.camera?.far || defaults.far,\n\t\t\ttarget: options.camera?.target || new THREE.Vector3(0, 0, 0),\n\t\t\tdynamicNear: options.camera?.dynamicNear ?? true\n\t\t},\n\t\tlighting: {\n\t\t\tenableSunlight: options.lighting?.enableSunlight ?? true,\n\t\t\tsunlightIntensity: options.lighting?.sunlightIntensity ?? 1,\n\t\t\t// Sun overhead and offset to one side, expressed in the scene basis so it stays overhead in\n\t\t\t// any up convention (a hardcoded +Z height made the sun near-horizontal in a Y-up scene).\n\t\t\tsunlightPosition:\n\t\t\t\toptions.lighting?.sunlightPosition ||\n\t\t\t\tsunOffset(\n\t\t\t\t\toptions.environment?.sceneUp ?? defaultUp,\n\t\t\t\t\tdefaults.lightDistance,\n\t\t\t\t\tdefaults.lightHeight\n\t\t\t\t),\n\t\t\tambientLightColor: options.lighting?.ambientLightColor || new THREE.Color(0x404040),\n\t\t\t// The look sets ambient low across the board — the hemisphere fill + env carry the lift, so\n\t\t\t// flat ambient is only a thin floor keeping shadows off pure black. Explicit option still wins.\n\t\t\tambientLightIntensity: options.lighting?.ambientLightIntensity ?? preset.ambientIntensity,\n\t\t\tsunlightColor: options.lighting?.sunlightColor || 0xffffff, // Default to white sunlight\n\t\t\t// Direction-aware fill. The look decides whether it's on (a positive hemisphereIntensity is\n\t\t\t// what actually creates the light in setupLighting); an explicit option overrides.\n\t\t\tenableHemisphereLight:\n\t\t\t\toptions.lighting?.enableHemisphereLight ?? preset.hemisphereIntensity > 0,\n\t\t\themisphereSkyColor: options.lighting?.hemisphereSkyColor ?? 0xdfe6ff,\n\t\t\t// A slightly warm ground tint reads as bounced light and keeps fill from desaturating colour.\n\t\t\themisphereGroundColor: options.lighting?.hemisphereGroundColor ?? 0x6b5f52,\n\t\t\themisphereIntensity: options.lighting?.hemisphereIntensity ?? preset.hemisphereIntensity\n\t\t},\n\t\tenvironment: {\n\t\t\thdrPath: options.environment?.hdrPath || '/baseHDR.hdr',\n\t\t\tbackgroundColor: options.environment?.backgroundColor || new THREE.Color(0xf0f0f0),\n\t\t\tenableEnvironmentLighting: options.environment?.enableEnvironmentLighting ?? true,\n\t\t\tsceneUp: options.environment?.sceneUp || defaultUp,\n\t\t\tshowEnvironment: options.environment?.showEnvironment ?? false,\n\t\t\tenvironmentIntensity: options.environment?.environmentIntensity ?? preset.environmentIntensity\n\t\t},\n\t\tfloor: {\n\t\t\tenabled: options.floor?.enabled ?? false,\n\t\t\tsize: options.floor?.size || defaults.floorSize,\n\t\t\tcolor: options.floor?.color || new THREE.Color(0x808080),\n\t\t\troughness: options.floor?.roughness ?? 0.7,\n\t\t\tmetalness: options.floor?.metalness ?? 0.0,\n\t\t\treceiveShadow: options.floor?.receiveShadow ?? true\n\t\t},\n\t\trender: {\n\t\t\tenableShadows: options.render?.enableShadows ?? true,\n\t\t\tshadowMapSize: options.render?.shadowMapSize || 2048,\n\t\t\tantialias: options.render?.antialias ?? true,\n\t\t\tpixelRatio: options.render?.pixelRatio || Math.min(window.devicePixelRatio, 2),\n\t\t\t// ?? not || so an explicit NoToneMapping (=== 0) is honoured rather than falling through.\n\t\t\ttoneMapping: options.render?.toneMapping ?? preset.toneMapping,\n\t\t\ttoneMappingExposure: options.render?.toneMappingExposure ?? preset.toneMappingExposure,\n\t\t\tpreserveDrawingBuffer: options.render?.preserveDrawingBuffer ?? false,\n\t\t\tambientOcclusion: options.render?.ambientOcclusion ?? preset.ambientOcclusion,\n\t\t\taoIntensity: options.render?.aoIntensity ?? 1,\n\t\t\t// Cap AO buffers at 1× by default — the biggest lever on GTAO cost on high-DPI displays.\n\t\t\taoPixelRatio: options.render?.aoPixelRatio ?? 1,\n\t\t\t// On-demand rendering (audit P4): draw only when something changed. Opt-out flag.\n\t\t\tonDemand: options.render?.onDemand ?? true\n\t\t},\n\t\tcontrols: {\n\t\t\tenableDamping: options.controls?.enableDamping ?? false,\n\t\t\tdampingFactor: options.controls?.dampingFactor || 0.05,\n\t\t\tautoRotate: options.controls?.autoRotate ?? false,\n\t\t\tautoRotateSpeed: options.controls?.autoRotateSpeed || 0.5,\n\t\t\tenableZoom: options.controls?.enableZoom ?? true,\n\t\t\tenablePan: options.controls?.enablePan ?? true,\n\t\t\tminDistance: options.controls?.minDistance || defaults.minDistance,\n\t\t\tmaxDistance: options.controls?.maxDistance || Infinity\n\t\t},\n\t\tgrid: {\n\t\t\t// Defaults mirror createGrid's so the two never drift. Grid is an independent overlay — a\n\t\t\t// look never toggles it.\n\t\t\tenabled: options.grid?.enabled ?? false,\n\t\t\tcellSize: options.grid?.cellSize ?? 1,\n\t\t\tmajorEvery: options.grid?.majorEvery ?? 10,\n\t\t\tcellColor: options.grid?.cellColor ?? 0x888888,\n\t\t\tmajorColor: options.grid?.majorColor ?? 0x444444,\n\t\t\tfadeDistance: options.grid?.fadeDistance ?? 100,\n\t\t\t// The \"ground\" plane is the one orthogonal to the scene up axis, so the grid lies under the\n\t\t\t// model regardless of up convention (Z-up Rhino → 'z'; Y-up → 'y'). Explicit `plane` wins.\n\t\t\tplane: options.grid?.plane ?? upToAxis(options.environment?.sceneUp ?? defaultUp)\n\t\t},\n\t\tgizmo: {\n\t\t\tenabled: options.gizmo?.enabled ?? false\n\t\t},\n\t\tedges: {\n\t\t\t// Defaults mirror addEdges' so the two never drift. Edges are an independent overlay — a\n\t\t\t// look never toggles them.\n\t\t\tenabled: options.edges?.enabled ?? false,\n\t\t\t// No color default: leaving it undefined lets addEdges derive each mesh's edge color from\n\t\t\t// its own surface material (darkened). Set a color explicitly to force one uniform tint.\n\t\t\tcolor: options.edges?.color,\n\t\t\tdarken: options.edges?.darken,\n\t\t\twidth: options.edges?.width ?? 1.5,\n\t\t\tthresholdAngle: options.edges?.thresholdAngle ?? 44,\n\t\t\tdistanceFade: options.edges?.distanceFade ?? true\n\t\t},\n\t\tmeasure: {\n\t\t\t// Visual defaults live in createMeasureTool; only `enabled` needs a value here, the rest\n\t\t\t// pass through (undefined → the tool's own default).\n\t\t\tenabled: options.measure?.enabled ?? false,\n\t\t\tsnapPixels: options.measure?.snapPixels,\n\t\t\tcolor: options.measure?.color,\n\t\t\tlabelClassName: options.measure?.labelClassName,\n\t\t\tdisplayUnit: options.measure?.displayUnit,\n\t\t\tformat: options.measure?.format\n\t\t},\n\t\tevents: {\n\t\t\tonBackgroundClicked: options.events?.onBackgroundClicked,\n\t\t\tonObjectSelected: options.events?.onObjectSelected,\n\t\t\tonMeshMetadataClicked: options.events?.onMeshMetadataClicked,\n\t\t\tonMeshDoubleClicked: options.events?.onMeshDoubleClicked,\n\t\t\tselectionColor: options.events?.selectionColor || '#ff0000', // Default to red\n\t\t\tenableEventHandlers: options.events?.enableEventHandlers ?? true,\n\t\t\tenableKeyboardControls: options.events?.enableKeyboardControls ?? true,\n\t\t\tenableClickToFocus: options.events?.enableClickToFocus ?? true,\n\t\t\tenableDoubleClickZoom: options.events?.enableDoubleClickZoom ?? true,\n\t\t\tonReady: options.events?.onReady,\n\t\t\tonFrame: options.events?.onFrame\n\t\t}\n\t};\n}\n\n/**\n * Dispose a material together with any textures it references (`map`, `roughnessMap`, …), matching\n * `clearScene`'s texture sweep (three-helpers) so no teardown path leaks GPU textures across viewer\n * mount/unmount cycles. Walks own enumerable properties only — `for...in` would needlessly iterate\n * the prototype chain.\n */\nexport function disposeMaterialWithTextures(material: THREE.Material): void {\n\tfor (const value of Object.values(material)) {\n\t\tif (value instanceof THREE.Texture) {\n\t\t\tvalue.dispose();\n\t\t}\n\t}\n\tmaterial.dispose();\n}\n\n/**\n * Fit a directional light's shadow camera to the scene content. The orthographic shadow frustum is\n * sized to the content's bounding sphere (padded), so the fixed shadow-map texels cover only the\n * model rather than a generous constant area — the dominant lever on shadow crispness. Near/far are\n * derived from how far the light sits from the content centre, keeping depth precision tight.\n *\n * No-op when there is no content (an empty box would collapse the frustum to a point).\n */\nfunction fitShadowToContent(light: THREE.DirectionalLight, bounds: THREE.Box3): void {\n\tif (bounds.isEmpty()) return;\n\n\tconst center = bounds.getCenter(new THREE.Vector3());\n\t// Bounding-sphere radius makes the frustum rotation-invariant: the light can shine from any\n\t// angle and the model still fits, with no per-angle recompute. Pad so grazing-angle casters and\n\t// soft-shadow (VSM) blur near the edges don't clip.\n\tconst radius = bounds.getSize(new THREE.Vector3()).length() * 0.5 * 1.2;\n\n\tconst cam = light.shadow.camera;\n\tcam.left = -radius;\n\tcam.right = radius;\n\tcam.top = radius;\n\tcam.bottom = -radius;\n\n\t// Aim the shadow camera at the content centre. The light keeps its configured *position*; only\n\t// its target moves, so the lighting direction is preserved while the shadow frustum recentres.\n\tlight.target.position.copy(center);\n\tlight.target.updateMatrixWorld();\n\n\t// Near/far bracket the content along the light→centre axis. Clamp near to a small positive value\n\t// so a light sitting inside the bounds can't push near ≤ 0.\n\tconst lightDistance = light.position.distanceTo(center);\n\tcam.near = Math.max(radius * 0.01, lightDistance - radius);\n\tcam.far = lightDistance + radius;\n\tcam.updateProjectionMatrix();\n}\n\nfunction createScene(config: Required<ThreeInitializerOptions>): THREE.Scene {\n\tconst scene = new THREE.Scene();\n\n\tconst bgColor =\n\t\ttypeof config.environment.backgroundColor === 'string'\n\t\t\t? new THREE.Color(config.environment.backgroundColor)\n\t\t\t: config.environment.backgroundColor;\n\tscene.background = bgColor || null;\n\n\treturn scene;\n}\n\n// Resize applied before render so buffer clear and draw happen in the same frame,\n// preventing visible blank frames when the canvas is resized\nfunction createAnimationLoop(\n\trenderer: THREE.WebGLRenderer,\n\tscene: THREE.Scene,\n\tcamera: THREE.PerspectiveCamera,\n\tgetActiveCamera: () => THREE.Camera,\n\tcameraController: CameraController,\n\tcontrols: OrbitControls,\n\tgetCanvasSize: () => { width: number; height: number },\n\t// The resolved config.render.pixelRatio — the single source of truth for DPR (see initThree).\n\tpixelRatio: number,\n\tonFrame?: (delta: number) => void,\n\tgrid?: Grid | null,\n\tgizmo?: ViewGizmo | null,\n\tgetRenderPipeline?: () => RenderPipeline | null,\n\tlabelLayer?: LabelLayer | null,\n\tnearFitter?: NearPlaneFitter | null,\n\t// On-demand rendering (audit P4): render only when something changed. False = legacy every-frame.\n\tonDemand: boolean = true\n): { animate: () => void; dispose: () => void; invalidate: () => void } {\n\tlet animationId: number | null = null;\n\tlet lastTime = performance.now();\n\n\t// The loop always *ticks* (updates are cheap); it only *renders* when: invalidate() was called\n\t// (scene content, style toggles, async edge attach), the active camera moved — a matrix compare\n\t// catches every driver: damping, presets, gizmo snaps, near-plane refits — or the safety repaint\n\t// interval elapsed, which bounds the staleness of any mutation that forgot to invalidate.\n\tlet renderRequested = true; // first frame always renders\n\tlet lastRenderTime = 0;\n\tconst IDLE_REPAINT_INTERVAL_MS = 500;\n\tconst lastWorldMatrix = new THREE.Matrix4();\n\tconst lastProjectionMatrix = new THREE.Matrix4();\n\tlet lastCamera: THREE.Camera | null = null;\n\tconst invalidate = () => {\n\t\trenderRequested = true;\n\t};\n\n\tconst cameraMoved = (activeCamera: THREE.Camera): boolean => {\n\t\t// matrixWorld is normally refreshed by renderer.render — which we're deciding whether to\n\t\t// call — so refresh it here first (cheap: a camera has no deep subtree).\n\t\tactiveCamera.updateMatrixWorld();\n\t\tconst moved =\n\t\t\tlastCamera !== activeCamera ||\n\t\t\t!lastWorldMatrix.equals(activeCamera.matrixWorld) ||\n\t\t\t!lastProjectionMatrix.equals(activeCamera.projectionMatrix);\n\t\tif (moved) {\n\t\t\tlastCamera = activeCamera;\n\t\t\tlastWorldMatrix.copy(activeCamera.matrixWorld);\n\t\t\tlastProjectionMatrix.copy(activeCamera.projectionMatrix);\n\t\t}\n\t\treturn moved;\n\t};\n\n\t// Pointer/wheel activity is a catch-all for click-driven scene mutations (measure points,\n\t// selection highlights) whose code paths predate on-demand rendering.\n\tconst canvas = renderer.domElement;\n\tconst pointerEvents = ['pointerdown', 'pointerup', 'wheel'] as const;\n\tif (onDemand) {\n\t\tfor (const type of pointerEvents) {\n\t\t\tcanvas.addEventListener(type, invalidate, { passive: true });\n\t\t}\n\t}\n\n\tconst checkResize = () => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tif (width === 0 || height === 0) return;\n\n\t\t// Must floor, not round: renderer.setSize floors the buffer size, and a mismatched rounding\n\t\t// here makes the comparison never settle — the resize branch would then run every frame.\n\t\tconst newW = Math.floor(width * pixelRatio);\n\t\tconst newH = Math.floor(height * pixelRatio);\n\n\t\tif (renderer.domElement.width !== newW || renderer.domElement.height !== newH) {\n\t\t\trenderer.setPixelRatio(pixelRatio);\n\t\t\trenderer.setSize(width, height, false);\n\t\t\tcamera.aspect = width / height;\n\t\t\tcamera.updateProjectionMatrix();\n\t\t\t// Reshape the orthographic frustum too, if it's the active projection.\n\t\t\tcameraController.updateAspect(width, height);\n\t\t\t// Keep the AO composer's render targets in step with the canvas.\n\t\t\tgetRenderPipeline?.()?.setSize(width, height, pixelRatio);\n\t\t\t// CSS2D overlay matches the canvas's CSS size (not the pixel-ratio buffer size).\n\t\t\tlabelLayer?.setSize(width, height);\n\t\t\tinvalidate();\n\t\t}\n\t};\n\n\tconst animate = function () {\n\t\tanimationId = requestAnimationFrame(animate);\n\n\t\tconst now = performance.now();\n\t\tconst delta = (now - lastTime) / 1000;\n\t\tlastTime = now;\n\n\t\tcheckResize();\n\n\t\tif (controls.enableDamping || controls.autoRotate) {\n\t\t\tcontrols.update();\n\t\t}\n\n\t\t// Keep the grid centered on the camera so it reads as infinite.\n\t\tif (grid) grid.update(getActiveCamera().position);\n\n\t\t// Advance the gizmo's fade/spin animation (no-op when idle).\n\t\tif (gizmo) gizmo.update(delta);\n\n\t\t// Refit the perspective near plane to the camera↔content gap (after controls moved the\n\t\t// camera, before anything renders) so depth precision tracks the viewing distance.\n\t\tif (nearFitter) nearFitter.update();\n\n\t\tonFrame?.(delta);\n\n\t\tconst activeCamera = getActiveCamera();\n\n\t\t// On-demand gate: skip the draw (the expensive part, especially with the AO composer) when\n\t\t// nothing changed. Ticking continues regardless, so damping/tweens re-trigger via the camera\n\t\t// compare on their next movement.\n\t\tif (onDemand) {\n\t\t\tconst shouldRender =\n\t\t\t\trenderRequested ||\n\t\t\t\tcameraMoved(activeCamera) ||\n\t\t\t\tnow - lastRenderTime >= IDLE_REPAINT_INTERVAL_MS;\n\t\t\tif (!shouldRender) return;\n\t\t\trenderRequested = false;\n\t\t\tlastRenderTime = now;\n\t\t}\n\n\t\tconst renderPipeline = getRenderPipeline?.();\n\t\tif (renderPipeline) {\n\t\t\t// AO path: composer owns the render. Retarget to the active camera in case 2D/3D swapped.\n\t\t\trenderPipeline.setCamera(activeCamera);\n\t\t\trenderPipeline.render(delta);\n\t\t} else {\n\t\t\trenderer.render(scene, activeCamera);\n\t\t}\n\n\t\t// HTML labels follow their 3D anchors — render the DOM overlay against the active camera.\n\t\tif (labelLayer) labelLayer.render(scene, activeCamera);\n\n\t\t// The gizmo draws as an overlay in a corner viewport with its own clear; render it last so it\n\t\t// sits on top of the scene.\n\t\tif (gizmo) gizmo.render(renderer);\n\t};\n\n\tconst dispose = () => {\n\t\tif (animationId !== null) {\n\t\t\tcancelAnimationFrame(animationId);\n\t\t\tanimationId = null;\n\t\t}\n\t\tif (onDemand) {\n\t\t\tfor (const type of pointerEvents) {\n\t\t\t\tcanvas.removeEventListener(type, invalidate);\n\t\t\t}\n\t\t}\n\t};\n\n\treturn { animate, dispose, invalidate };\n}\n\nfunction setupEnvironment(\n\tscene: THREE.Scene,\n\trenderer: THREE.WebGLRenderer,\n\tconfig: Required<ThreeInitializerOptions>,\n\tisDisposed: () => boolean\n) {\n\tif (config.environment.enableEnvironmentLighting) {\n\t\tnew HDRLoader().load(\n\t\t\tconfig.environment.hdrPath || '/baseHDR.hdr',\n\t\t\tfunction (envMap) {\n\t\t\t\t// The viewer can be torn down while the HDR is still fetching/decoding (fast\n\t\t\t\t// mount/unmount). dispose() has already swept the scene, so adopting the texture now\n\t\t\t\t// would leak it — and onReady must not fire on a dead viewer.\n\t\t\t\tif (isDisposed()) {\n\t\t\t\t\tenvMap.dispose();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!envMap?.image) {\n\t\t\t\t\tgetLogger().warn('HDR loaded without image data; skipping environment map.');\n\t\t\t\t\t// The texture object still holds GPU/CPU resources even without usable image data —\n\t\t\t\t\t// dispose it, since it will never be attached to the scene.\n\t\t\t\t\tenvMap?.dispose();\n\t\t\t\t\tconfig.events.onReady?.();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tenvMap.mapping = THREE.EquirectangularReflectionMapping;\n\n\t\t\t\t// Prefilter the raw equirect HDR through PMREM: this builds the roughness-aware mip\n\t\t\t\t// chain a MeshStandardMaterial samples for image-based lighting. Without it, three\n\t\t\t\t// falls back to sampling the equirect map directly and a rough surface reads a near-\n\t\t\t\t// mirror level — reflections stay unnaturally sharp/busy and specular highlights\n\t\t\t\t// sparkle, which is a big part of the \"not quite right\" look. The prefiltered cube is\n\t\t\t\t// what drives IBL; the raw equirect is kept only if it's also shown as the background.\n\t\t\t\tconst pmrem = new THREE.PMREMGenerator(renderer);\n\t\t\t\tpmrem.compileEquirectangularShader();\n\t\t\t\tconst prefiltered = pmrem.fromEquirectangular(envMap).texture;\n\t\t\t\tpmrem.dispose();\n\n\t\t\t\tscene.environment = prefiltered;\n\t\t\t\t// Normalize the HDR's IBL contribution so brightness is consistent across HDRs of\n\t\t\t\t// differing exposure, instead of dim-HDR-looks-dim / bright-HDR-blows-out.\n\t\t\t\tscene.environmentIntensity = config.environment.environmentIntensity ?? 1;\n\t\t\t\t// Equirectangular mapping assumes the HDR's horizon lies in the XZ plane — i.e. Y-up.\n\t\t\t\t// This scene is Z-up, so without a rotation the environment sits on its side: the\n\t\t\t\t// horizon runs vertically and the sky lights the model from +Y instead of from above.\n\t\t\t\t// Invisible on a neutral studio HDR, obvious on any HDR with a sky/ground split.\n\t\t\t\tconst envRotation = environmentRotationFor(config.environment.sceneUp ?? defaultUp);\n\t\t\t\tscene.environmentRotation.copy(envRotation);\n\t\t\t\tif (config.environment.showEnvironment) {\n\t\t\t\t\t// Background wants the full-resolution equirect, not the low-res prefiltered probe —\n\t\t\t\t\t// so keep the raw map for that and let it dispose with the scene background sweep.\n\t\t\t\t\tscene.background = envMap;\n\t\t\t\t\t// Keep the visible background locked to the same orientation as the IBL probe;\n\t\t\t\t\t// they are separate properties and drift apart if only one is set.\n\t\t\t\t\tscene.backgroundRotation.copy(envRotation);\n\t\t\t\t} else {\n\t\t\t\t\t// The raw equirect was only an input to PMREM; the prefiltered probe has superseded\n\t\t\t\t\t// it for IBL and nothing else references it, so release it now.\n\t\t\t\t\tenvMap.dispose();\n\t\t\t\t}\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t},\n\t\t\tundefined,\n\t\t\tfunction (error) {\n\t\t\t\tif (isDisposed()) return;\n\t\t\t\tgetLogger().warn('HDR texture could not be loaded, falling back to basic lighting:', error);\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t}\n\t\t);\n\t} else {\n\t\tconfig.events.onReady?.();\n\t}\n}\n\n/** The lights created by {@link setupLighting}, handed back so runtime setters can retune them. */\ntype SceneLights = {\n\tambient: THREE.AmbientLight;\n\t/** Hemisphere fill light — null unless `lighting.enableHemisphereLight`. */\n\themisphere: THREE.HemisphereLight | null;\n\t/**\n\t * Shadow-casting sun. Null when sunlight is disabled or shadows are off — the caller uses it only\n\t * to refit the shadow frustum on geometry change (see `fitShadowToContent`), so null means nothing\n\t * to refit.\n\t */\n\tsun: THREE.DirectionalLight | null;\n};\n\n/**\n * Set up scene lighting. Returns handles to the created lights so the caller can refit the sun's\n * shadow frustum on geometry change and retune fill lights at runtime.\n */\nfunction setupLighting(scene: THREE.Scene, config: Required<ThreeInitializerOptions>): SceneLights {\n\tconst ambient = new THREE.AmbientLight(\n\t\tconfig.lighting.ambientLightColor,\n\t\tconfig.lighting.ambientLightIntensity\n\t);\n\tscene.add(ambient);\n\n\t// Hemisphere fill: soft sky-from-above / ground-from-below light that lifts occluded and\n\t// downward-facing surfaces the HDR may leave dark. Aligned to the scene up so \"sky\" is genuinely\n\t// up in a Z-up scene (a HemisphereLight defaults to +Y up).\n\tlet hemisphere: THREE.HemisphereLight | null = null;\n\tif (config.lighting.enableHemisphereLight) {\n\t\themisphere = new THREE.HemisphereLight(\n\t\t\tconfig.lighting.hemisphereSkyColor,\n\t\t\tconfig.lighting.hemisphereGroundColor,\n\t\t\tconfig.lighting.hemisphereIntensity\n\t\t);\n\t\tconst up = config.environment.sceneUp ?? defaultUp;\n\t\themisphere.position.copy(up);\n\t\tscene.add(hemisphere);\n\t}\n\n\tif (!config.lighting.enableSunlight) return { ambient, hemisphere, sun: null };\n\n\tconst sunlight = new THREE.DirectionalLight(\n\t\tconfig.lighting.sunlightColor ?? 0xffffff,\n\t\tconfig.lighting.sunlightIntensity\n\t);\n\tconst pos = config.lighting.sunlightPosition;\n\tif (pos) {\n\t\tsunlight.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\tif (!config.render.enableShadows) {\n\t\tscene.add(sunlight);\n\t\treturn { ambient, hemisphere, sun: null };\n\t}\n\n\tsunlight.castShadow = true;\n\n\t// The frustum bounds (left/right/top/bottom/near/far) are not set here — they are fitted to the\n\t// scene content by fitShadowToContent, called at init and on every geometry change. Sizing them\n\t// to the model instead of a fixed constant is the dominant lever on shadow crispness.\n\tsunlight.shadow.mapSize.width = config.render.shadowMapSize || 2048;\n\tsunlight.shadow.mapSize.height = config.render.shadowMapSize || 2048;\n\n\tsunlight.shadow.bias = -0.0001;\n\tsunlight.shadow.normalBias = 0.02;\n\t// Soften VSM edges; cheap and only meaningful once the frustum is tight (see fitShadowToContent).\n\tsunlight.shadow.radius = 4;\n\n\tscene.add(sunlight);\n\t// A DirectionalLight aims at its target's world position; the target must be in the scene graph\n\t// for its matrix to update. fitShadowToContent moves this target to the content centre.\n\tscene.add(sunlight.target);\n\treturn { ambient, hemisphere, sun: sunlight };\n}\n\nfunction addFloor(scene: THREE.Scene, config: Required<ThreeInitializerOptions>) {\n\tconst floorSize = config.floor.size;\n\tconst floorGeometry = new THREE.PlaneGeometry(floorSize, floorSize);\n\n\tconst floorColor =\n\t\ttypeof config.floor.color === 'string'\n\t\t\t? new THREE.Color(config.floor.color)\n\t\t\t: config.floor.color;\n\n\tconst floorMaterial = new THREE.MeshStandardMaterial({\n\t\tcolor: floorColor,\n\t\troughness: config.floor.roughness,\n\t\tmetalness: config.floor.metalness,\n\t\tside: THREE.DoubleSide\n\t});\n\n\tconst floor = new THREE.Mesh(floorGeometry, floorMaterial);\n\tfloor.userData.id = 'floor';\n\tfloor.name = 'floor';\n\t// PlaneGeometry lies in XY with a +Z normal — already the ground for a Z-up scene. Orient its\n\t// normal to the scene up axis so the floor is the ground plane in any up convention.\n\tconst up = (config.environment?.sceneUp || defaultUp).clone().normalize();\n\tfloor.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), up);\n\tfloor.position.set(0, 0, 0);\n\n\tif (config.floor.receiveShadow && config.render.enableShadows) {\n\t\tfloor.receiveShadow = true;\n\t}\n\n\tscene.add(floor);\n}\n\nfunction createCamera(\n\tconfig: Required<ThreeInitializerOptions>,\n\tcanvas: HTMLCanvasElement\n): THREE.PerspectiveCamera {\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tconst camera = new THREE.PerspectiveCamera(\n\t\tconfig.camera.fov,\n\t\twidth / height,\n\t\tconfig.camera.near,\n\t\tconfig.camera.far\n\t);\n\n\tconst pos = config.camera.position;\n\tif (pos) {\n\t\tcamera.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\treturn camera;\n}\n\nfunction setupRenderer(\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>,\n\tpixelRatio: number\n): THREE.WebGLRenderer {\n\tconst renderer = new THREE.WebGLRenderer({\n\t\tantialias: config.render.antialias,\n\t\tcanvas,\n\t\talpha: true,\n\t\tpowerPreference: 'high-performance',\n\t\tpreserveDrawingBuffer: config.render.preserveDrawingBuffer,\n\t\t// Deliberately NOT logarithmic: three's depth-based post passes (our GTAO pipeline) reconstruct\n\t\t// view-space positions assuming standard perspective depth and do not support log-encoded\n\t\t// depth — with it on, AO is computed from wrong depths (haloing, wrong-scale occlusion). The\n\t\t// per-scale near/far defaults (see applyDefaults) keep standard depth precision adequate for\n\t\t// the viewer's scene scales. If log depth is ever needed, AO must be disabled with it.\n\t\tlogarithmicDepthBuffer: false\n\t});\n\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tif (parent) {\n\t\tcanvas.style.width = '100%';\n\t\tcanvas.style.height = '100%';\n\t\tcanvas.style.display = 'block';\n\t}\n\n\trenderer.setSize(width, height, false);\n\trenderer.setPixelRatio(pixelRatio);\n\n\tif (config.render.enableShadows) {\n\t\trenderer.shadowMap.enabled = true;\n\t\trenderer.shadowMap.type = THREE.VSMShadowMap;\n\t}\n\n\trenderer.toneMapping = config.render.toneMapping!;\n\trenderer.toneMappingExposure = config.render.toneMappingExposure ?? 1.0;\n\trenderer.outputColorSpace = THREE.SRGBColorSpace;\n\n\trenderer.sortObjects = true;\n\n\treturn renderer;\n}\n\nfunction setupEventHandlers(\n\tcanvas: HTMLCanvasElement,\n\tscene: THREE.Scene,\n\tcameraController: CameraController,\n\tconfig: Required<ThreeInitializerOptions>\n): {\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n} {\n\tconst selectedObjects = new Set<THREE.Object3D>();\n\tconst originalMaterials = new Map<THREE.Object3D, THREE.Material | THREE.Material[]>();\n\tconst raycaster = new THREE.Raycaster();\n\tconst mouse = new THREE.Vector2();\n\tconst mouseDownPosition = new THREE.Vector2();\n\tconst getActiveCamera = () => cameraController.getActiveCamera();\n\n\t// An object is hittable only if every ancestor is also visible. Three.js's\n\t// recursive intersect doesn't enforce that — it can hit a visible Mesh inside\n\t// a hidden Group.\n\tconst isFullyVisible = (object: THREE.Object3D): boolean => {\n\t\tlet current: THREE.Object3D | null = object;\n\t\twhile (current) {\n\t\t\tif (!current.visible) return false;\n\t\t\tcurrent = current.parent;\n\t\t}\n\t\treturn true;\n\t};\n\n\tconst fitToView = () => {\n\t\t// Frame the scene's renderable content; viewer aids (grid/floor/labels/measure) are excluded so\n\t\t// the camera-tracking grid plane can't dominate the bounds and blow up the fit distance.\n\t\tconst box = computeContentBounds(scene);\n\n\t\tif (box.isEmpty()) {\n\t\t\tgetLogger().warn('No objects to fit to view');\n\t\t\treturn;\n\t\t}\n\n\t\t// Delegate the move to the camera controller: it frames from the current view direction and\n\t\t// repositions whichever camera is LIVE, re-deriving the ortho frustum in 2D mode — whereas\n\t\t// moving the perspective camera directly would change nothing visible in 2D (and silently\n\t\t// drag the invisible perspective camera out of sync).\n\t\tcameraController.frameBounds(box, false);\n\t};\n\n\tconst selectionColorObj =\n\t\ttypeof config.events.selectionColor === 'string'\n\t\t\t? new THREE.Color(config.events.selectionColor)\n\t\t\t: config.events.selectionColor instanceof THREE.Color\n\t\t\t\t? config.events.selectionColor\n\t\t\t\t: new THREE.Color('#ff0000');\n\n\tconst clearSelection = () => {\n\t\tselectedObjects.forEach((obj) => {\n\t\t\tconst restorable = obj as THREE.Object3D & {\n\t\t\t\tmaterial?: THREE.Material | THREE.Material[];\n\t\t\t};\n\t\t\tif (originalMaterials.has(obj)) {\n\t\t\t\tconst original = originalMaterials.get(obj)!;\n\t\t\t\t// Dispose the clone we swapped in before restoring the original.\n\t\t\t\tconst clone = restorable.material;\n\t\t\t\tif (clone instanceof THREE.Material) clone.dispose();\n\t\t\t\telse if (Array.isArray(clone)) clone.forEach((m) => m.dispose());\n\t\t\t\trestorable.material = original;\n\t\t\t\toriginalMaterials.delete(obj);\n\n\t\t\t\t// If the object left the scene while selected (a solve's clearScene only saw — and\n\t\t\t\t// disposed — the highlight clone), no later scene traversal can reach the original we\n\t\t\t\t// just restored, so it must be disposed here. Compute content is cleared wholesale per\n\t\t\t\t// solve, so a detached object's material has no surviving sharers.\n\t\t\t\tlet root: THREE.Object3D = obj;\n\t\t\t\twhile (root.parent) root = root.parent;\n\t\t\t\tif (root !== scene) {\n\t\t\t\t\tif (original instanceof THREE.Material) original.dispose();\n\t\t\t\t\telse original.forEach((m) => m.dispose());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tselectedObjects.clear();\n\t};\n\n\t// Highlight a selected object by cloning its material and recoloring. Meshes get an `emissive`\n\t// tint (so the surface keeps its base color); lines and points have no emissive channel, so we\n\t// recolor `color` directly. Returns true if a highlight was applied (a material was found).\n\tconst applyHighlight = (object: THREE.Object3D): boolean => {\n\t\tconst target = object as THREE.Object3D & { material?: THREE.Material | THREE.Material[] };\n\t\tif (!(target.material instanceof THREE.Material)) return false;\n\n\t\toriginalMaterials.set(object, target.material);\n\t\tconst clone = target.material.clone();\n\n\t\tif (object instanceof THREE.Mesh && 'emissive' in clone) {\n\t\t\t(clone as THREE.MeshStandardMaterial).emissive = selectionColorObj.clone();\n\t\t} else if ('color' in clone) {\n\t\t\t(clone as THREE.LineBasicMaterial).color = selectionColorObj.clone();\n\t\t}\n\n\t\ttarget.material = clone;\n\t\treturn true;\n\t};\n\n\t// Picking lines and points needs a ray-to-geometry tolerance, scaled to the scene so it holds at\n\t// any zoom. Plain THREE.Points use Raycaster.params.Points.threshold; fat Line2 uses its own\n\t// material linewidth, so only Points needs this. (THREE.Line would use params.Line.threshold, but\n\t// curves here are Line2.) Recomputed per pick from the current scene bounds.\n\tconst updatePickThresholds = () => {\n\t\tconst box = computeContentBounds(scene);\n\t\tconst diagonal = box.isEmpty() ? 1 : box.getSize(new THREE.Vector3()).length();\n\t\traycaster.params.Points.threshold = diagonal * 0.01;\n\t};\n\n\tconst handleMouseDown = (event: MouseEvent) => {\n\t\tmouseDownPosition.set(event.clientX, event.clientY);\n\t};\n\n\tconst handleCanvasClick = (event: MouseEvent) => {\n\t\t// Ignore if mouse has moved (drag)\n\t\tconst currentMousePosition = new THREE.Vector2(event.clientX, event.clientY);\n\t\tif (mouseDownPosition.distanceTo(currentMousePosition) > 5) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tupdatePickThresholds();\n\t\traycaster.setFromCamera(mouse, getActiveCamera());\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length > 0) {\n\t\t\tconst clickedObject = intersects[0].object;\n\n\t\t\tif (!selectedObjects.has(clickedObject)) {\n\t\t\t\tclearSelection();\n\t\t\t\tselectedObjects.add(clickedObject);\n\n\t\t\t\t// Clone material (so siblings sharing it are untouched) and recolor to highlight.\n\t\t\t\t// Handles meshes, fat lines, and points alike.\n\t\t\t\tapplyHighlight(clickedObject);\n\n\t\t\t\tconfig.events?.onObjectSelected?.(clickedObject);\n\n\t\t\t\tif (clickedObject instanceof THREE.Mesh && Object.keys(clickedObject.userData).length > 0) {\n\t\t\t\t\tconfig.events?.onMeshMetadataClicked?.(clickedObject.userData);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tclearSelection();\n\t\t\tconfig.events?.onBackgroundClicked?.({ x: mouse.x, y: mouse.y });\n\t\t}\n\t};\n\n\tconst handleDoubleClick = (event: MouseEvent) => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tupdatePickThresholds();\n\t\traycaster.setFromCamera(mouse, getActiveCamera());\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length === 0) return;\n\n\t\tconst target = intersects[0].object;\n\t\tconfig.events?.onMeshDoubleClicked?.(target);\n\n\t\tif (!config.events?.enableDoubleClickZoom) return;\n\n\t\tconst box = new THREE.Box3().setFromObject(target);\n\t\tif (box.isEmpty()) return;\n\n\t\t// Frame the clicked object via the controller so the ACTIVE camera moves (ortho included —\n\t\t// its frustum is re-derived, since translating an ortho camera alone zooms nothing). The\n\t\t// controller's tween is cancellable: a rapid second double-click replaces the first tween\n\t\t// instead of running a competing loop, and dispose() stops it outright.\n\t\tcameraController.frameBounds(box, true);\n\t};\n\n\tconst handleKeydown = (event: KeyboardEvent) => {\n\t\tif (!config.events?.enableKeyboardControls) return;\n\n\t\tswitch (event.key.toLowerCase()) {\n\t\t\tcase 'f':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t\tcase 'escape':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tclearSelection();\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t}\n\t};\n\n\tif (config.events?.enableClickToFocus) {\n\t\tcanvas.addEventListener('mousedown', handleMouseDown);\n\t\tcanvas.addEventListener('click', handleCanvasClick);\n\t\tcanvas.addEventListener('dblclick', handleDoubleClick);\n\t}\n\n\tif (config.events?.enableKeyboardControls) {\n\t\tcanvas.setAttribute('tabindex', '0');\n\t\tcanvas.addEventListener('keydown', handleKeydown);\n\t}\n\n\tconst dispose = () => {\n\t\tcanvas.removeEventListener('mousedown', handleMouseDown);\n\t\tcanvas.removeEventListener('click', handleCanvasClick);\n\t\tcanvas.removeEventListener('dblclick', handleDoubleClick);\n\t\tcanvas.removeEventListener('keydown', handleKeydown);\n\t\tclearSelection();\n\t};\n\n\treturn { dispose, fitToView, clearSelection };\n}\n\nfunction setupControls(\n\tcamera: THREE.PerspectiveCamera,\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>\n): OrbitControls {\n\tconst controls = new OrbitControls(camera, canvas);\n\n\tconst target = config.camera.target;\n\tif (target) {\n\t\tcontrols.target.set(target.x, target.y, target.z);\n\t}\n\n\tcontrols.enableDamping = config.controls.enableDamping || false;\n\tcontrols.dampingFactor = config.controls.dampingFactor || 0.05;\n\n\tcontrols.autoRotate = config.controls.autoRotate || false;\n\tcontrols.autoRotateSpeed = config.controls.autoRotateSpeed || 0.5;\n\n\tcontrols.enableZoom = config.controls.enableZoom ?? true;\n\tcontrols.enablePan = config.controls.enablePan ?? true;\n\tcontrols.minDistance = config.controls.minDistance || 0.001;\n\tcontrols.maxDistance = config.controls.maxDistance || Infinity;\n\n\tcontrols.screenSpacePanning = false;\n\tcontrols.maxPolarAngle = Math.PI;\n\n\tcontrols.update();\n\treturn controls;\n}\n","import * as THREE from 'three';\n\nimport { computeContentBounds } from './three-helpers';\n\n/**\n * Per-frame dynamic near-plane fitting for the perspective camera.\n *\n * Depth-buffer precision is ∝ near/z²: with a fixed tiny near (0.01 m for the 'm' scale) a depth\n * ULP grows to ~0.25 m at 200 m viewing distance, which is what makes distant coplanar-ish surfaces\n * z-fight and any constant depth bias balloon to meter scale. Pushing `near` up to a fraction of\n * the camera's gap to the nearest thing it can see recovers that precision — 10–100× when zoomed\n * out — without clipping anything.\n *\n * Only `near` is fitted; `far` barely affects precision and must keep covering large aids (grid\n * fade region, floor), so it stays owned by config/`updateScene`. External writes to `camera.near`\n * (the per-solve static fit in `updateScene`, host code) are adopted as the new lower bound rather\n * than fought: the fitter only ever *raises* near above that floor.\n *\n * The 2D orthographic camera needs no fitting (ortho depth is linear) and is untouched — updating\n * the dormant perspective camera while 2D is active is harmless.\n */\n\n/** Stay this fraction of the gap back from the nearest clippable thing — headroom for the frame's camera motion and bounds staleness. */\nconst NEAR_GAP_FRACTION = 0.5;\n/** Never push near beyond this fraction of far: keeps the frustum sane if the camera flies out. */\nconst MAX_NEAR_TO_FAR = 0.01;\n/** Skip sub-5% changes so the projection matrix isn't rebuilt every frame while orbiting. */\nconst APPLY_THRESHOLD = 0.05;\n\nexport interface NearPlaneFitterOptions {\n\tcamera: THREE.PerspectiveCamera;\n\tscene: THREE.Scene;\n\t/**\n\t * Unit normals of ground planes through the origin that carry ground aids (grid, floor). The\n\t * camera's perpendicular distance to each also bounds near — the aid re-centers under the camera,\n\t * so content distance alone would clip it at grazing views.\n\t *\n\t * Pass a callback, not a snapshot: these aids are runtime-toggleable, and a hidden one must not\n\t * constrain anything. The clamp is proportional to the camera's *height above the plane*, so a\n\t * grid that merely exists — built once so it can be toggled, but currently invisible — would\n\t * collapse `near` toward 0 at grazing views and destroy depth precision (ULP ∝ 1/near) to protect\n\t * geometry nobody can see. Return only the planes whose aid is visible this frame.\n\t */\n\tgroundNormals?: () => THREE.Vector3[];\n}\n\nexport interface NearPlaneFitter {\n\t/** Refit `camera.near` to the current camera/content. Call once per frame, before rendering. */\n\tupdate: () => void;\n}\n\nconst NO_GROUND_NORMALS: THREE.Vector3[] = [];\n\nexport function createNearPlaneFitter({\n\tcamera,\n\tscene,\n\tgroundNormals = () => NO_GROUND_NORMALS\n}: NearPlaneFitterOptions): NearPlaneFitter {\n\t// The floor near never fitted below. Seeded from construction config; re-adopted whenever\n\t// something other than this fitter writes camera.near.\n\tlet baseNear = camera.near;\n\tlet appliedNear = camera.near;\n\n\tconst center = new THREE.Vector3();\n\tconst size = new THREE.Vector3();\n\n\tconst update = () => {\n\t\tif (camera.near !== appliedNear) baseNear = camera.near; // external write → new floor\n\n\t\tconst bounds = computeContentBounds(scene);\n\t\tlet near = baseNear;\n\t\tif (!bounds.isEmpty()) {\n\t\t\t// Gap to the content's bounding sphere: the closest any content can be to the camera.\n\t\t\tconst radius = bounds.getSize(size).length() * 0.5;\n\t\t\tlet gap = camera.position.distanceTo(bounds.getCenter(center)) - radius;\n\t\t\tfor (const normal of groundNormals()) {\n\t\t\t\tgap = Math.min(gap, Math.abs(camera.position.dot(normal)));\n\t\t\t}\n\t\t\tnear = THREE.MathUtils.clamp(gap * NEAR_GAP_FRACTION, baseNear, camera.far * MAX_NEAR_TO_FAR);\n\t\t}\n\n\t\tif (Math.abs(near - appliedNear) > appliedNear * APPLY_THRESHOLD) {\n\t\t\tcamera.near = near;\n\t\t\tcamera.updateProjectionMatrix();\n\t\t\tappliedNear = near;\n\t\t}\n\t};\n\n\treturn { update };\n}\n","import * as THREE from 'three';\n\nexport type CameraConfig = {\n\tposition?: THREE.Vector3;\n\tfov?: number;\n\tnear?: number;\n\tfar?: number;\n\ttarget?: THREE.Vector3;\n\t/**\n\t * Refit the perspective camera's near plane to the camera↔content gap every frame (default true).\n\t * Recovers depth-buffer precision when zoomed out (precision ∝ near/z²), which is what stops\n\t * distant surfaces z-fighting. `near` stays the lower bound — the plane is only raised, never\n\t * lowered below it.\n\t */\n\tdynamicNear?: boolean;\n};\n\nexport type LightingConfig = {\n\tenableSunlight?: boolean;\n\tsunlightIntensity?: number;\n\tsunlightPosition?: THREE.Vector3;\n\tambientLightColor?: THREE.Color;\n\tambientLightIntensity?: number;\n\tsunlightColor?: THREE.Color | number;\n\t/**\n\t * Add a hemisphere fill light (sky color from above, ground color from below). Unlike the flat\n\t * ambient, this gives soft *direction-aware* fill, so downward- and side-facing surfaces never\n\t * collapse to black when the HDR's lower hemisphere is dark. The single biggest lever for keeping\n\t * results well-lit regardless of which HDR is loaded. Default false (opt-in) — enabling it shifts\n\t * the look. See {@link LightingConfig.hemisphereIntensity}.\n\t */\n\tenableHemisphereLight?: boolean;\n\t/** Hemisphere fill sky color (lights upward-facing surfaces). Default white. */\n\themisphereSkyColor?: THREE.Color | number;\n\t/** Hemisphere fill ground color (lights downward-facing surfaces). Default a mid grey. */\n\themisphereGroundColor?: THREE.Color | number;\n\t/** Hemisphere fill strength. Default 0.6. Only applies when {@link LightingConfig.enableHemisphereLight}. */\n\themisphereIntensity?: number;\n};\n\nexport type EnvironmentConfig = {\n\thdrPath?: string;\n\tbackgroundColor?: THREE.Color | string;\n\tenableEnvironmentLighting?: boolean;\n\t/**\n\t * The scene's up axis. **Defaults to `(0, 0, 1)` — Rhino's Z-up**, not Three's native Y-up,\n\t * because geometry arrives in Rhino's frame and is never rotated on ingress (see\n\t * `coordinate-transform.ts`). Everything orientation-dependent derives from this: view presets,\n\t * the default iso camera, sun position, grid plane, floor normal, and the hemisphere light.\n\t *\n\t * Overriding it reorients the viewer but does NOT rotate incoming geometry, so a Y-up value only\n\t * makes sense if the host also feeds Y-up geometry.\n\t */\n\tsceneUp?: THREE.Vector3;\n\tshowEnvironment?: boolean;\n\t/**\n\t * Uniform multiplier on the HDR's image-based lighting contribution (`scene.environmentIntensity`).\n\t * Normalizes brightness across HDRs of differing exposure — raise it to lift a dim HDR, lower it to\n\t * tame a blown-out one — so the scene doesn't render dim-or-blown purely because of the HDR chosen.\n\t * Default 1 (three.js default, unchanged look).\n\t */\n\tenvironmentIntensity?: number;\n};\n\nexport type FloorConfig = {\n\tenabled?: boolean;\n\tsize?: number;\n\tcolor?: THREE.Color | string;\n\troughness?: number;\n\tmetalness?: number;\n\treceiveShadow?: boolean;\n};\n\nexport type RenderConfig = {\n\tenableShadows?: boolean;\n\tshadowMapSize?: number;\n\tantialias?: boolean;\n\tpixelRatio?: number;\n\ttoneMapping?: THREE.ToneMapping;\n\ttoneMappingExposure?: number;\n\tpreserveDrawingBuffer?: boolean;\n\t/**\n\t * Enable ground-truth ambient occlusion (GTAO) via a postprocessing pipeline. Default false —\n\t * turning it on switches rendering from `renderer.render` to an EffectComposer, which costs more.\n\t */\n\tambientOcclusion?: boolean;\n\t/** AO strength 0–1 when {@link RenderConfig.ambientOcclusion} is on. Default 1. */\n\taoIntensity?: number;\n\t/**\n\t * Device-pixel-ratio cap for the ambient-occlusion postprocessing buffers. AO is low-frequency, so\n\t * rendering its buffers below the display DPR is nearly invisible but hugely cheaper — on a Retina\n\t * display (DPR 2) full-resolution AO means 4× the pixels through GTAO's per-pixel sample loops,\n\t * which can dominate frame time. Default 1 (AO buffers at 1× regardless of display DPR). Raise\n\t * toward the display DPR for sharper AO at higher cost; only relevant when AO is enabled.\n\t */\n\taoPixelRatio?: number;\n\t/**\n\t * Render only when something changed (camera motion, invalidate(), pointer input, resize), with\n\t * a ~500 ms safety repaint, instead of every animation frame. Default true — cuts idle GPU/battery\n\t * to ~2 fps worth of work, which matters especially with ambient occlusion on. Set false to\n\t * restore the legacy continuous loop.\n\t */\n\tonDemand?: boolean;\n};\n\n/**\n * A ready-to-go visual look. A `look` is a named bundle of LIGHTING/MATERIAL defaults only — it is\n * deliberately decoupled from the CAD overlays (edges, grid), which are driven independently by\n * {@link EdgesConfig}/{@link GridConfig}. Pick one and the viewer looks professional with zero other\n * config; every individual `lighting`/`environment`/`render` option still overrides the preset. Seeds\n * construction defaults and can be re-applied live via `setLook`.\n *\n * - 'technical' (default): matte, drawing-like — neutral tone mapping, low IBL, no fill. Reads like a\n * CAD shaded view (Rhino/Onshape).\n * - 'studio': balanced presentation — ACES tone mapping, hemisphere fill + lifted HDR so results are\n * well-lit regardless of the HDR, without washing colour out. The polished \"product shot\" look.\n * - 'showcase': punchier presentation — ACES, stronger IBL/fill and a touch more exposure.\n */\n/**\n * The look values as a runtime array — the single source of truth. {@link Look} is derived from it, so\n * the type and the enumerable list can never drift. Consumers (e.g. a viewer's style picker) iterate\n * this instead of hardcoding the names, so adding or renaming a look here updates them automatically.\n * 'technical' is first because it's the default.\n */\nexport const LOOKS = ['technical', 'studio', 'showcase'] as const;\n\nexport type Look = (typeof LOOKS)[number];\n\n/**\n * The lighting/material dials a {@link Look} sets. Single source of truth shared by construction-time\n * defaults and the runtime `setLook`, so the two never drift. `envMapIntensity` and `cullBackfaces`\n * are parse-time material choices (see the batch parser's `material` option, exposed via\n * `materialAppearanceForLook`); the rest are applied to the live scene. A look does NOT carry edges\n * or grid — those are independent overlay concerns.\n */\nexport type LookPreset = {\n\ttoneMapping: THREE.ToneMapping;\n\ttoneMappingExposure: number;\n\t/** IBL reflection strength on compute materials (parse-time material choice). */\n\tenvMapIntensity: number;\n\t/**\n\t * Uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`). The\n\t * 'studio'/'showcase' looks lift this above 1 so results stay bright regardless of the HDR.\n\t */\n\tenvironmentIntensity: number;\n\t/**\n\t * Hemisphere fill strength. The 'studio'/'showcase' looks turn it on (direction-aware fill that\n\t * lifts shadowed / under-facing surfaces a dark HDR leaves black); 'technical' keeps it 0.\n\t */\n\themisphereIntensity: number;\n\t/**\n\t * Flat ambient strength. Kept low on 'studio'/'showcase' so the hemisphere fill carries the lift\n\t * without the flat white ambient desaturating colour.\n\t */\n\tambientIntensity: number;\n\t/** Cull back faces on compute meshes (parse-time material choice; crisper solids). */\n\tcullBackfaces: boolean;\n\tambientOcclusion: boolean;\n};\n\n/** Crisp boundary/crease edge overlays on meshes. See `addEdges`. */\nexport type EdgesConfig = {\n\t/** Auto-attach edge overlays to meshes as they load. Default false (opt-in). */\n\tenabled?: boolean;\n\t/**\n\t * Force a single edge color for all meshes. Omit (the default) to derive each mesh's edge color\n\t * from its own surface material, darkened by `darken` — so edges read as the object's own outline.\n\t */\n\tcolor?: THREE.ColorRepresentation;\n\t/**\n\t * How far derived edge colors are darkened toward black, 0–1 (default 0.75). Ignored when `color`\n\t * is set.\n\t */\n\tdarken?: number;\n\t/** Edge thickness in CSS px. Default 1.5. */\n\twidth?: number;\n\t/** Crease angle (degrees): keep edges where faces differ by more than this. Default 44. */\n\tthresholdAngle?: number;\n\t/** Fade an overlay out as its mesh shrinks on screen, so far zoom-outs stay clean. Default true. */\n\tdistanceFade?: boolean;\n\t/** Skip overlay extraction for meshes above this triangle count. Default 4M. See `EdgeOptions`. */\n\tmaxTriangles?: number;\n\t/** Overlays above this segment count render opaque (no distance fade). Default 2M. */\n\tmaxSegments?: number;\n\t/**\n\t * When a mesh is skipped for exceeding `maxTriangles`, approximate its edges with the\n\t * screen-space edge-detection pass (constant cost in triangle count). Default true.\n\t */\n\tscreenSpaceFallback?: boolean;\n};\n\nexport type ControlsConfig = {\n\tenableDamping?: boolean;\n\tdampingFactor?: number;\n\tautoRotate?: boolean;\n\tautoRotateSpeed?: number;\n\tenableZoom?: boolean;\n\tenablePan?: boolean;\n\tminDistance?: number;\n\tmaxDistance?: number;\n};\n\n/** Infinite distance-fading reference grid. See `createGrid`. */\nexport type GridConfig = {\n\t/** Show the grid. Default false (opt-in). */\n\tenabled?: boolean;\n\t/** Minor cell size in world units (meters). Default 1. */\n\tcellSize?: number;\n\t/** Minor cells per major line. Default 10. */\n\tmajorEvery?: number;\n\t/** Minor line color. */\n\tcellColor?: THREE.ColorRepresentation;\n\t/** Major line color. */\n\tmajorColor?: THREE.ColorRepresentation;\n\t/** World radius at which the grid fully fades. Default 100. */\n\tfadeDistance?: number;\n\t/**\n\t * Axis the grid lies perpendicular to — the scene's up axis. Defaults to whichever axis\n\t * `sceneUp` points along, so it is `'z'` (Rhino's horizontal ground) unless you override\n\t * `sceneUp`. Set explicitly only to force a grid orientation that ignores the scene up.\n\t */\n\tplane?: 'x' | 'y' | 'z';\n};\n\n/** Corner nav-cube/axis gizmo that snaps to preset views. See `createViewGizmo`. */\nexport type GizmoConfig = {\n\t/** Show the gizmo. Default false (opt-in). */\n\tenabled?: boolean;\n};\n\n/** Two-click distance measurement tool. See `createMeasureTool`. */\nexport type MeasureConfig = {\n\t/**\n\t * Create the measurement tool. Default false. Note: this only *builds* the tool (and its label\n\t * overlay); start measuring by calling `measureTool.setEnabled(true)` on the init result.\n\t */\n\tenabled?: boolean;\n\t/** Snap to a vertex within this many screen px. Default 12. */\n\tsnapPixels?: number;\n\t/** Marker + line color. Default yellow. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** CSS class for the distance label. */\n\tlabelClassName?: string;\n\t/**\n\t * Model unit (pass the response's `modelunits`). The scene is in meters, so the default label is\n\t * converted to this unit — a mm model reads \"25.0 mm\". Defaults to meters. Ignored if `format` is set.\n\t */\n\tdisplayUnit?: string;\n\t/**\n\t * Format the measurement → label text. Receives the straight-line `distance` and per-axis `delta`.\n\t * Default renders the total plus a Δx/Δy/Δz breakdown.\n\t */\n\tformat?: (distance: number, delta: THREE.Vector3) => string;\n};\n\nexport type ThreeInitializerOptions = {\n\tsceneScale?: 'mm' | 'cm' | 'm' | 'inches' | 'feet';\n\t/**\n\t * Pick a ready-to-go visual look up front — seeds professional lighting/material defaults (tone\n\t * mapping, AO, IBL strength, hemisphere fill; see {@link Look}). Individual `lighting`/\n\t * `environment`/`render` options still win when set explicitly, so this only fills in what you\n\t * leave unspecified. A look does NOT touch edges/grid (those are independent overlays). Defaults\n\t * to 'technical'. Re-apply later via the init result's `setLook`.\n\t */\n\tlook?: Look;\n\tcamera?: CameraConfig;\n\tlighting?: LightingConfig;\n\tenvironment?: EnvironmentConfig;\n\tfloor?: FloorConfig;\n\trender?: RenderConfig;\n\tcontrols?: ControlsConfig;\n\tgrid?: GridConfig;\n\tgizmo?: GizmoConfig;\n\tedges?: EdgesConfig;\n\tmeasure?: MeasureConfig;\n\tevents?: EventConfig;\n};\n\nexport type EventConfig = {\n\tonBackgroundClicked?: (event: { x: number; y: number }) => void;\n\tonObjectSelected?: (object: THREE.Object3D) => void;\n\t/** Called when a mesh with metadata is clicked. Receives the mesh's metadata object. */\n\tonMeshMetadataClicked?: (metadata: Record<string, string>) => void;\n\t/** Called when a mesh is double-clicked. Receives the mesh object. */\n\tonMeshDoubleClicked?: (object: THREE.Object3D) => void;\n\t/** Color to use for highlighting selected meshes. Defaults to red (#ff0000). */\n\tselectionColor?: THREE.Color | string;\n\t/** Enable all event handlers (click/selection/metadata). Defaults to true. */\n\tenableEventHandlers?: boolean;\n\tenableKeyboardControls?: boolean;\n\tenableClickToFocus?: boolean;\n\t/** Zoom into a mesh on double-click. Defaults to true. */\n\tenableDoubleClickZoom?: boolean;\n\t/** Called once the HDR environment map has finished loading and been applied to the scene. */\n\tonReady?: () => void;\n\t/** Called every animation frame, after controls update and before render. Use for custom per-frame logic. */\n\tonFrame?: (delta: number) => void;\n};\n","import * as THREE from 'three';\nimport { Line2 } from 'three/addons/lines/Line2.js';\nimport { LineGeometry } from 'three/addons/lines/LineGeometry.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport { getLogger } from '@/core';\n\nimport { rhinoToThree } from '../coordinate-transform';\n\nimport type { DisplayCurve, DisplayItem, DisplayPoint } from './types';\nimport type { RhinoModule } from 'rhino3dm';\n\n/**\n * Builds THREE.js objects from the non-mesh display items on a DisplayBatch — curves (decoded from\n * Rhino-native JSON via rhino3dm and tessellated to a fat `Line2`) and points (raw positions\n * rendered as one {@link THREE.Points}). Mirrors the mesh path's coordinate handling: every position\n * goes through {@link rhinoToThree}, which is the identity — the Three scene IS Rhino's Z-up frame,\n * so items land at their Rhino coordinates, same as meshes (see `../coordinate-transform.ts`).\n *\n * selva-compute does not own the rhino3dm WASM instance (it is heavy and the host app initializes\n * it once); the caller threads it in, same as the response decoder. If no instance is supplied,\n * curves are skipped with a warning and points still render — they need no decode.\n */\n\nconst DEFAULT_COLOR = '#ffffff';\n\n/**\n * Adaptive tessellation parameters. Rather than a fixed segment count, curved spans are recursively\n * split until the midpoint of a span sits within {@link CURVE_CHORD_TOLERANCE_RATIO} of the curve's\n * size from the straight chord — so a span gets points in proportion to how much it actually bends.\n */\n/** Initial uniform splits before adaptive refinement kicks in (ensures closed/looping curves aren't collapsed). */\nconst CURVE_INITIAL_SEGMENTS = 12;\n/** Chord-deviation tolerance as a fraction of the curve's bounding-box diagonal. Smaller = smoother. */\nconst CURVE_CHORD_TOLERANCE_RATIO = 0.0004;\n/** Hard recursion-depth cap per initial span, so pathological curves can't explode the vertex count. */\nconst CURVE_MAX_SUBDIVISION_DEPTH = 12;\n/** Max turn angle (radians) allowed across a span before it's split. ~3° keeps arcs visibly smooth. */\nconst CURVE_MAX_TURN_RADIANS = 0.05;\n\nexport interface DisplayItemParseOptions {\n\t/** rhino3dm instance for decoding curve JSON. Omit to skip curves (points still render). */\n\trhino?: RhinoModule;\n\t/**\n\t * No-op. Historically toggled the Rhino Z-up → Three Y-up rotation, but the pipeline now keeps\n\t * one coordinate frame end to end ({@link rhinoToThree} is the identity), so this flag no longer\n\t * changes the result. Do NOT pre-rotate your own geometry to compensate — none is applied.\n\t *\n\t * @deprecated Retained only so existing call sites compile unchanged; has no effect.\n\t */\n\tapplyTransforms?: boolean;\n}\n\n/**\n * Parse a batch's `items` into renderable THREE objects. Returns an empty array when there are no\n * items. Unknown kinds are skipped with a warning (forward-compatible with future label/icon kinds\n * a viewer hasn't taught itself to render yet).\n */\nexport function parseDisplayItems(\n\titems: DisplayItem[] | undefined,\n\toptions: DisplayItemParseOptions = {}\n): THREE.Object3D[] {\n\tif (!items || items.length === 0) return [];\n\n\tconst { rhino, applyTransforms = true } = options;\n\tconst objects: THREE.Object3D[] = [];\n\n\tfor (const item of items) {\n\t\tswitch (item.kind) {\n\t\t\tcase 'curve': {\n\t\t\t\tconst line = buildCurveLine(item, rhino, applyTransforms);\n\t\t\t\tif (line) objects.push(line);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'point': {\n\t\t\t\tconst point = buildPoint(item, applyTransforms);\n\t\t\t\tif (point) objects.push(point);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t// Exhaustiveness guard: assigning to `never` makes a new kind added to the union\n\t\t\t\t// without a case here a compile error. At runtime (plain-JS callers, newer\n\t\t\t\t// producers) an unrecognized kind still reaches this branch and is skipped.\n\t\t\t\tconst unhandled: never = item;\n\t\t\t\tconst unknown = unhandled as { kind?: string };\n\t\t\t\tgetLogger().warn(`Skipping unknown display item kind: ${String(unknown.kind)}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn objects;\n}\n\n/** Default fat-line thickness (CSS px) when a curve carries no explicit {@link DisplayCurve.width}. */\nconst DEFAULT_LINE_WIDTH = 2;\n\n/**\n * Decode a curve's Rhino JSON and tessellate it to a fat `Line2`. Returns null if rhino3dm is absent\n * or decoding fails, so one bad curve never aborts the whole batch.\n *\n * Uses `Line2`/`LineMaterial` rather than `THREE.Line` so thickness (`item.width`) is actually\n * honoured — plain `THREE.Line` is hard-capped at 1px on every major GPU backend. `LineMaterial`\n * needs its `resolution` set to the drawing-buffer size, but `Line2.onBeforeRender` does that\n * automatically from the renderer each frame, so the parser needs no renderer reference.\n */\nfunction buildCurveLine(\n\titem: DisplayCurve,\n\trhino: RhinoModule | undefined,\n\tapplyTransforms: boolean\n): Line2 | null {\n\tif (!rhino) {\n\t\tgetLogger().warn('No rhino3dm instance provided; skipping curve display item.');\n\t\treturn null;\n\t}\n\n\tconst curve = decodeCurve(item.json, rhino);\n\tif (!curve) return null;\n\n\tlet points: THREE.Vector3[];\n\ttry {\n\t\tpoints = tessellate(curve, applyTransforms);\n\t} catch (error) {\n\t\t// WASM calls (pointAt / tryGetPolyline / getBoundingBox) can throw on malformed geometry.\n\t\t// Log and skip this curve so one bad item never aborts the whole batch (contract above).\n\t\tgetLogger().warn('Failed to tessellate curve display item; skipping.', error);\n\t\treturn null;\n\t} finally {\n\t\tdeleteRhinoObject(curve);\n\t}\n\tif (points.length < 2) return null;\n\n\tconst positions: number[] = [];\n\tfor (const p of points) positions.push(p.x, p.y, p.z);\n\n\tconst geometry = new LineGeometry();\n\tgeometry.setPositions(positions);\n\n\t// @types/three's LineMaterial omits `linewidth` (and doesn't surface `transparent`/`opacity`\n\t// through its chain) though all exist at runtime. Set them via a narrow typed view rather than\n\t// scattering casts.\n\tconst params = materialParams(item.color, item.opacity);\n\tconst material = new LineMaterial({ color: params.color });\n\tconst styled = material as LineMaterial & {\n\t\tlinewidth: number;\n\t\ttransparent: boolean;\n\t\topacity: number;\n\t};\n\tstyled.linewidth = item.width ?? DEFAULT_LINE_WIDTH; // CSS px (worldUnits defaults false)\n\tstyled.transparent = params.transparent;\n\tstyled.opacity = params.opacity;\n\n\tconst line = new Line2(geometry, material);\n\tline.computeLineDistances(); // required for any future dashed styling; cheap\n\tline.name = item.name;\n\tline.userData = {\n\t\tsource: 'compute',\n\t\tid: item.id,\n\t\tlayer: item.layer,\n\t\tkind: 'curve',\n\t\tmetadata: item.metadata\n\t};\n\treturn line;\n}\n\n/**\n * Render a single point as a one-vertex THREE.Points. Returns null (with a warning) when the item's\n * position is missing or non-finite — display items arrive as network JSON, so a malformed point\n * must be skipped rather than throwing or pushing NaN into the buffer (a NaN vertex poisons the\n * bounding sphere and can break camera fit-to-view for the whole scene).\n */\nfunction buildPoint(item: DisplayPoint, applyTransforms: boolean): THREE.Points | null {\n\t// Validate before trusting the declared type: `position` comes off the wire.\n\tconst { position } = item as { position?: { X?: unknown; Y?: unknown; Z?: unknown } };\n\tif (\n\t\t!position ||\n\t\ttypeof position.X !== 'number' ||\n\t\t!Number.isFinite(position.X) ||\n\t\ttypeof position.Y !== 'number' ||\n\t\t!Number.isFinite(position.Y) ||\n\t\ttypeof position.Z !== 'number' ||\n\t\t!Number.isFinite(position.Z)\n\t) {\n\t\tgetLogger().warn(\n\t\t\t`Skipping point display item with missing or non-finite position (id: ${String(item.id)}).`\n\t\t);\n\t\treturn null;\n\t}\n\n\tconst { x, y, z } = rhinoToThree(position.X, position.Y, position.Z, applyTransforms);\n\n\tconst geometry = new THREE.BufferGeometry();\n\tgeometry.setAttribute('position', new THREE.Float32BufferAttribute([x, y, z], 3));\n\n\tconst material = new THREE.PointsMaterial({\n\t\t...materialParams(item.color, item.opacity),\n\t\tsize: 6,\n\t\tsizeAttenuation: false\n\t});\n\n\tconst points = new THREE.Points(geometry, material);\n\tpoints.name = item.name;\n\tpoints.userData = {\n\t\tsource: 'compute',\n\t\tid: item.id,\n\t\tlayer: item.layer,\n\t\tkind: 'point',\n\t\tmetadata: item.metadata\n\t};\n\treturn points;\n}\n\n/**\n * Free a rhino3dm object's WASM-heap memory. rhino3dm objects are emscripten bindings — JS GC\n * never reclaims their heap allocation, so everything decoded during a solve must be deleted\n * explicitly or the WASM heap grows monotonically across solves.\n */\nfunction deleteRhinoObject(obj: unknown): void {\n\t(obj as { delete?: () => void } | null | undefined)?.delete?.();\n}\n\n/** Decode Rhino CommonObject JSON into a rhino3dm Curve (or null on failure). */\nfunction decodeCurve(json: string, rhino: RhinoModule): InstanceType<RhinoModule['Curve']> | null {\n\ttry {\n\t\tconst parsed = JSON.parse(json);\n\t\tconst obj = rhino.CommonObject.decode(parsed);\n\t\t// decode returns a CommonObject; only curves carry domain/pointAt. Treat anything else as a miss.\n\t\tif (obj && typeof (obj as { pointAt?: unknown }).pointAt === 'function') {\n\t\t\treturn obj as InstanceType<RhinoModule['Curve']>;\n\t\t}\n\t\tdeleteRhinoObject(obj);\n\t\tgetLogger().warn('Decoded display-item JSON is not a curve; skipping.');\n\t\treturn null;\n\t} catch (error) {\n\t\tgetLogger().warn('Failed to decode curve display item JSON:', error);\n\t\treturn null;\n\t}\n}\n\n/**\n * Tessellate a curve to THREE points (passed through the shared — identity — coordinate mapping).\n *\n * Most curves Grasshopper emits are linear — a line is 2 vertices, a polyline is N+1 — yet uniform\n * sampling would inflate every one to {@link CURVE_INITIAL_SEGMENTS}+1 points. So we first ask\n * rhino3dm if the curve *is* a polyline (covers lines, polylines, and degree-1 nurbs/polycurves) and\n * emit its exact vertices when so. Only genuinely curved geometry (arcs, nurbs, polycurves with\n * curved spans) falls through to {@link sampleUniform}.\n */\nfunction tessellate(\n\tcurve: InstanceType<RhinoModule['Curve']>,\n\tapplyTransforms: boolean\n): THREE.Vector3[] {\n\tconst exact = tryPolylineVertices(curve, applyTransforms);\n\tif (exact) return exact;\n\n\treturn sampleUniform(curve, applyTransforms);\n}\n\n/** Minimal shape we use off a rhino3dm Polyline (a Point3dList). */\ninterface PolylineLike {\n\tcount: number;\n\tget(index: number): number[];\n}\n\n/**\n * If the curve has an exact polyline form, return its vertices; otherwise null. `tryGetPolyline`\n * returns `[ok, Polyline]`; the Polyline is a Point3dList (`count` + `get(i) → [x,y,z]`).\n */\nfunction tryPolylineVertices(\n\tcurve: InstanceType<RhinoModule['Curve']>,\n\tapplyTransforms: boolean\n): THREE.Vector3[] | null {\n\tif (!curve.isPolyline()) return null;\n\n\t// rhino3dm's WASM `tryGetPolyline` returns the Polyline directly (not the documented\n\t// `[ok, Polyline]` tuple). Accept either: unwrap a tuple if we got one, else use it as-is.\n\tconst result = curve.tryGetPolyline() as unknown;\n\tconst polyline = (Array.isArray(result) ? result[1] : result) as PolylineLike | null;\n\tif (!polyline || typeof polyline.count !== 'number' || polyline.count < 2) {\n\t\tdeleteRhinoObject(polyline);\n\t\treturn null;\n\t}\n\n\tconst out: THREE.Vector3[] = [];\n\tfor (let i = 0; i < polyline.count; i++) {\n\t\tconst p = polyline.get(i); // [x, y, z] in Rhino Z-up\n\t\tconst { x, y, z } = rhinoToThree(p[0], p[1], p[2], applyTransforms);\n\t\tout.push(new THREE.Vector3(x, y, z));\n\t}\n\n\tdeleteRhinoObject(polyline);\n\treturn out;\n}\n\n/**\n * Adaptively sample a curve across its domain via `pointAt`. Robust for any curved type (arc, nurbs,\n * polycurve). Instead of a fixed segment count, we start from {@link CURVE_INITIAL_SEGMENTS} uniform\n * spans and recursively subdivide each only where it actually bends — a span is split when its\n * parameter-midpoint deviates from the straight chord by more than a tolerance derived from the\n * curve's bounding-box diagonal. Result: smooth on tight bends, sparse on near-straight runs, and\n * scale-independent (a tiny fillet and a huge arc both hit the same *visual* smoothness).\n */\nfunction sampleUniform(\n\tcurve: InstanceType<RhinoModule['Curve']>,\n\tapplyTransforms: boolean\n): THREE.Vector3[] {\n\tconst domain = curve.domain;\n\tconst t0 = domain[0];\n\tconst t1 = domain[1];\n\tconst span = t1 - t0;\n\n\tconst evalAt = (t: number): THREE.Vector3 => {\n\t\tconst p = curve.pointAt(t); // [x, y, z] in Rhino Z-up\n\t\tconst { x, y, z } = rhinoToThree(p[0], p[1], p[2], applyTransforms);\n\t\treturn new THREE.Vector3(x, y, z);\n\t};\n\n\tconst tolerance = chordTolerance(curve);\n\n\t// Evaluate each segment boundary once and carry it forward as the next `pa`,\n\t// instead of re-evaluating ta/tb (3 pointAt calls per segment → 1).\n\tlet ta = t0;\n\tlet pa = evalAt(t0);\n\tconst out: THREE.Vector3[] = [pa];\n\tfor (let i = 0; i < CURVE_INITIAL_SEGMENTS; i++) {\n\t\tconst tb = t0 + (span * (i + 1)) / CURVE_INITIAL_SEGMENTS;\n\t\tconst pb = evalAt(tb);\n\t\tsubdivide(ta, pa, tb, pb, evalAt, tolerance, CURVE_MAX_SUBDIVISION_DEPTH, out);\n\t\tout.push(pb);\n\t\tta = tb;\n\t\tpa = pb;\n\t}\n\n\treturn out;\n}\n\n/**\n * Recursively refine the span [ta, tb]. If the curve point at the parameter-midpoint lies farther\n * than `tolerance` from the chord pa→pb, split and recurse on both halves; otherwise the chord is a\n * good-enough approximation and nothing is added. Pushes interior points (excluding endpoints — the\n * caller owns those) into `out` in parameter order.\n */\nfunction subdivide(\n\tta: number,\n\tpa: THREE.Vector3,\n\ttb: number,\n\tpb: THREE.Vector3,\n\tevalAt: (t: number) => THREE.Vector3,\n\ttolerance: number,\n\tdepth: number,\n\tout: THREE.Vector3[]\n): void {\n\tif (depth <= 0) return;\n\n\tconst tm = (ta + tb) / 2;\n\tconst pm = evalAt(tm);\n\n\t// Subdivide on chord deviation OR on the turn angle at the midpoint. A pure deviation test can\n\t// pass a long, gently-curving span whose endpoints straddle the chord symmetrically; the angle\n\t// test catches the visible kink at span joints that deviation alone misses.\n\tconst deviation = distanceToSegment(pm, pa, pb);\n\tconst turn = turnAngle(pa, pm, pb);\n\tif (deviation <= tolerance && turn <= CURVE_MAX_TURN_RADIANS) return;\n\n\tsubdivide(ta, pa, tm, pm, evalAt, tolerance, depth - 1, out);\n\tout.push(pm);\n\tsubdivide(tm, pm, tb, pb, evalAt, tolerance, depth - 1, out);\n}\n\n/** Tolerance in world units: a fraction of the curve's bounding-box diagonal, with a tiny floor. */\nfunction chordTolerance(curve: InstanceType<RhinoModule['Curve']>): number {\n\t// rhino3dm WASM's getBoundingBox takes no args at runtime despite the .d.ts signature.\n\tconst box = (\n\t\tcurve as unknown as { getBoundingBox(): InstanceType<RhinoModule['BoundingBox']> }\n\t).getBoundingBox();\n\tconst min = box.min;\n\tconst max = box.max;\n\tdeleteRhinoObject(box);\n\tconst diagonal = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]);\n\treturn Math.max(diagonal * CURVE_CHORD_TOLERANCE_RATIO, 1e-6);\n}\n\n/**\n * Angle (radians) of the turn at `b` along the path a→b→c. 0 = straight, π = full reversal.\n *\n * Scalar math on purpose: this runs once per subdivision test inside a recursion that can evaluate\n * ~2^12 spans per curve, so `Vector3.clone()` temporaries here caused measurable GC churn (and\n * module-scope scratch vectors would be unsafe across the recursive calls).\n */\nfunction turnAngle(a: THREE.Vector3, b: THREE.Vector3, c: THREE.Vector3): number {\n\tconst abx = b.x - a.x;\n\tconst aby = b.y - a.y;\n\tconst abz = b.z - a.z;\n\tconst bcx = c.x - b.x;\n\tconst bcy = c.y - b.y;\n\tconst bcz = c.z - b.z;\n\n\tconst lenAb = Math.sqrt(abx * abx + aby * aby + abz * abz);\n\tconst lenBc = Math.sqrt(bcx * bcx + bcy * bcy + bcz * bcz);\n\tif (lenAb === 0 || lenBc === 0) return 0;\n\n\tconst dot = abx * bcx + aby * bcy + abz * bcz;\n\tconst cos = Math.max(-1, Math.min(1, dot / (lenAb * lenBc)));\n\treturn Math.acos(cos);\n}\n\n/**\n * Perpendicular distance from point `p` to the segment a→b (clamped to the segment endpoints).\n * Scalar math for the same allocation-churn reason as {@link turnAngle}.\n */\nfunction distanceToSegment(p: THREE.Vector3, a: THREE.Vector3, b: THREE.Vector3): number {\n\tconst abx = b.x - a.x;\n\tconst aby = b.y - a.y;\n\tconst abz = b.z - a.z;\n\tconst lengthSq = abx * abx + aby * aby + abz * abz;\n\tif (lengthSq === 0) return p.distanceTo(a);\n\n\tconst apx = p.x - a.x;\n\tconst apy = p.y - a.y;\n\tconst apz = p.z - a.z;\n\tconst t = Math.max(0, Math.min(1, (apx * abx + apy * aby + apz * abz) / lengthSq));\n\n\tconst dx = apx - abx * t;\n\tconst dy = apy - aby * t;\n\tconst dz = apz - abz * t;\n\treturn Math.sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n/** Shared color/opacity → THREE material params. Opacity < 1 flips `transparent` on. */\nfunction materialParams(\n\tcolor: string | undefined,\n\topacity: number | undefined\n): { color: THREE.Color; transparent: boolean; opacity: number } {\n\tconst resolved = opacity ?? 1;\n\treturn {\n\t\tcolor: new THREE.Color(color ?? DEFAULT_COLOR),\n\t\ttransparent: resolved < 1,\n\t\topacity: resolved\n\t};\n}\n","/** Rhino and Three use the same Z-up coordinate frame (identity transform). */\n\n/** A point in either frame (the frames are now identical). */\nexport interface Vec3 {\n\tx: number;\n\ty: number;\n\tz: number;\n}\n\n/** Identity transform (both frames Z-up). Deprecated; use coordinates directly. */\nexport function rhinoToThree(x: number, y: number, z: number, _apply = true): Vec3 {\n\treturn { x, y, z };\n}\n","import { inflateSync } from 'fflate';\n\nimport { decodeBase64ToBinary } from '@/core/utils/encoding';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport type { MaterialGroup, SerializableMaterial } from './types.js';\n\n// ============================================================================\n// WIRE FORMAT CONSTANTS\n// ============================================================================\n\n/** \"SLVA\" little-endian — an uncompressed mesh blob. */\nexport const BINARY_MESH_MAGIC = 0x41564c53;\n/**\n * \"SLVZ\" little-endian — a gzip (raw DEFLATE) container around a SLVA blob. The plugin applies this\n * optionally when it shrinks the payload (the wire is otherwise uncompressed). Layout:\n * [4] magic = SLVZ, [4] uncompressedLen (uint32), [N] raw-deflate stream of the SLVA blob.\n */\nexport const COMPRESSED_MESH_MAGIC = 0x5a564c53;\n/**\n * Current writer version. v2 added the uint16-index flag (FLAG_UINT16_INDICES); v3 added the\n * delta+zigzag filter flag (FLAG_DELTA_ENCODED).\n */\nexport const BINARY_MESH_VERSION = 3;\n/**\n * Oldest wire version this parser still decodes. Each version only added a flag bit — v1 always\n * used uint32 indices, v2 introduced uint16 indices, v3 the delta filter — so the flag-driven read\n * path handles every older blob unchanged. Accepting them keeps persisted/cached blobs (saved `.gh`\n * files, DMF files, cached compute results) decodable after upgrade.\n */\nexport const MIN_SUPPORTED_VERSION = 1;\n/** Bit 0 of the geometry flags word: 0 = int16 quantized, 1 = float32 raw. */\nexport const FLAG_FLOAT32 = 0x1;\n/** Bit 1 of the geometry flags word: 0 = uint32 indices, 1 = uint16 indices. */\nexport const FLAG_UINT16_INDICES = 0x2;\n/**\n * Bit 2 of the geometry flags word: int16 vertex components and the index stream are stored as\n * wrapped per-component deltas from their predecessor, zigzag-mapped to unsigned (float32 vertices\n * are never filtered). Deltas of welded meshes concentrate near zero, which makes the SLVZ DEFLATE\n * pass compress far better. Decoding reverses the filter with a running prefix sum.\n */\nexport const FLAG_DELTA_ENCODED = 0x4;\n/**\n * Bit 3 of the geometry flags word: a UV chunk trails the index block. Layout:\n * `uvFormat(u32: 0 = uint16 quantized, 1 = float32) | uvOrigin(2×f64) | uvScale(2×f64) | data`,\n * with the element count implied by vertexCount. Quantized UVs reconstruct as\n * `uv = origin + q * scale` (q unsigned in [0, 65535]) and are delta+zigzag filtered per component\n * (independent u/v predictors) iff FLAG_DELTA_ENCODED; float32 UVs are never filtered. Absent flag\n * = absent chunk, so untextured blobs are byte-identical to pre-chunk writers.\n */\nexport const FLAG_HAS_UVS = 0x8;\n/**\n * Bit 4 of the geometry flags word: a vertex-color chunk trails the index block (after the UV\n * chunk when both are present). Layout: `uint8 rgb[vertexCount*3]`, delta+zigzag filtered per\n * channel (wrapped 8-bit, independent r/g/b predictors) iff FLAG_DELTA_ENCODED.\n */\nexport const FLAG_HAS_VERTEX_COLORS = 0x10;\n\n/** uvFormat value inside the UV chunk: uint16 quantized. */\nexport const UV_FORMAT_UINT16 = 0;\n/** uvFormat value inside the UV chunk: raw float32. */\nexport const UV_FORMAT_FLOAT32 = 1;\n\nconst HEADER_PREAMBLE_BYTES = 4 /* magic */ + 4 /* version */ + 4; /* metadataLen */\nconst GEOMETRY_HEADER_BYTES =\n\t4 /* flags */ + 24 /* origin (3 x f64) */ + 24 /* scale (3 x f64) */ + 4; /* vertexCount */\n\n/**\n * The SLVA wire format is little-endian. Header fields use explicit-LE `DataView` reads, but the\n * zero-copy geometry readers below construct typed-array views in *host* byte order — a deliberate\n * trade: rewriting the hot geometry paths onto per-element DataView reads would cost far more than\n * it buys, since every mainstream JS target (x86, ARM, WASM) is little-endian. This one-time check\n * makes the assumption explicit: on a big-endian host the parser refuses to decode rather than\n * silently returning byte-swapped garbage.\n */\nconst HOST_IS_LITTLE_ENDIAN = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;\n\n// ============================================================================\n// PARSED TYPES\n// ============================================================================\n\n/**\n * Metadata JSON embedded inside the binary blob.\n *\n * This is the mesh-blob subset of a `DisplayBatch` minus the `compressedData` field (the blob is\n * opaque to its own metadata header). Kept separate from the public `DisplayBatch` type because the\n * blob's metadata never carries `compressedData` itself — it would be circular.\n */\nexport interface BinaryMeshMetadata {\n\tmaterials: SerializableMaterial[];\n\tgroups: MaterialGroup[];\n\tsourceComponentId?: string;\n}\n\n/**\n * Result of parsing a binary mesh blob.\n *\n * `vertices` and `indices` hold absolute (unfiltered) values. For pre-v3 blobs they are typed-array\n * views over the original `ArrayBuffer` — zero copies; the consumer is responsible for not mutating\n * the underlying buffer if it cares about safety, or for calling `.slice()` to detach. Delta-encoded\n * blobs (FLAG_DELTA_ENCODED) decode into freshly allocated arrays instead.\n *\n * `uvs` / `colors` are the optional trailing chunks (FLAG_HAS_UVS / FLAG_HAS_VERTEX_COLORS), null\n * when the blob doesn't carry them. UVs are returned dequantized to absolute Float32 values (u,v\n * per vertex), so consumers can hand them straight to a `BufferAttribute(uvs, 2)`. Colors are raw\n * r,g,b bytes per vertex for a normalized `BufferAttribute(colors, 3, true)`.\n */\nexport interface ParsedBinaryMeshBatch {\n\tmetadata: BinaryMeshMetadata;\n\tflags: number;\n\tvertices: Int16Array | Float32Array;\n\tindices: Uint16Array | Uint32Array;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\n\tuvs: Float32Array | null;\n\tcolors: Uint8Array | null;\n}\n\n// ============================================================================\n// PARSER\n// ============================================================================\n\n/**\n * Parses a binary mesh batch blob in the SLVA wire format.\n *\n * The blob layout is:\n * ```\n * [4] magic = \"SLVA\" (0x53 0x4C 0x56 0x41)\n * [4] version = uint32 (currently 3)\n * [4] metadataLen = uint32 byte length of UTF-8 metadata JSON\n * [N] metadata = UTF-8 JSON (materials, groups, sourceComponentId, ...)\n * [4] flags = uint32 (bit 0: 0 = int16 quantized, 1 = float32 raw;\n * bit 1: 0 = uint32 indices, 1 = uint16 indices;\n * bit 2: 1 = delta+zigzag filtered)\n * [24] origin = 3 x float64\n * [24] scale = 3 x float64 (step per int16 unit; identity for float32)\n * [4] vertexCount = uint32 number of vertices (positions = vertexCount * 3 components)\n * [V] vertices = int16[vertexCount*3] OR float32[vertexCount*3]\n * [4] indexCount = uint32 number of indices\n * [I] indices = uint32[indexCount] OR uint16[indexCount]\n * ```\n *\n * For int16 vertices: world position = `origin + (q + 32767) * scale`. This matches Three.js\n * `BufferAttribute(arr, 3, true)` (`normalized: true`) semantics when the per-mesh transform\n * encodes `origin + scale`.\n *\n * For float32: `origin = (0, 0, 0)`, `scale = (1, 1, 1)`, vertices are raw world positions.\n *\n * With FLAG_DELTA_ENCODED (v3), the stored int16 vertex components and indices are wrapped\n * differences from their predecessor, zigzag-mapped — see the flag's doc. The parser returns the\n * reconstructed absolute values, so consumers never see the filter.\n *\n * @param input - The blob, as either an `ArrayBuffer`/`Uint8Array` (binary transport) or a\n * base64-encoded string (today's JSON-envelope transport).\n * @returns Decoded metadata plus typed-array views into the geometry payload.\n * @throws {RhinoComputeError} On invalid magic, unknown version, or truncated input.\n */\nexport function parseBinaryMeshBatch(\n\tinput: ArrayBuffer | Uint8Array | string\n): ParsedBinaryMeshBatch {\n\tconst raw = parseBinaryMeshBatchRaw(input);\n\n\tlet vertices: Int16Array | Float32Array;\n\tif (raw.isFloat32) {\n\t\tvertices = raw.vertexData as Float32Array;\n\t} else if (raw.deltaEncoded) {\n\t\tvertices = decodeDeltaVertices(raw.vertexData as Uint16Array);\n\t} else {\n\t\tvertices = raw.vertexData as Int16Array;\n\t}\n\n\tlet indices = raw.indexData;\n\tif (raw.deltaEncoded) {\n\t\tindices =\n\t\t\tindices instanceof Uint16Array\n\t\t\t\t? decodeDeltaIndices16(indices)\n\t\t\t\t: decodeDeltaIndices32(indices);\n\t}\n\tvalidateIndicesInRange(indices, raw.vertexCount);\n\n\treturn {\n\t\tmetadata: raw.metadata,\n\t\tflags: raw.flags,\n\t\tvertices,\n\t\tindices,\n\t\torigin: raw.origin,\n\t\tscale: raw.scale,\n\t\tuvs: raw.uvs,\n\t\tcolors: raw.colors\n\t};\n}\n\n/**\n * Raw wire-value view of a blob: geometry arrays are exactly as stored — zigzag-mapped deltas when\n * the blob carries the delta filter — while metadata, UVs, and colors are fully decoded (they're\n * small). For consumers that hand the heavy decoding to a worker (`mesh-assembly.ts`); everyone\n * else wants {@link parseBinaryMeshBatch}, which returns reconstructed absolute values.\n */\nexport interface RawBinaryMeshBatch {\n\tmetadata: BinaryMeshMetadata;\n\tflags: number;\n\t/** Wire vertex components: zigzag deltas (Uint16) when `deltaEncoded` and not float32. */\n\tvertexData: Uint16Array | Int16Array | Float32Array;\n\t/** Wire indices: zigzag deltas when `deltaEncoded`. NOT validated against vertexCount. */\n\tindexData: Uint16Array | Uint32Array;\n\tisFloat32: boolean;\n\tdeltaEncoded: boolean;\n\tvertexCount: number;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\n\tuvs: Float32Array | null;\n\tcolors: Uint8Array | null;\n}\n\n/** See {@link RawBinaryMeshBatch}. Same validation/throw behavior as the decoding parser. */\nexport function parseBinaryMeshBatchRaw(\n\tinput: ArrayBuffer | Uint8Array | string\n): RawBinaryMeshBatch {\n\tif (!HOST_IS_LITTLE_ENDIAN) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.',\n\t\t\tErrorCodes.ENVIRONMENT_ERROR\n\t\t);\n\t}\n\n\tconst bytes = maybeDecompress(toUint8Array(input));\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\n\tif (bytes.byteLength < HEADER_PREAMBLE_BYTES) {\n\t\tthrow fail('Blob too small to contain SLVA header.', {\n\t\t\texpectedBytes: HEADER_PREAMBLE_BYTES,\n\t\t\tavailableBytes: bytes.byteLength\n\t\t});\n\t}\n\n\tlet offset = 0;\n\n\tconst magic = view.getUint32(offset, true);\n\toffset += 4;\n\tif (magic !== BINARY_MESH_MAGIC) {\n\t\tthrow fail(`Invalid SLVA magic: 0x${magic.toString(16)}`, {\n\t\t\texpectedMagic: `0x${BINARY_MESH_MAGIC.toString(16)}`,\n\t\t\tactualMagic: `0x${magic.toString(16)}`\n\t\t});\n\t}\n\n\tconst version = view.getUint32(offset, true);\n\toffset += 4;\n\tif (version < MIN_SUPPORTED_VERSION || version > BINARY_MESH_VERSION) {\n\t\tthrow fail(`Unsupported SLVA version: ${version}`, {\n\t\t\tminSupportedVersion: MIN_SUPPORTED_VERSION,\n\t\t\tmaxSupportedVersion: BINARY_MESH_VERSION,\n\t\t\tactualVersion: version\n\t\t});\n\t}\n\n\tconst metadataLen = view.getUint32(offset, true);\n\toffset += 4;\n\tif (offset + metadataLen > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read metadata JSON.', {\n\t\t\texpectedBytes: metadataLen,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst metadataBytes = bytes.subarray(offset, offset + metadataLen);\n\toffset += metadataLen;\n\n\tlet metadata: BinaryMeshMetadata;\n\ttry {\n\t\tmetadata = JSON.parse(decodeUtf8(metadataBytes)) as BinaryMeshMetadata;\n\t} catch (error) {\n\t\tthrow fail(\n\t\t\t`Failed to parse metadata JSON: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ metadataLen }\n\t\t);\n\t}\n\n\tif (offset + GEOMETRY_HEADER_BYTES > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read geometry header.', {\n\t\t\texpectedBytes: GEOMETRY_HEADER_BYTES,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst flags = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst originX = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originY = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originZ = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst scaleX = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleY = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleZ = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst vertexCount = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst useFloat32 = (flags & FLAG_FLOAT32) !== 0;\n\tconst deltaEncoded = (flags & FLAG_DELTA_ENCODED) !== 0;\n\tconst componentCount = vertexCount * 3;\n\tconst bytesPerComponent = useFloat32 ? 4 : 2;\n\tconst verticesByteLength = componentCount * bytesPerComponent;\n\n\tif (offset + verticesByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read vertices.', {\n\t\t\texpectedBytes: verticesByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tuseFloat32,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\t// Typed-array views require alignment to the element size. The header lays out the geometry\n\t// block such that the vertex byte offset is always 4-aligned (preamble 12 + metadataLen + 4 +\n\t// 48 + 4). float32 needs 4-byte alignment (satisfied), int16 needs 2-byte alignment\n\t// (satisfied). We can take a zero-copy view as long as `bytes.byteOffset + offset` agrees with\n\t// that alignment in the underlying buffer — a wrapper Uint8Array could violate it. Fall back\n\t// to a fresh copy if so.\n\tconst absoluteOffset = bytes.byteOffset + offset;\n\tlet vertexData: Uint16Array | Int16Array | Float32Array;\n\tif (useFloat32) {\n\t\tvertexData = readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount);\n\t} else if (deltaEncoded) {\n\t\t// Left as raw zigzag deltas — parseBinaryMeshBatch (or the assembly worker) prefix-sums them.\n\t\tvertexData = readUint16Array(bytes.buffer, absoluteOffset, componentCount);\n\t} else {\n\t\tvertexData = readInt16Vertices(bytes.buffer, absoluteOffset, componentCount);\n\t}\n\toffset += verticesByteLength;\n\n\tif (offset + 4 > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read index count.', {\n\t\t\texpectedBytes: 4,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\tconst indexCount = view.getUint32(offset, true);\n\toffset += 4;\n\n\tconst useUint16Indices = (flags & FLAG_UINT16_INDICES) !== 0;\n\tconst bytesPerIndex = useUint16Indices ? 2 : 4;\n\tconst indicesByteLength = indexCount * bytesPerIndex;\n\tif (offset + indicesByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read indices.', {\n\t\t\texpectedBytes: indicesByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tindexCount,\n\t\t\tuseUint16Indices\n\t\t});\n\t}\n\n\tconst indexData = useUint16Indices\n\t\t? readUint16Array(bytes.buffer, bytes.byteOffset + offset, indexCount)\n\t\t: readUint32Array(bytes.buffer, bytes.byteOffset + offset, indexCount);\n\toffset += indicesByteLength;\n\n\t// Optional trailing chunks (UV first, then colors). Blobs from pre-chunk writers simply end\n\t// here; the flags gate every read, so nothing is consumed when the chunks are absent.\n\tlet uvs: Float32Array | null = null;\n\tif ((flags & FLAG_HAS_UVS) !== 0) {\n\t\tconst parsed = parseUvChunk(bytes, view, offset, vertexCount, deltaEncoded);\n\t\tuvs = parsed.uvs;\n\t\toffset = parsed.offset;\n\t}\n\n\tlet colors: Uint8Array | null = null;\n\tif ((flags & FLAG_HAS_VERTEX_COLORS) !== 0) {\n\t\tcolors = parseColorChunk(bytes, offset, vertexCount, deltaEncoded);\n\t}\n\n\treturn {\n\t\tmetadata,\n\t\tflags,\n\t\tvertexData,\n\t\tindexData,\n\t\tisFloat32: useFloat32,\n\t\tdeltaEncoded,\n\t\tvertexCount,\n\t\torigin: [originX, originY, originZ],\n\t\tscale: [scaleX, scaleY, scaleZ],\n\t\tuvs,\n\t\tcolors\n\t};\n}\n\n/** Byte size of the UV chunk header: uvFormat(u32) + uvOrigin(2×f64) + uvScale(2×f64). */\nconst UV_CHUNK_HEADER_BYTES = 4 + 16 + 16;\n\n/**\n * Parses the trailing UV chunk into absolute Float32 u,v pairs. Quantized UVs reconstruct as\n * `origin + q * scale` with an unsigned q, undoing the per-component delta+zigzag filter when the\n * blob-wide delta flag is set; float32 UVs are copied out as-is (never filtered).\n */\nfunction parseUvChunk(\n\tbytes: Uint8Array,\n\tview: DataView,\n\toffset: number,\n\tvertexCount: number,\n\tdeltaEncoded: boolean\n): { uvs: Float32Array; offset: number } {\n\tif (offset + UV_CHUNK_HEADER_BYTES > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read UV chunk header.', {\n\t\t\texpectedBytes: UV_CHUNK_HEADER_BYTES,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset\n\t\t});\n\t}\n\n\tconst uvFormat = view.getUint32(offset, true);\n\toffset += 4;\n\tconst originU = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst originV = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleU = view.getFloat64(offset, true);\n\toffset += 8;\n\tconst scaleV = view.getFloat64(offset, true);\n\toffset += 8;\n\n\tconst componentCount = vertexCount * 2;\n\tconst useFloat32 = uvFormat === UV_FORMAT_FLOAT32;\n\tconst dataByteLength = componentCount * (useFloat32 ? 4 : 2);\n\tif (offset + dataByteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read UV chunk.', {\n\t\t\texpectedBytes: dataByteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tuvFormat,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\tconst absoluteOffset = bytes.byteOffset + offset;\n\tlet uvs: Float32Array;\n\tif (useFloat32) {\n\t\t// Copy (not view) so the attribute owns its memory like the quantized path.\n\t\tuvs = readFloat32Vertices(bytes.buffer, absoluteOffset, componentCount).slice();\n\t} else {\n\t\tconst raw = readUint16Array(bytes.buffer, absoluteOffset, componentCount);\n\t\tuvs = new Float32Array(componentCount);\n\t\tlet qu = 0;\n\t\tlet qv = 0;\n\t\tfor (let i = 0; i < componentCount; i += 2) {\n\t\t\tif (deltaEncoded) {\n\t\t\t\tqu = (qu + unzigzag(raw[i]!)) & 0xffff;\n\t\t\t\tqv = (qv + unzigzag(raw[i + 1]!)) & 0xffff;\n\t\t\t} else {\n\t\t\t\tqu = raw[i]!;\n\t\t\t\tqv = raw[i + 1]!;\n\t\t\t}\n\t\t\tuvs[i] = originU + qu * scaleU;\n\t\t\tuvs[i + 1] = originV + qv * scaleV;\n\t\t}\n\t}\n\n\treturn { uvs, offset: offset + dataByteLength };\n}\n\n/**\n * Parses the trailing vertex-color chunk into raw r,g,b bytes, undoing the per-channel wrapped\n * 8-bit delta+zigzag filter when the blob-wide delta flag is set.\n */\nfunction parseColorChunk(\n\tbytes: Uint8Array,\n\toffset: number,\n\tvertexCount: number,\n\tdeltaEncoded: boolean\n): Uint8Array {\n\tconst byteLength = vertexCount * 3;\n\tif (offset + byteLength > bytes.byteLength) {\n\t\tthrow fail('Insufficient data to read vertex-color chunk.', {\n\t\t\texpectedBytes: byteLength,\n\t\t\tavailableBytes: bytes.byteLength - offset,\n\t\t\toffset,\n\t\t\tvertexCount\n\t\t});\n\t}\n\n\tconst raw = bytes.subarray(offset, offset + byteLength);\n\tif (!deltaEncoded) {\n\t\treturn raw.slice();\n\t}\n\n\tconst colors = new Uint8Array(byteLength);\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tfor (let i = 0; i < byteLength; i += 3) {\n\t\tr = (r + unzigzag(raw[i]!)) & 0xff;\n\t\tg = (g + unzigzag(raw[i + 1]!)) & 0xff;\n\t\tb = (b + unzigzag(raw[i + 2]!)) & 0xff;\n\t\tcolors[i] = r;\n\t\tcolors[i + 1] = g;\n\t\tcolors[i + 2] = b;\n\t}\n\treturn colors;\n}\n\n// ============================================================================\n// HELPERS\n// ============================================================================\n\nfunction toUint8Array(input: ArrayBuffer | Uint8Array | string): Uint8Array {\n\tif (typeof input === 'string') {\n\t\treturn decodeBase64ToBinary(input);\n\t}\n\tif (input instanceof Uint8Array) {\n\t\treturn input;\n\t}\n\treturn new Uint8Array(input);\n}\n\n/**\n * If the blob is a SLVZ compressed container, inflate it back to the raw SLVA bytes; otherwise\n * return the input untouched. Detection is by the leading 4-byte magic, so an uncompressed SLVA\n * blob (or any pre-v3 payload) flows through unchanged.\n */\nfunction maybeDecompress(bytes: Uint8Array): Uint8Array {\n\tif (bytes.byteLength < 8) {\n\t\treturn bytes;\n\t}\n\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\tif (view.getUint32(0, true) !== COMPRESSED_MESH_MAGIC) {\n\t\treturn bytes;\n\t}\n\n\tconst uncompressedLen = view.getUint32(4, true);\n\tconst deflated = bytes.subarray(8);\n\n\t// Bound the wire-supplied length before allocating — a corrupt header could\n\t// otherwise request ~4 GB. DEFLATE won't expand past ~1000×.\n\tconst maxPlausibleLen = Math.max(deflated.byteLength * 1032 + 1024, 1 << 20);\n\tif (uncompressedLen > maxPlausibleLen) {\n\t\tthrow fail('SLVZ header declares an implausible uncompressed length', {\n\t\t\tuncompressedLen,\n\t\t\tdeflatedBytes: deflated.byteLength,\n\t\t\tmaxPlausibleLen\n\t\t});\n\t}\n\n\tlet out: Uint8Array;\n\ttry {\n\t\t// One byte of slack past the declared length: fflate returns a subarray trimmed to the byte\n\t\t// count actually written, so an understating header (stream longer than declared) lands on\n\t\t// length uncompressedLen + 1 and an overstating one (stream shorter) below uncompressedLen —\n\t\t// either way the check below catches the mismatch instead of a zero-padded/truncated tail\n\t\t// silently decoding as geometry.\n\t\tout = inflateSync(deflated, { out: new Uint8Array(uncompressedLen + 1) });\n\t} catch (error) {\n\t\tthrow fail(\n\t\t\t`Failed to inflate SLVZ blob: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ uncompressedLen, deflatedBytes: deflated.byteLength }\n\t\t);\n\t}\n\n\tif (out.byteLength !== uncompressedLen) {\n\t\tthrow fail('SLVZ payload inflated to a different size than the header declares.', {\n\t\t\tdeclaredLen: uncompressedLen,\n\t\t\tactualLen: out.byteLength,\n\t\t\tdeflatedBytes: deflated.byteLength\n\t\t});\n\t}\n\n\treturn out;\n}\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n\tif (typeof TextDecoder !== 'undefined') {\n\t\treturn new TextDecoder('utf-8').decode(bytes);\n\t}\n\t// Node fallback (Buffer is utf-8 by default).\n\tif (\n\t\ttypeof (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n\t\t\t.Buffer !== 'undefined'\n\t) {\n\t\treturn (\n\t\t\tglobalThis as { Buffer: { from(b: Uint8Array): { toString(enc: string): string } } }\n\t\t).Buffer.from(bytes).toString('utf-8');\n\t}\n\tthrow new RhinoComputeError(\n\t\t'No UTF-8 decoder available in this environment.',\n\t\tErrorCodes.INVALID_STATE\n\t);\n}\n\nfunction readInt16Vertices(buffer: ArrayBufferLike, byteOffset: number, count: number): Int16Array {\n\tif (count === 0) return new Int16Array(0);\n\tif (byteOffset % 2 === 0) {\n\t\treturn new Int16Array(buffer, byteOffset, count);\n\t}\n\t// Misaligned (rare — would require a wrapper Uint8Array with odd byteOffset).\n\tconst copy = new Uint8Array(count * 2);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 2));\n\treturn new Int16Array(copy.buffer);\n}\n\nfunction readFloat32Vertices(\n\tbuffer: ArrayBufferLike,\n\tbyteOffset: number,\n\tcount: number\n): Float32Array {\n\tif (count === 0) return new Float32Array(0);\n\tif (byteOffset % 4 === 0) {\n\t\treturn new Float32Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 4);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 4));\n\treturn new Float32Array(copy.buffer);\n}\n\nfunction readUint16Array(buffer: ArrayBufferLike, byteOffset: number, count: number): Uint16Array {\n\tif (count === 0) return new Uint16Array(0);\n\tif (byteOffset % 2 === 0) {\n\t\treturn new Uint16Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 2);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 2));\n\treturn new Uint16Array(copy.buffer);\n}\n\nfunction readUint32Array(buffer: ArrayBufferLike, byteOffset: number, count: number): Uint32Array {\n\tif (count === 0) return new Uint32Array(0);\n\tif (byteOffset % 4 === 0) {\n\t\treturn new Uint32Array(buffer, byteOffset, count);\n\t}\n\tconst copy = new Uint8Array(count * 4);\n\tcopy.set(new Uint8Array(buffer, byteOffset, count * 4));\n\treturn new Uint32Array(copy.buffer);\n}\n\n/**\n * Rejects blobs whose index stream references vertices past `vertexCount`. Downstream mesh\n * assembly trusts indices arithmetically (rebasing, `subarray` slicing), so an out-of-range index\n * would otherwise corrupt geometry silently instead of failing the parse. A uint16 index stream\n * can't exceed a vertex count above 65535, so that case skips the scan.\n */\nfunction validateIndicesInRange(indices: Uint16Array | Uint32Array, vertexCount: number): void {\n\tif (indices.length === 0) return;\n\tif (indices instanceof Uint16Array && vertexCount > 0xffff) return;\n\tfor (let i = 0; i < indices.length; i++) {\n\t\tif (indices[i]! >= vertexCount) {\n\t\t\tthrow fail('Index out of range of vertexCount.', {\n\t\t\t\tindexPosition: i,\n\t\t\t\tindexValue: indices[i],\n\t\t\t\tvertexCount\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Inverse of the writer's zigzag map: 0,1,2,3 → 0,-1,1,-2. */\nfunction unzigzag(zz: number): number {\n\treturn (zz >>> 1) ^ -(zz & 1);\n}\n\n/**\n * Undoes the v3 delta filter on the quantized vertex stream: each component is a zigzag-mapped,\n * wrapped 16-bit difference from the previous vertex's same component (independent x/y/z running\n * sums). `(x << 16) >> 16` reproduces the writer's int16 wrapping.\n */\nfunction decodeDeltaVertices(zigzagged: Uint16Array): Int16Array {\n\tconst out = new Int16Array(zigzagged.length);\n\tlet px = 0;\n\tlet py = 0;\n\tlet pz = 0;\n\tfor (let i = 0; i < zigzagged.length; i += 3) {\n\t\tpx = ((px + unzigzag(zigzagged[i]!)) << 16) >> 16;\n\t\tpy = ((py + unzigzag(zigzagged[i + 1]!)) << 16) >> 16;\n\t\tpz = ((pz + unzigzag(zigzagged[i + 2]!)) << 16) >> 16;\n\t\tout[i] = px;\n\t\tout[i + 1] = py;\n\t\tout[i + 2] = pz;\n\t}\n\treturn out;\n}\n\nfunction decodeDeltaIndices16(zigzagged: Uint16Array): Uint16Array {\n\tconst out = new Uint16Array(zigzagged.length);\n\tlet prev = 0;\n\tfor (let i = 0; i < zigzagged.length; i++) {\n\t\tprev = (prev + unzigzag(zigzagged[i]!)) & 0xffff;\n\t\tout[i] = prev;\n\t}\n\treturn out;\n}\n\nfunction decodeDeltaIndices32(zigzagged: Uint32Array): Uint32Array {\n\tconst out = new Uint32Array(zigzagged.length);\n\tlet prev = 0;\n\tfor (let i = 0; i < zigzagged.length; i++) {\n\t\tprev = (prev + unzigzag(zigzagged[i]!)) >>> 0;\n\t\tout[i] = prev;\n\t}\n\treturn out;\n}\n\nfunction fail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\n}\n","import * as THREE from 'three';\n\nimport { parseColor } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch, parseBinaryMeshBatchRaw } from './binary-parser.js';\nimport { fingerprintViews, geometryCacheGet, geometryCachePut } from './geometry-cache.js';\nimport { meshAssemblyWorkerSource } from './mesh-assembly.js';\nimport { applyTextureMap } from './texture-cache.js';\n\nimport type { AssembledGeometry, AssemblyJob, AssemblyWindow } from './mesh-assembly.js';\n\nimport type { ParsedBinaryMeshBatch } from './binary-parser.js';\nimport type {\n\tDisplayBatch,\n\tMaterialAppearanceOptions,\n\tMaterialGroup,\n\tMeshBatchParsingOptions,\n\tMeshMetadata,\n\tSerializableMaterial\n} from './types.js';\n\n/** Internal telemetry only (not exposed in public options). */\ninterface ParseTelemetry {\n\tparseTime?: number;\n\tperfStart?: number;\n}\n\n/**\n * Parses a batched mesh JSON and creates Three.js meshes.\n *\n * The geometry payload is the binary \"SLVA\" blob produced by the C# `BinaryGeometryWriter`,\n * base64-encoded into the outer JSON envelope. We `JSON.parse` the small envelope, then hand the\n * blob to `parseBinaryMeshBatch` which decodes the geometry without ever turning it into a string.\n *\n * An invalid JSON envelope (not a batch at all) logs and returns `[]` — that is the\n * \"genuinely absent data\" case. A batch whose *blob* is corrupt, truncated, or unsupported throws\n * instead of silently rendering an empty scene.\n *\n * @param batchJson - JSON string containing the batched mesh data\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatch(\n\tbatchJson: string,\n\toptions?: MeshBatchParsingOptions\n): Promise<THREE.Mesh[]> {\n\tconst { debug = false } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\t// Narrow catch: only the envelope JSON.parse is allowed to degrade to []. Blob parse errors\n\t// from parseMeshBatchObject propagate — see that entry point's contract.\n\tlet batch: DisplayBatch;\n\tconst parseStart = performance.now();\n\ttry {\n\t\tbatch = JSON.parse(batchJson);\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch envelope JSON:', error);\n\t\treturn [];\n\t}\n\tconst parseTime = performance.now() - parseStart;\n\n\treturn await parseMeshBatchObject(batch, options, { parseTime, perfStart });\n}\n\n/**\n * Parses a DisplayBatch object and creates Three.js meshes from its mesh blob.\n *\n * The path is synchronous internally — `parseBinaryMeshBatch` does no IO, just typed-array views\n * over the blob. The function stays `async` so callers don't have to change shape if we move\n * parsing into a worker later.\n *\n * A batch with no `compressedData` (genuinely empty/absent geometry) resolves to `[]`. A corrupt,\n * truncated, or unsupported blob throws so callers get a signal instead of a silent empty scene —\n * `getThreeMeshesFromComputeResponse` documents (and now delivers) exactly that rethrow.\n *\n * @param batch - DisplayBatch object\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatchObject(\n\tbatch: DisplayBatch,\n\toptions?: MeshBatchParsingOptions,\n\t/** @internal Timings threaded from an outer entry point; not a caller option. */\n\ttelemetry?: ParseTelemetry\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false, material } = options ?? {};\n\tconst { parseTime = 0, perfStart = debug ? performance.now() : 0 } = telemetry ?? {};\n\n\tif (!batch.compressedData) {\n\t\t// No blob at all — an items-only or empty batch. This is the one entry-point path that\n\t\t// legitimately yields [] rather than throwing.\n\t\treturn [];\n\t}\n\n\t// Off-thread path (audit P2): heavy batches decode+assemble in a worker; null → do it here.\n\tconst workerMeshes = await tryBuildViaWorker(batch.compressedData, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tfallback: {\n\t\t\tmaterials: batch.materials,\n\t\t\tgroups: batch.groups,\n\t\t\tsourceComponentId: batch.sourceComponentId\n\t\t}\n\t});\n\tif (workerMeshes) return workerMeshes;\n\n\tconst decodeStart = performance.now();\n\tconst parsed = parseBinaryMeshBatch(batch.compressedData);\n\tconst decodeTime = performance.now() - decodeStart;\n\n\tconst blobBytes = debug ? approximateBase64DecodedBytes(batch.compressedData) : 0;\n\n\treturn buildMeshesFromParsed(parsed, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback: {\n\t\t\tmaterials: batch.materials,\n\t\t\tgroups: batch.groups,\n\t\t\tsourceComponentId: batch.sourceComponentId\n\t\t}\n\t});\n}\n\n/**\n * Parses a raw binary mesh batch blob (SLVA wire format) and creates Three.js meshes.\n *\n * Use this entry point when the blob arrives as a binary WebSocket frame (Phase 1b transport):\n * the JSON envelope no longer carries `displayData`, so there's nothing to `JSON.parse`. The blob\n * is self-describing — materials, groups, and `sourceComponentId` come from its embedded metadata\n * header.\n *\n * @param blob - Raw blob bytes from a binary WebSocket frame.\n * @param options - Rendering options.\n * @returns Promise resolving to array of Three.js mesh objects.\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatchBlob(\n\tblob: ArrayBuffer | Uint8Array,\n\toptions?: MeshBatchParsingOptions\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false, material } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\t// Off-thread path (audit P2): heavy batches decode+assemble in a worker; null → do it here.\n\tconst workerMeshes = await tryBuildViaWorker(blob, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial\n\t});\n\tif (workerMeshes) return workerMeshes;\n\n\tconst decodeStart = performance.now();\n\tconst parsed = parseBinaryMeshBatch(blob);\n\tconst decodeTime = performance.now() - decodeStart;\n\n\tconst blobBytes = blob.byteLength;\n\n\treturn buildMeshesFromParsed(parsed, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tparseTime: 0,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes\n\t});\n}\n\ninterface BuildOptions {\n\tmergeByMaterial: boolean;\n\tapplyTransforms: boolean;\n\tdebug: boolean;\n\tmaterial?: MaterialAppearanceOptions;\n\tparseTime: number;\n\tdecodeTime: number;\n\tperfStart: number;\n\tblobBytes: number;\n\t/** Outer-envelope fallback when the blob's metadata is missing fields (defensive). */\n\tfallback?: {\n\t\tmaterials?: SerializableMaterial[];\n\t\tgroups?: MaterialGroup[];\n\t\tsourceComponentId?: string;\n\t};\n}\n\nfunction buildMeshesFromParsed(\n\tparsed: ParsedBinaryMeshBatch,\n\topts: BuildOptions\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial: materialAppearance,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback\n\t} = opts;\n\n\tconst materialsSrc = parsed.metadata.materials ?? fallback?.materials ?? [];\n\tconst groups = parsed.metadata.groups ?? fallback?.groups ?? [];\n\t// Prefer the outer envelope's sourceComponentId over the blob's embedded one. The blob bakes in\n\t// the id at encode time, but a reloaded part (e.g. from a .dmf instanced many times) re-stamps a\n\t// fresh id on the envelope to keep web pick identity distinct per placement. The blob value is\n\t// the fallback for the raw-blob transport, which has no envelope.\n\tconst sourceComponentId = fallback?.sourceComponentId ?? parsed.metadata.sourceComponentId;\n\n\tconst isFloat32 = (parsed.flags & FLAG_FLOAT32) !== 0;\n\n\t// Group metadata arrives as embedded (or envelope) JSON and is used arithmetically below —\n\t// unchecked, a bad vertexStart/indexStart wraps rebased indices into a Uint32Array, `subarray`\n\t// silently clamps, and an out-of-range materialId feeds `undefined` into `new THREE.Mesh`.\n\t// Fail the parse instead of silently corrupting the render.\n\tvalidateGroupMetadata(\n\t\tgroups,\n\t\tmaterialsSrc.length,\n\t\tparsed.vertices.length / 3,\n\t\tparsed.indices.length\n\t);\n\n\t// Dequantize once up-front into a single Float32Array. Downstream code (per-group merging,\n\t// computeVertexNormals, ground-offset) all expect world-unit floats, and a single\n\t// linear pass over the int16 buffer is far cheaper than the legacy gunzip + base64 path.\n\t// No rotation happens here: the scene uses Rhino's Z-up frame, so vertices pass through in the\n\t// frame they arrived in (see ../coordinate-transform.ts). `applyTransforms` is inert.\n\tconst worldVertices = isFloat32\n\t\t? maybeRotateFloat32Vertices(parsed.vertices as Float32Array, applyTransforms)\n\t\t: dequantizeInt16(parsed.vertices as Int16Array, parsed.origin, parsed.scale, applyTransforms);\n\n\tif (debug) {\n\t\tconst wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;\n\t\tgetLogger().debug('Mesh Batch Stats:');\n\t\tgetLogger().debug(` Materials: ${materialsSrc.length} | Groups: ${groups.length}`);\n\t\tgetLogger().debug(\n\t\t\t` Vertices: ${parsed.vertices.length / 3} | Indices: ${parsed.indices.length}`\n\t\t);\n\t\tgetLogger().debug(` Format: ${isFloat32 ? 'float32' : 'int16 quantized'}`);\n\t\tgetLogger().debug(\n\t\t\t` Blob: ${(blobBytes / 1024 / 1024).toFixed(2)} MB | Geometry on wire: ${(wireBytes / 1024 / 1024).toFixed(2)} MB`\n\t\t);\n\t}\n\n\tconst meshCreateStart = performance.now();\n\t// Vertex colors are batch-wide when present (meshes without real colors carry a white fill,\n\t// which multiplies to identity), so the material can enable vertexColors unconditionally.\n\tconst materials = materialsSrc.map((m) =>\n\t\tcreateMaterial(m, {\n\t\t\tvertexColors: parsed.colors != null,\n\t\t\tappearance: materialAppearance\n\t\t})\n\t);\n\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const group of groups) {\n\t\tif (mergeByMaterial && group.meshes.length > 1) {\n\t\t\tconst mergedMesh = createMergedMesh(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials,\n\t\t\t\tparsed.uvs,\n\t\t\t\tparsed.colors\n\t\t\t);\n\t\t\tmergedMesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\tmeshes.push(mergedMesh);\n\t\t} else {\n\t\t\tconst individualMeshes = createIndividualMeshes(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials,\n\t\t\t\tparsed.uvs,\n\t\t\t\tparsed.colors\n\t\t\t);\n\t\t\tfor (const mesh of individualMeshes) {\n\t\t\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t}\n\t\t\tmeshes.push(...individualMeshes);\n\t\t}\n\t}\n\n\tconst meshCreateTime = performance.now() - meshCreateStart;\n\n\tif (debug) {\n\t\tconst totalTime = performance.now() - perfStart;\n\t\tgetLogger().debug('Performance:');\n\t\tif (parseTime > 0) getLogger().debug(` Parse JSON: ${parseTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Decode binary: ${decodeTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Create Meshes: ${meshCreateTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Total: ${totalTime.toFixed(2)}ms`);\n\t}\n\n\treturn Promise.resolve(meshes);\n}\n\nfunction metadataFail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\n}\n\n/**\n * Validates the batch's group/mesh metadata against the decoded geometry buffers before any of it\n * is used arithmetically. Throws a VALIDATION_ERROR on the first inconsistency (out-of-range\n * `materialId`, non-integer or negative offsets/counts, or vertex/index windows that overrun the\n * buffers) so malformed or version-skewed metadata fails the parse loudly.\n */\nfunction validateGroupMetadata(\n\tgroups: MaterialGroup[],\n\tmaterialCount: number,\n\ttotalVertexCount: number,\n\ttotalIndexCount: number\n): void {\n\tfor (const group of groups) {\n\t\tif (\n\t\t\t!Number.isInteger(group.materialId) ||\n\t\t\tgroup.materialId < 0 ||\n\t\t\tgroup.materialId >= materialCount\n\t\t) {\n\t\t\tthrow metadataFail('Group materialId out of range of the materials array.', {\n\t\t\t\tmaterialId: group.materialId,\n\t\t\t\tmaterialCount\n\t\t\t});\n\t\t}\n\n\t\tfor (const mesh of group.meshes) {\n\t\t\tconst fields = {\n\t\t\t\tvertexStart: mesh.vertexStart,\n\t\t\t\tvertexCount: mesh.vertexCount,\n\t\t\t\tindexStart: mesh.indexStart,\n\t\t\t\tindexCount: mesh.indexCount\n\t\t\t};\n\t\t\tfor (const [field, value] of Object.entries(fields)) {\n\t\t\t\tif (!Number.isInteger(value) || value < 0) {\n\t\t\t\t\tthrow metadataFail(`Mesh metadata field \"${field}\" must be a non-negative integer.`, {\n\t\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (mesh.vertexStart + mesh.vertexCount > totalVertexCount) {\n\t\t\t\tthrow metadataFail('Mesh vertex window exceeds the batch vertex buffer.', {\n\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\tvertexStart: mesh.vertexStart,\n\t\t\t\t\tvertexCount: mesh.vertexCount,\n\t\t\t\t\ttotalVertexCount\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (mesh.indexStart + mesh.indexCount > totalIndexCount) {\n\t\t\t\tthrow metadataFail('Mesh index window exceeds the batch index buffer.', {\n\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\tindexStart: mesh.indexStart,\n\t\t\t\t\tindexCount: mesh.indexCount,\n\t\t\t\t\ttotalIndexCount\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Error for an index outside its mesh's declared vertex window\n * `[vertexStart, vertexStart + vertexCount)`. Rebasing (`index - vertexStart`) writes into an\n * unsigned array, so a violation would otherwise wrap to ~4 billion and corrupt the geometry.\n * The range checks themselves are inlined in the copy loops (audit P6 — a function call per index\n * was measurable at millions of indices); this only builds the failure.\n */\nfunction indexOutOfWindow(indexValue: number, meshMeta: MeshMetadata): RhinoComputeError {\n\treturn metadataFail(\"Index references a vertex outside its mesh's vertex window.\", {\n\t\tmeshName: meshMeta.name,\n\t\tindexValue,\n\t\tvertexStart: meshMeta.vertexStart,\n\t\tvertexCount: meshMeta.vertexCount\n\t});\n}\n\n/**\n * Content key for the cross-solve geometry cache: samples of every buffer window this geometry is\n * built from, plus the window layout as salt (identical bytes at a different offset rebase to\n * different geometry). See geometry-cache.ts for the safety model.\n */\nfunction geometryContentKey(\n\tkind: 'merged' | 'single',\n\tmeshes: MeshMetadata[],\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tallUvs: Float32Array | null,\n\tallColors: Uint8Array | null\n): string {\n\tconst parts: (ArrayBufferView | null)[] = [];\n\tlet salt = kind;\n\tfor (const meshMeta of meshes) {\n\t\tsalt += `|${meshMeta.vertexStart},${meshMeta.vertexCount},${meshMeta.indexStart},${meshMeta.indexCount}`;\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentEnd = componentStart + meshMeta.vertexCount * 3;\n\t\tparts.push(allVertices.subarray(componentStart, componentEnd));\n\t\tparts.push(allIndices.subarray(meshMeta.indexStart, meshMeta.indexStart + meshMeta.indexCount));\n\t\tparts.push(\n\t\t\tallUvs\n\t\t\t\t? allUvs.subarray(\n\t\t\t\t\t\tmeshMeta.vertexStart * 2,\n\t\t\t\t\t\t(meshMeta.vertexStart + meshMeta.vertexCount) * 2\n\t\t\t\t\t)\n\t\t\t\t: null\n\t\t);\n\t\tparts.push(allColors ? allColors.subarray(componentStart, componentEnd) : null);\n\t}\n\treturn fingerprintViews(parts, salt);\n}\n\n/**\n * Reconstructs world-unit float32 positions from int16 quantized values.\n *\n * Mirrors the encoder formula: `world = origin + (q + 32767) * scale`. Selva keeps one coordinate\n * frame end to end (the Three scene is Rhino's Z-up frame — see `../coordinate-transform.ts`), so\n * vertices pass through unrotated. `_applyCoordinateTransform` is retained for call-site\n * compatibility and no longer changes the output.\n */\nfunction dequantizeInt16(\n\tq: Int16Array,\n\torigin: [number, number, number],\n\tscale: [number, number, number],\n\t_applyCoordinateTransform: boolean\n): Float32Array {\n\tconst out = new Float32Array(q.length);\n\tconst ox = origin[0];\n\tconst oy = origin[1];\n\tconst oz = origin[2];\n\tconst sx = scale[0];\n\tconst sy = scale[1];\n\tconst sz = scale[2];\n\n\tfor (let i = 0; i < q.length; i += 3) {\n\t\tout[i] = ox + (q[i]! + 32767) * sx;\n\t\tout[i + 1] = oy + (q[i + 1]! + 32767) * sy;\n\t\tout[i + 2] = oz + (q[i + 2]! + 32767) * sz;\n\t}\n\n\treturn out;\n}\n\n/**\n * For float32 batches the parser's view is already in the scene frame (Rhino Z-up), so we pass it\n * through without copying. `_applyCoordinateTransform` is retained for call-site compatibility and\n * no longer rotates.\n */\nfunction maybeRotateFloat32Vertices(\n\tvertices: Float32Array,\n\t_applyCoordinateTransform: boolean\n): Float32Array {\n\treturn vertices;\n}\n\n// ============================================================================\n// OFF-THREAD ASSEMBLY (audit P2 — docs/plans/5.display-pipeline-performance-audit.md)\n// ============================================================================\n\n/**\n * Below this triangle count the synchronous path finishes in ~10 ms — a worker round-trip (two\n * buffer copies + wake) isn't worth it. Above it, delta-decode + dequantize + merge + normals run\n * in the worker and the main thread only wraps returned buffers (or reuses cached geometries).\n */\nconst ASSEMBLY_WORKER_MIN_TRIANGLES = 50_000;\n\ninterface PendingAssembly {\n\tresolve: (geometries: AssembledGeometry[]) => void;\n\treject: (error: Error) => void;\n}\n\nlet assemblyWorker: Worker | null | undefined; // undefined = not yet tried, null = unavailable\nconst pendingAssemblies = new Map<number, PendingAssembly>();\nlet nextAssemblyRequestId = 1;\n\nfunction getAssemblyWorker(): Worker | null {\n\tif (assemblyWorker !== undefined) return assemblyWorker;\n\tif (\n\t\ttypeof Worker === 'undefined' ||\n\t\ttypeof Blob === 'undefined' ||\n\t\ttypeof URL === 'undefined' ||\n\t\ttypeof URL.createObjectURL !== 'function'\n\t) {\n\t\tassemblyWorker = null;\n\t\treturn null;\n\t}\n\ttry {\n\t\t// Blob URL keeps the library bundler-agnostic; deliberately never revoked (see edges.ts).\n\t\tconst url = URL.createObjectURL(\n\t\t\tnew Blob([meshAssemblyWorkerSource()], { type: 'text/javascript' })\n\t\t);\n\t\tconst worker = new Worker(url);\n\t\tworker.onmessage = (event: MessageEvent) => {\n\t\t\tconst { id, geometries, error } = event.data as {\n\t\t\t\tid: number;\n\t\t\t\tgeometries?: AssembledGeometry[];\n\t\t\t\terror?: string;\n\t\t\t};\n\t\t\tconst pending = pendingAssemblies.get(id);\n\t\t\tif (!pending) return;\n\t\t\tpendingAssemblies.delete(id);\n\t\t\tif (geometries) pending.resolve(geometries);\n\t\t\telse pending.reject(new Error(error ?? 'mesh assembly failed in worker'));\n\t\t};\n\t\tworker.onerror = () => {\n\t\t\tfor (const pending of pendingAssemblies.values()) {\n\t\t\t\tpending.reject(new Error('mesh assembly worker crashed'));\n\t\t\t}\n\t\t\tpendingAssemblies.clear();\n\t\t\tworker.terminate();\n\t\t\tassemblyWorker = null; // don't retry this session — callers fall back to the sync path\n\t\t};\n\t\tassemblyWorker = worker;\n\t} catch {\n\t\tassemblyWorker = null;\n\t}\n\treturn assemblyWorker;\n}\n\nfunction requestAssembly(\n\tworker: Worker,\n\tinput: unknown,\n\ttransfer: Transferable[]\n): Promise<AssembledGeometry[]> {\n\treturn new Promise<AssembledGeometry[]>((resolve, reject) => {\n\t\tconst id = nextAssemblyRequestId++;\n\t\tpendingAssemblies.set(id, { resolve, reject });\n\t\tworker.postMessage({ id, input }, transfer);\n\t});\n}\n\ninterface WorkerPathOptions {\n\tmergeByMaterial: boolean;\n\tapplyTransforms: boolean;\n\tdebug: boolean;\n\tmaterial?: MaterialAppearanceOptions;\n\tfallback?: BuildOptions['fallback'];\n}\n\n/**\n * Attempt the off-thread build. Returns the finished meshes, or `null` when the worker path\n * doesn't apply (no Worker, small batch, worker crashed) — the caller then runs the synchronous\n * path. Malformed-blob/metadata errors throw, matching the entry points' contract either way.\n *\n * Cache interplay: the worker always assembles and fingerprints every geometry (decode is\n * whole-array work anyway), and the main thread prefers an existing cached geometry over the\n * returned buffers — so cache hits skip the GPU re-upload, and the wasted worker CPU for them is\n * off the critical path by definition.\n */\nasync function tryBuildViaWorker(\n\tinput: ArrayBuffer | Uint8Array | string,\n\topts: WorkerPathOptions\n): Promise<THREE.Mesh[] | null> {\n\tif (typeof Worker === 'undefined') return null;\n\n\tconst raw = parseBinaryMeshBatchRaw(input);\n\tif (raw.indexData.length / 3 < ASSEMBLY_WORKER_MIN_TRIANGLES) return null;\n\tconst worker = getAssemblyWorker();\n\tif (!worker) return null;\n\n\tconst materialsSrc = raw.metadata.materials ?? opts.fallback?.materials ?? [];\n\tconst groups = raw.metadata.groups ?? opts.fallback?.groups ?? [];\n\tconst sourceComponentId = opts.fallback?.sourceComponentId ?? raw.metadata.sourceComponentId;\n\tvalidateGroupMetadata(groups, materialsSrc.length, raw.vertexCount, raw.indexData.length);\n\n\t// Same job branching as buildMeshesFromParsed, with a parallel ref list to wrap results.\n\tinterface JobRef {\n\t\tkind: 'merged' | 'single';\n\t\tgroup: MaterialGroup;\n\t\tmeshMeta?: MeshMetadata;\n\t}\n\tconst windowOf = (m: MeshMetadata): AssemblyWindow => ({\n\t\tvertexStart: m.vertexStart,\n\t\tvertexCount: m.vertexCount,\n\t\tindexStart: m.indexStart,\n\t\tindexCount: m.indexCount\n\t});\n\tconst jobs: AssemblyJob[] = [];\n\tconst jobRefs: JobRef[] = [];\n\tfor (const group of groups) {\n\t\tif (opts.mergeByMaterial && group.meshes.length > 1) {\n\t\t\tjobs.push({ kind: 'merged', windows: group.meshes.map(windowOf) });\n\t\t\tjobRefs.push({ kind: 'merged', group });\n\t\t} else {\n\t\t\tfor (const meshMeta of group.meshes) {\n\t\t\t\tjobs.push({ kind: 'single', windows: [windowOf(meshMeta)] });\n\t\t\t\tjobRefs.push({ kind: 'single', group, meshMeta });\n\t\t\t}\n\t\t}\n\t}\n\n\t// The geometry views alias the caller's blob buffer — copy them so the transfer can't detach\n\t// it. UV/color arrays are parser-owned fresh copies and transfer directly.\n\tconst vertexData = raw.vertexData.slice();\n\tconst indexData = raw.indexData.slice();\n\tconst transfer: Transferable[] = [vertexData.buffer, indexData.buffer];\n\tif (raw.uvs) transfer.push(raw.uvs.buffer);\n\tif (raw.colors) transfer.push(raw.colors.buffer);\n\n\tlet assembled: AssembledGeometry[];\n\ttry {\n\t\tassembled = await requestAssembly(\n\t\t\tworker,\n\t\t\t{\n\t\t\t\tvertexData,\n\t\t\t\tisFloat32: raw.isFloat32,\n\t\t\t\tdeltaEncoded: raw.deltaEncoded,\n\t\t\t\torigin: raw.origin,\n\t\t\t\tscale: raw.scale,\n\t\t\t\tindexData,\n\t\t\t\tuvs: raw.uvs,\n\t\t\t\tcolors: raw.colors,\n\t\t\t\tjobs\n\t\t\t},\n\t\t\ttransfer\n\t\t);\n\t} catch (error) {\n\t\tgetLogger().warn('Mesh assembly worker failed; falling back to main-thread parse.', error);\n\t\treturn null;\n\t}\n\tif (assembled.length !== jobs.length) return null; // defensive: protocol mismatch → sync path\n\n\tconst materials = materialsSrc.map((m) =>\n\t\tcreateMaterial(m, { vertexColors: raw.colors != null, appearance: opts.material })\n\t);\n\n\tconst meshes: THREE.Mesh[] = [];\n\tfor (let i = 0; i < assembled.length; i++) {\n\t\tconst result = assembled[i]!;\n\t\tconst ref = jobRefs[i]!;\n\n\t\tlet geometry = geometryCacheGet(result.key);\n\t\tif (!geometry) {\n\t\t\tgeometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(result.positions, 3));\n\t\t\tgeometry.setAttribute('normal', new THREE.BufferAttribute(result.normals, 3));\n\t\t\tgeometry.setIndex(new THREE.BufferAttribute(result.indices, 1));\n\t\t\tif (result.uvs) geometry.setAttribute('uv', new THREE.BufferAttribute(result.uvs, 2));\n\t\t\tif (result.colors) {\n\t\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(result.colors, 3, true));\n\t\t\t}\n\t\t\tgeometryCachePut(result.key, geometry);\n\t\t}\n\n\t\tconst mesh =\n\t\t\tref.kind === 'merged'\n\t\t\t\t? finalizeMergedMesh(geometry, ref.group, materials)\n\t\t\t\t: finalizeSingleMesh(geometry, ref.meshMeta!, ref.group, materials);\n\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\tmeshes.push(mesh);\n\t}\n\n\tif (opts.debug) {\n\t\tgetLogger().debug(\n\t\t\t`Mesh batch assembled off-thread: ${meshes.length} meshes, ${raw.indexData.length / 3} triangles`\n\t\t);\n\t}\n\treturn meshes;\n}\n\n// ============================================================================\n// MATERIAL CONSTRUCTION\n// ============================================================================\n\n// A near-pure metal has no diffuse response, so under the low-IBL 'technical' look it goes flat and\n// reads as painted card. Real architectural sheet metal is coated, not a bare mirror — so materials\n// that are meaningfully metallic get a thin satin clearcoat: a glossy dielectric layer whose\n// highlight and environment response are independent of the base metalness/envMap, so folds catch\n// light even when the IBL is dialed down. Below this metalness the material is treated as\n// plastic/matte and left untouched.\nconst METAL_CLEARCOAT_THRESHOLD = 0.5;\nconst METAL_CLEARCOAT = 0.5;\nconst METAL_CLEARCOAT_ROUGHNESS = 0.3;\n\nfunction createMaterial(\n\tmatData: SerializableMaterial,\n\toptions?: { vertexColors?: boolean; appearance?: MaterialAppearanceOptions }\n): THREE.MeshPhysicalMaterial {\n\tconst color = parseColor(matData.color);\n\tconst vertexColors = options?.vertexColors ?? false;\n\tconst appearance = options?.appearance;\n\n\tconst material = new THREE.MeshPhysicalMaterial({\n\t\tcolor,\n\t\tmetalness: matData.metalness,\n\t\troughness: matData.roughness,\n\t\topacity: matData.opacity,\n\t\ttransparent: matData.transparent,\n\t\tvertexColors,\n\t\t// Cull back faces for closed solids (crisper silhouette, less overdraw); keep both sides for\n\t\t// open surfaces. Caller-controlled since Rhino emits both — default DoubleSide is the safe read.\n\t\tside: appearance?.cullBackfaces ? THREE.FrontSide : THREE.DoubleSide,\n\t\t// Reduced polygon offset to minimize artifacts\n\t\t// Only use minimal offset to prevent z-fighting on coplanar faces\n\t\tpolygonOffset: true,\n\t\tpolygonOffsetFactor: 0.5,\n\t\tpolygonOffsetUnits: 0.5,\n\t\t// Improve depth rendering\n\t\tdepthWrite: true,\n\t\tdepthTest: true\n\t});\n\n\t// HDR image-based-lighting reflection strength. Left at three's default (1) unless the caller\n\t// dials it: <1 flattens reflections toward a matte/technical read, >1 pushes a glossier look.\n\tif (appearance?.envMapIntensity != null) {\n\t\tmaterial.envMapIntensity = appearance.envMapIntensity;\n\t}\n\n\t// Metals get a satin clearcoat so coated sheet metal reads as coated, not flat, under low IBL\n\t// (see the constants above). Plastics/matte fall below the threshold and stay bare.\n\tif (matData.metalness > METAL_CLEARCOAT_THRESHOLD) {\n\t\tmaterial.clearcoat = METAL_CLEARCOAT;\n\t\tmaterial.clearcoatRoughness = METAL_CLEARCOAT_ROUGHNESS;\n\t}\n\n\t// Vertex colors arrive as raw sRGB bytes, but three's vertex-color path multiplies them into the\n\t// (linear) working space with no decode — so they render washed out. Patch the vertex shader to\n\t// sRGB→linear decode `color` before use. Only meshes with real vertex colors take this path.\n\tif (vertexColors) {\n\t\tapplyVertexColorSRGBDecode(material);\n\t}\n\n\t// Texture loading is async (image decode); the cache assigns `material.map` when ready and\n\t// flags needsUpdate, so the mesh renders untextured for at most the first frames. Hash-keyed\n\t// asset URLs are immutable, so each texture is fetched and decoded once per session.\n\tif (matData.map) {\n\t\tapplyTextureMap(material, matData.map);\n\t}\n\n\treturn material;\n}\n\n/**\n * Patch a material's vertex shader to decode its per-vertex `color` attribute from sRGB to linear.\n * three.js uploads vertex colors verbatim and its `color_vertex` chunk multiplies them straight into\n * the linear working color space (unlike textures, which carry a `colorSpace` and get decoded) — so\n * sRGB-authored vertex colors render too bright without this. Done in the shader (not a CPU pass over\n * the buffer) to keep the hot per-solve parse cheap; the decode is a handful of GPU ops per vertex.\n */\nfunction applyVertexColorSRGBDecode(material: THREE.Material): void {\n\tmaterial.onBeforeCompile = (shader) => {\n\t\tshader.vertexShader = shader.vertexShader.replace(\n\t\t\t'#include <color_vertex>',\n\t\t\t`#include <color_vertex>\n\t\t\t#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\t\t\t\tvColor.rgb = mix(\n\t\t\t\t\tvColor.rgb / 12.92,\n\t\t\t\t\tpow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),\n\t\t\t\t\tstep( vec3( 0.04045 ), vColor.rgb )\n\t\t\t\t);\n\t\t\t#endif`\n\t\t);\n\t};\n}\n\n// ============================================================================\n// MESH CONSTRUCTION\n// ============================================================================\n\n/**\n * Creates a merged mesh from multiple meshes sharing the same material.\n *\n * Indices in the parser output already reference offsets into the combined vertex array (the C#\n * pipeline rebases per-mesh local indices into combined-array indices when assembling the batch).\n * For merged meshes we copy the relevant slices into a fresh contiguous buffer and shift indices\n * to match the new layout.\n */\nfunction createMergedMesh(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tmaterials: THREE.Material[],\n\tallUvs: Float32Array | null = null,\n\tallColors: Uint8Array | null = null\n): THREE.Mesh {\n\t// Cross-solve reuse (audit P1): identical content → same BufferGeometry object, skipping the\n\t// merge copies, computeVertexNormals, and the GPU re-upload entirely.\n\tconst cacheKey = geometryContentKey(\n\t\t'merged',\n\t\tgroup.meshes,\n\t\tallVertices,\n\t\tallIndices,\n\t\tallUvs,\n\t\tallColors\n\t);\n\tlet geometry = geometryCacheGet(cacheKey);\n\n\tif (!geometry) {\n\t\tlet totalVertexCount = 0;\n\t\tlet totalIndexCount = 0;\n\t\tfor (const meshMeta of group.meshes) {\n\t\t\ttotalVertexCount += meshMeta.vertexCount;\n\t\t\ttotalIndexCount += meshMeta.indexCount;\n\t\t}\n\n\t\tconst mergedVertices = new Float32Array(totalVertexCount * 3);\n\t\tconst mergedIndices = new Uint32Array(totalIndexCount);\n\t\tconst mergedUvs = allUvs ? new Float32Array(totalVertexCount * 2) : null;\n\t\tconst mergedColors = allColors ? new Uint8Array(totalVertexCount * 3) : null;\n\n\t\tlet vertexWriteCursor = 0;\n\t\tlet indexWriteCursor = 0;\n\n\t\tfor (const meshMeta of group.meshes) {\n\t\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\t\tconst componentLen = meshMeta.vertexCount * 3;\n\t\t\tmergedVertices.set(\n\t\t\t\tallVertices.subarray(componentStart, componentStart + componentLen),\n\t\t\t\tvertexWriteCursor * 3\n\t\t\t);\n\n\t\t\tif (mergedUvs && allUvs) {\n\t\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\t\tmergedUvs.set(\n\t\t\t\t\tallUvs.subarray(uvStart, uvStart + meshMeta.vertexCount * 2),\n\t\t\t\t\tvertexWriteCursor * 2\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (mergedColors && allColors) {\n\t\t\t\tmergedColors.set(\n\t\t\t\t\tallColors.subarray(componentStart, componentStart + componentLen),\n\t\t\t\t\tvertexWriteCursor * 3\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst indicesSlice = allIndices.subarray(\n\t\t\t\tmeshMeta.indexStart,\n\t\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t\t);\n\t\t\tconst indexShift = vertexWriteCursor - meshMeta.vertexStart;\n\t\t\tconst windowStart = meshMeta.vertexStart;\n\t\t\tconst windowEnd = meshMeta.vertexStart + meshMeta.vertexCount;\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\t\tif (indexValue < windowStart || indexValue >= windowEnd) {\n\t\t\t\t\tthrow indexOutOfWindow(indexValue, meshMeta);\n\t\t\t\t}\n\t\t\t\tmergedIndices[indexWriteCursor + i] = indexValue + indexShift;\n\t\t\t}\n\n\t\t\tvertexWriteCursor += meshMeta.vertexCount;\n\t\t\tindexWriteCursor += meshMeta.indexCount;\n\t\t}\n\n\t\tgeometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(mergedVertices, 3));\n\t\tgeometry.setIndex(new THREE.BufferAttribute(mergedIndices, 1));\n\t\tif (mergedUvs) {\n\t\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(mergedUvs, 2));\n\t\t}\n\t\tif (mergedColors) {\n\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(mergedColors, 3, true));\n\t\t}\n\t\tgeometry.computeVertexNormals();\n\t\tgeometryCachePut(cacheKey, geometry);\n\t}\n\n\treturn finalizeMergedMesh(geometry, group, materials);\n}\n\n/** Wraps a merged group's geometry (built or cache-hit) in its THREE.Mesh with identity/userData. */\nfunction finalizeMergedMesh(\n\tgeometry: THREE.BufferGeometry,\n\tgroup: MaterialGroup,\n\tmaterials: THREE.Material[]\n): THREE.Mesh {\n\tconst threeMesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\tconst firstMesh = group.meshes[0];\n\tconst meshNames = group.meshes.map((m) => m.name).filter((name) => name && name.length > 0);\n\tthreeMesh.name = meshNames.length > 0 ? meshNames[0]! : `merged_material_${group.materialId}`;\n\tthreeMesh.castShadow = true;\n\tthreeMesh.receiveShadow = true;\n\n\tthreeMesh.userData = {\n\t\tsource: 'compute',\n\t\tname: threeMesh.name,\n\t\tlayer: firstMesh?.layer ?? '',\n\t\toriginalIndex: firstMesh?.originalIndex ?? 0,\n\t\tmetadata: firstMesh?.metadata ?? {},\n\t\tmergedFrom: group.meshes.slice(1).map((m) => ({\n\t\t\tname: m.name,\n\t\t\tlayer: m.layer,\n\t\t\toriginalIndex: m.originalIndex\n\t\t}))\n\t};\n\n\treturn threeMesh;\n}\n\n/**\n * Creates individual meshes from a material group. Each mesh's indices are rebased so they\n * address its own local vertex slice starting from 0.\n */\nfunction createIndividualMeshes(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tmaterials: THREE.Material[],\n\tallUvs: Float32Array | null = null,\n\tallColors: Uint8Array | null = null\n): THREE.Mesh[] {\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\n\t\t// Cross-solve reuse (audit P1) — see createMergedMesh.\n\t\tconst cacheKey = geometryContentKey(\n\t\t\t'single',\n\t\t\t[meshMeta],\n\t\t\tallVertices,\n\t\t\tallIndices,\n\t\t\tallUvs,\n\t\t\tallColors\n\t\t);\n\t\tlet geometry = geometryCacheGet(cacheKey);\n\n\t\tif (!geometry) {\n\t\t\t// `subarray` returns a view; copy via `slice` so the BufferAttribute owns its memory and\n\t\t\t// downstream code (dispose/reuse) can't surprise us by sharing the parser's buffer.\n\t\t\tconst vertices = allVertices.slice(componentStart, componentStart + componentLen);\n\n\t\t\tconst indicesSlice = allIndices.subarray(\n\t\t\t\tmeshMeta.indexStart,\n\t\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t\t);\n\t\t\tconst rebasedIndices = new Uint32Array(indicesSlice.length);\n\t\t\tconst baseIndex = meshMeta.vertexStart;\n\t\t\tconst windowEnd = meshMeta.vertexStart + meshMeta.vertexCount;\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\t\tif (indexValue < baseIndex || indexValue >= windowEnd) {\n\t\t\t\t\tthrow indexOutOfWindow(indexValue, meshMeta);\n\t\t\t\t}\n\t\t\t\trebasedIndices[i] = indexValue - baseIndex;\n\t\t\t}\n\n\t\t\tgeometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\t\t\tgeometry.setIndex(new THREE.BufferAttribute(rebasedIndices, 1));\n\t\t\tif (allUvs) {\n\t\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\t\tconst uvs = allUvs.slice(uvStart, uvStart + meshMeta.vertexCount * 2);\n\t\t\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));\n\t\t\t}\n\t\t\tif (allColors) {\n\t\t\t\tconst colors = allColors.slice(componentStart, componentStart + componentLen);\n\t\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3, true));\n\t\t\t}\n\t\t\tgeometry.computeVertexNormals();\n\t\t\tgeometryCachePut(cacheKey, geometry);\n\t\t}\n\n\t\tmeshes.push(finalizeSingleMesh(geometry, meshMeta, group, materials));\n\t}\n\n\treturn meshes;\n}\n\n/** Wraps a single mesh's geometry (built or cache-hit) in its THREE.Mesh with identity/userData. */\nfunction finalizeSingleMesh(\n\tgeometry: THREE.BufferGeometry,\n\tmeshMeta: MeshMetadata,\n\tgroup: MaterialGroup,\n\tmaterials: THREE.Material[]\n): THREE.Mesh {\n\tconst mesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\tmesh.name = meshMeta.name;\n\tmesh.userData = {\n\t\tsource: 'compute',\n\t\tname: meshMeta.name,\n\t\tlayer: meshMeta.layer ?? '',\n\t\toriginalIndex: meshMeta.originalIndex,\n\t\tmetadata: meshMeta.metadata ?? {}\n\t};\n\tmesh.castShadow = true;\n\tmesh.receiveShadow = true;\n\treturn mesh;\n}\n\n// ============================================================================\n// DEBUG HELPERS\n// ============================================================================\n\nfunction approximateBase64DecodedBytes(base64: string): number {\n\treturn Math.floor((base64.length * 3) / 4);\n}\n","import * as THREE from 'three';\n\nimport { CACHED_GEOMETRY_USERDATA_FLAG } from '../threejs/three-helpers.js';\n\n/**\n * Cross-solve `BufferGeometry` cache, keyed by geometry *content* (audit P1 —\n * docs/plans/5.display-pipeline-performance-audit.md).\n *\n * The viewer rebuilds the whole scene every solve: `clearScene` disposes every geometry and the\n * parser re-decodes, re-copies, re-computes normals and re-uploads to the GPU — even for meshes the\n * solve didn't change. This cache closes that loop the same way the edge-segment cache does:\n * fingerprint the *raw wire windows* a geometry is built from, and on a hit hand back the very same\n * `BufferGeometry` (normals computed, GPU buffers still resident) instead of rebuilding it.\n *\n * Safety model:\n * - Cached geometries are tagged with {@link CACHED_GEOMETRY_USERDATA_FLAG}; `clearScene` skips\n * disposing them, so the GPU buffers survive scene rebuilds. Everything else is disposed exactly\n * as before.\n * - Eviction (LRU by vertex+index bytes) *does* dispose. If an evicted geometry is still attached\n * to a live mesh, three transparently re-uploads its buffers on the next render — a one-frame\n * cost, never corruption.\n * - Sharing one geometry across several meshes (same content appearing twice in a solve, or across\n * solves) is safe: geometry is immutable after build, and materials live on the meshes.\n */\n\n/** CPU+GPU byte budget for cached geometry (positions+normals+indices+uv+color attributes). */\nconst GEOMETRY_CACHE_BYTE_BUDGET = 256 * 1024 * 1024;\n\n/** Words sampled from the head and tail of each buffer window when fingerprinting. */\nconst SAMPLE_WORDS = 1024;\n\ninterface CacheEntry {\n\tgeometry: THREE.BufferGeometry;\n\tbytes: number;\n}\n\nconst cache = new Map<string, CacheEntry>();\nlet cacheBytes = 0;\n\n/**\n * FNV-1a over head+tail samples of each part plus every part's exact length, mixed with a caller\n * salt (quantization origin/scale, flags, window layout). Sampling keeps the hash ~free at millions\n * of vertices; a false hit would need identical lengths AND identical sampled regions across a real\n * geometry edit — the same accepted trade the edge-segment cache documents.\n */\nexport function fingerprintViews(parts: (ArrayBufferView | null)[], salt: string): string {\n\tlet hash = 0x811c9dc5;\n\tconst mix = (word: number): void => {\n\t\thash ^= word;\n\t\thash = Math.imul(hash, 0x01000193);\n\t};\n\n\tfor (let i = 0; i < salt.length; i++) mix(salt.charCodeAt(i));\n\n\tfor (const part of parts) {\n\t\tif (!part) {\n\t\t\tmix(0xdead);\n\t\t\tcontinue;\n\t\t}\n\t\t// Hash raw 32-bit words where alignment allows; fall back to a byte view otherwise.\n\t\tconst byteLength = part.byteLength;\n\t\tmix(byteLength);\n\t\tif ((part.byteOffset & 3) === 0 && (byteLength & 3) === 0) {\n\t\t\tconst words = new Uint32Array(part.buffer, part.byteOffset, byteLength >> 2);\n\t\t\tconst head = Math.min(SAMPLE_WORDS, words.length);\n\t\t\tfor (let i = 0; i < head; i++) mix(words[i]!);\n\t\t\tfor (let i = Math.max(head, words.length - SAMPLE_WORDS); i < words.length; i++) {\n\t\t\t\tmix(words[i]!);\n\t\t\t}\n\t\t} else {\n\t\t\tconst bytes = new Uint8Array(part.buffer, part.byteOffset, byteLength);\n\t\t\tconst head = Math.min(SAMPLE_WORDS * 4, bytes.length);\n\t\t\tfor (let i = 0; i < head; i++) mix(bytes[i]!);\n\t\t\tfor (let i = Math.max(head, bytes.length - SAMPLE_WORDS * 4); i < bytes.length; i++) {\n\t\t\t\tmix(bytes[i]!);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn `${(hash >>> 0).toString(36)}:${parts.length}`;\n}\n\nfunction bytesOf(geometry: THREE.BufferGeometry): number {\n\tlet total = geometry.index?.array.byteLength ?? 0;\n\tfor (const attribute of Object.values(geometry.attributes)) {\n\t\ttotal += (attribute as THREE.BufferAttribute).array.byteLength;\n\t}\n\treturn total;\n}\n\n/** Look up a cached geometry, refreshing its LRU position. */\nexport function geometryCacheGet(key: string): THREE.BufferGeometry | undefined {\n\tconst entry = cache.get(key);\n\tif (!entry) return undefined;\n\tcache.delete(key);\n\tcache.set(key, entry);\n\treturn entry.geometry;\n}\n\n/** Insert a freshly built geometry, tagging it so `clearScene` won't dispose it. */\nexport function geometryCachePut(key: string, geometry: THREE.BufferGeometry): void {\n\tconst bytes = bytesOf(geometry);\n\tif (bytes > GEOMETRY_CACHE_BYTE_BUDGET) return; // absurd single geometry — don't cache\n\n\tgeometry.userData[CACHED_GEOMETRY_USERDATA_FLAG] = true;\n\n\tconst existing = cache.get(key);\n\tif (existing) {\n\t\t// Same content raced in twice (e.g. duplicate content within one solve building in\n\t\t// parallel) — keep the incumbent, dispose nothing: the caller uses the returned geometry.\n\t\treturn;\n\t}\n\n\tcache.set(key, { geometry, bytes });\n\tcacheBytes += bytes;\n\n\twhile (cacheBytes > GEOMETRY_CACHE_BYTE_BUDGET && cache.size > 1) {\n\t\tconst oldestKey = cache.keys().next().value as string;\n\t\tconst oldest = cache.get(oldestKey)!;\n\t\tcache.delete(oldestKey);\n\t\tcacheBytes -= oldest.bytes;\n\t\t// Disposing while still referenced by a scene mesh is safe: three re-uploads on next render.\n\t\t// Clear the tag so a later clearScene can dispose it for good.\n\t\tdelete oldest.geometry.userData[CACHED_GEOMETRY_USERDATA_FLAG];\n\t\toldest.geometry.dispose();\n\t}\n}\n\n/** Test/diagnostic hook: empty the cache, disposing everything in it. */\nexport function geometryCacheClear(): void {\n\tfor (const entry of cache.values()) {\n\t\tdelete entry.geometry.userData[CACHED_GEOMETRY_USERDATA_FLAG];\n\t\tentry.geometry.dispose();\n\t}\n\tcache.clear();\n\tcacheBytes = 0;\n}\n","/**\n * Off-thread mesh assembly — audit P2 (docs/plans/5.display-pipeline-performance-audit.md).\n *\n * {@link assembleGeometries} performs the hot, pure part of batch parsing: undoing the delta\n * filter on the raw wire arrays, dequantizing int16 positions to world floats, slicing/rebasing\n * the per-geometry windows, computing vertex normals, and fingerprinting each geometry for the\n * cross-solve cache. Everything it needs travels as typed arrays, so the whole stage runs in a\n * Worker and the main thread only wraps the returned buffers into `BufferGeometry` objects.\n *\n * Like `edge-extract.ts`, the function is a single self-contained unit with zero outer captures\n * (only `Math` and its arguments) so `Function.prototype.toString` yields code that runs unchanged\n * inside a blob-URL Worker ({@link meshAssemblyWorkerSource}) — bundler-agnostic by construction.\n * That constraint forces some duplication of small pure helpers from `binary-parser.ts`\n * (unzigzag/delta decode) and `geometry-cache.ts` (fingerprint); equivalence is pinned by tests\n * that assert the worker path shares cache entries with the synchronous path.\n */\n\nexport interface AssemblyWindow {\n\tvertexStart: number;\n\tvertexCount: number;\n\tindexStart: number;\n\tindexCount: number;\n}\n\nexport interface AssemblyJob {\n\tkind: 'merged' | 'single';\n\twindows: AssemblyWindow[];\n}\n\nexport interface AssemblyInput {\n\t/** Raw wire vertex components: zigzag deltas (Uint16) when delta-encoded, else absolute. */\n\tvertexData: Uint16Array | Int16Array | Float32Array;\n\tisFloat32: boolean;\n\tdeltaEncoded: boolean;\n\torigin: [number, number, number];\n\tscale: [number, number, number];\n\t/** Raw wire indices: zigzag deltas when delta-encoded, else absolute. */\n\tindexData: Uint16Array | Uint32Array;\n\t/** Already-decoded absolute UV pairs / RGB bytes (small, decoded on the main thread). */\n\tuvs: Float32Array | null;\n\tcolors: Uint8Array | null;\n\tjobs: AssemblyJob[];\n}\n\nexport interface AssembledGeometry {\n\t/** Cache key — identical to the synchronous path's `geometryContentKey` output. */\n\tkey: string;\n\tpositions: Float32Array;\n\tnormals: Float32Array;\n\tindices: Uint32Array;\n\tuvs: Float32Array | null;\n\tcolors: Uint8Array | null;\n}\n\nexport function assembleGeometries(input: AssemblyInput): AssembledGeometry[] {\n\t// NOTE: self-contained by design (worker stringification) — no outer references besides Math.\n\tconst { isFloat32, deltaEncoded, origin, scale, uvs, colors, jobs } = input;\n\n\tconst unzigzag = (zz: number): number => (zz >>> 1) ^ -(zz & 1);\n\n\t// --- Undo the delta filter (whole-array: each value depends on its predecessor) ------------\n\tlet worldVertices: Float32Array;\n\tif (isFloat32) {\n\t\tworldVertices = input.vertexData as Float32Array;\n\t} else {\n\t\tlet quantized: Int16Array;\n\t\tif (deltaEncoded) {\n\t\t\tconst zigzagged = input.vertexData as Uint16Array;\n\t\t\tquantized = new Int16Array(zigzagged.length);\n\t\t\tlet px = 0;\n\t\t\tlet py = 0;\n\t\t\tlet pz = 0;\n\t\t\tfor (let i = 0; i < zigzagged.length; i += 3) {\n\t\t\t\tpx = ((px + unzigzag(zigzagged[i])) << 16) >> 16;\n\t\t\t\tpy = ((py + unzigzag(zigzagged[i + 1])) << 16) >> 16;\n\t\t\t\tpz = ((pz + unzigzag(zigzagged[i + 2])) << 16) >> 16;\n\t\t\t\tquantized[i] = px;\n\t\t\t\tquantized[i + 1] = py;\n\t\t\t\tquantized[i + 2] = pz;\n\t\t\t}\n\t\t} else {\n\t\t\tquantized = input.vertexData as Int16Array;\n\t\t}\n\t\t// Dequantize: world = origin + (q + 32767) * scale (matches the writer/binary-parser).\n\t\tworldVertices = new Float32Array(quantized.length);\n\t\tconst ox = origin[0];\n\t\tconst oy = origin[1];\n\t\tconst oz = origin[2];\n\t\tconst sx = scale[0];\n\t\tconst sy = scale[1];\n\t\tconst sz = scale[2];\n\t\tfor (let i = 0; i < quantized.length; i += 3) {\n\t\t\tworldVertices[i] = ox + (quantized[i] + 32767) * sx;\n\t\t\tworldVertices[i + 1] = oy + (quantized[i + 1] + 32767) * sy;\n\t\t\tworldVertices[i + 2] = oz + (quantized[i + 2] + 32767) * sz;\n\t\t}\n\t}\n\n\tlet indices: Uint16Array | Uint32Array;\n\tif (deltaEncoded) {\n\t\tconst zigzagged = input.indexData;\n\t\tif (zigzagged instanceof Uint16Array) {\n\t\t\tconst out = new Uint16Array(zigzagged.length);\n\t\t\tlet prev = 0;\n\t\t\tfor (let i = 0; i < zigzagged.length; i++) {\n\t\t\t\tprev = (prev + unzigzag(zigzagged[i])) & 0xffff;\n\t\t\t\tout[i] = prev;\n\t\t\t}\n\t\t\tindices = out;\n\t\t} else {\n\t\t\tconst out = new Uint32Array(zigzagged.length);\n\t\t\tlet prev = 0;\n\t\t\tfor (let i = 0; i < zigzagged.length; i++) {\n\t\t\t\tprev = (prev + unzigzag(zigzagged[i])) >>> 0;\n\t\t\t\tout[i] = prev;\n\t\t\t}\n\t\t\tindices = out;\n\t\t}\n\t} else {\n\t\tindices = input.indexData;\n\t}\n\n\tconst totalVertexCount = worldVertices.length / 3;\n\tfor (let i = 0; i < indices.length; i++) {\n\t\tif (indices[i] >= totalVertexCount) {\n\t\t\tthrow new Error(`Index ${indices[i]} out of range of vertexCount ${totalVertexCount}`);\n\t\t}\n\t}\n\n\t// --- Fingerprint (must byte-match geometry-cache.ts fingerprintViews) ----------------------\n\tconst SAMPLE_WORDS = 1024;\n\tconst fingerprint = (parts: (ArrayBufferView | null)[], salt: string): string => {\n\t\tlet hash = 0x811c9dc5;\n\t\tconst mix = (word: number): void => {\n\t\t\thash ^= word;\n\t\t\thash = Math.imul(hash, 0x01000193);\n\t\t};\n\t\tfor (let i = 0; i < salt.length; i++) mix(salt.charCodeAt(i));\n\t\tfor (const part of parts) {\n\t\t\tif (!part) {\n\t\t\t\tmix(0xdead);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst byteLength = part.byteLength;\n\t\t\tmix(byteLength);\n\t\t\tif ((part.byteOffset & 3) === 0 && (byteLength & 3) === 0) {\n\t\t\t\tconst words = new Uint32Array(part.buffer, part.byteOffset, byteLength >> 2);\n\t\t\t\tconst head = Math.min(SAMPLE_WORDS, words.length);\n\t\t\t\tfor (let i = 0; i < head; i++) mix(words[i]);\n\t\t\t\tfor (let i = Math.max(head, words.length - SAMPLE_WORDS); i < words.length; i++) {\n\t\t\t\t\tmix(words[i]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst bytes = new Uint8Array(part.buffer, part.byteOffset, byteLength);\n\t\t\t\tconst head = Math.min(SAMPLE_WORDS * 4, bytes.length);\n\t\t\t\tfor (let i = 0; i < head; i++) mix(bytes[i]);\n\t\t\t\tfor (let i = Math.max(head, bytes.length - SAMPLE_WORDS * 4); i < bytes.length; i++) {\n\t\t\t\t\tmix(bytes[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn `${(hash >>> 0).toString(36)}:${parts.length}`;\n\t};\n\n\tconst keyFor = (kind: string, windows: AssemblyWindow[]): string => {\n\t\tconst parts: (ArrayBufferView | null)[] = [];\n\t\tlet salt = kind;\n\t\tfor (const window of windows) {\n\t\t\tsalt += `|${window.vertexStart},${window.vertexCount},${window.indexStart},${window.indexCount}`;\n\t\t\tconst componentStart = window.vertexStart * 3;\n\t\t\tconst componentEnd = componentStart + window.vertexCount * 3;\n\t\t\tparts.push(worldVertices.subarray(componentStart, componentEnd));\n\t\t\tparts.push(indices.subarray(window.indexStart, window.indexStart + window.indexCount));\n\t\t\tparts.push(\n\t\t\t\tuvs\n\t\t\t\t\t? uvs.subarray(window.vertexStart * 2, (window.vertexStart + window.vertexCount) * 2)\n\t\t\t\t\t: null\n\t\t\t);\n\t\t\tparts.push(colors ? colors.subarray(componentStart, componentEnd) : null);\n\t\t}\n\t\treturn fingerprint(parts, salt);\n\t};\n\n\t// --- Assemble each job: window copies, rebased indices, area-weighted vertex normals --------\n\tconst results: AssembledGeometry[] = [];\n\n\tfor (const job of jobs) {\n\t\tlet vertexTotal = 0;\n\t\tlet indexTotal = 0;\n\t\tfor (const window of job.windows) {\n\t\t\tvertexTotal += window.vertexCount;\n\t\t\tindexTotal += window.indexCount;\n\t\t}\n\n\t\tconst positions = new Float32Array(vertexTotal * 3);\n\t\tconst outIndices = new Uint32Array(indexTotal);\n\t\tconst outUvs = uvs ? new Float32Array(vertexTotal * 2) : null;\n\t\tconst outColors = colors ? new Uint8Array(vertexTotal * 3) : null;\n\n\t\tlet vertexCursor = 0;\n\t\tlet indexCursor = 0;\n\t\tfor (const window of job.windows) {\n\t\t\tconst componentStart = window.vertexStart * 3;\n\t\t\tpositions.set(\n\t\t\t\tworldVertices.subarray(componentStart, componentStart + window.vertexCount * 3),\n\t\t\t\tvertexCursor * 3\n\t\t\t);\n\t\t\tif (outUvs && uvs) {\n\t\t\t\toutUvs.set(\n\t\t\t\t\tuvs.subarray(window.vertexStart * 2, (window.vertexStart + window.vertexCount) * 2),\n\t\t\t\t\tvertexCursor * 2\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (outColors && colors) {\n\t\t\t\toutColors.set(\n\t\t\t\t\tcolors.subarray(componentStart, componentStart + window.vertexCount * 3),\n\t\t\t\t\tvertexCursor * 3\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst windowStart = window.vertexStart;\n\t\t\tconst windowEnd = window.vertexStart + window.vertexCount;\n\t\t\tconst shift = vertexCursor - window.vertexStart;\n\t\t\tfor (let i = 0; i < window.indexCount; i++) {\n\t\t\t\tconst indexValue = indices[window.indexStart + i];\n\t\t\t\tif (indexValue < windowStart || indexValue >= windowEnd) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Index ${indexValue} outside vertex window [${windowStart}, ${windowEnd})`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\toutIndices[indexCursor + i] = indexValue + shift;\n\t\t\t}\n\n\t\t\tvertexCursor += window.vertexCount;\n\t\t\tindexCursor += window.indexCount;\n\t\t}\n\n\t\t// Vertex normals, mirroring THREE.BufferGeometry.computeVertexNormals: accumulate the\n\t\t// non-normalized (area-weighted) face normal cross((c-b),(a-b)) onto each corner, then\n\t\t// normalize per vertex.\n\t\tconst normals = new Float32Array(vertexTotal * 3);\n\t\tfor (let i = 0; i < outIndices.length; i += 3) {\n\t\t\tconst a = outIndices[i] * 3;\n\t\t\tconst b = outIndices[i + 1] * 3;\n\t\t\tconst c = outIndices[i + 2] * 3;\n\n\t\t\tconst cbx = positions[c] - positions[b];\n\t\t\tconst cby = positions[c + 1] - positions[b + 1];\n\t\t\tconst cbz = positions[c + 2] - positions[b + 2];\n\t\t\tconst abx = positions[a] - positions[b];\n\t\t\tconst aby = positions[a + 1] - positions[b + 1];\n\t\t\tconst abz = positions[a + 2] - positions[b + 2];\n\n\t\t\tconst nx = cby * abz - cbz * aby;\n\t\t\tconst ny = cbz * abx - cbx * abz;\n\t\t\tconst nz = cbx * aby - cby * abx;\n\n\t\t\tnormals[a] += nx;\n\t\t\tnormals[a + 1] += ny;\n\t\t\tnormals[a + 2] += nz;\n\t\t\tnormals[b] += nx;\n\t\t\tnormals[b + 1] += ny;\n\t\t\tnormals[b + 2] += nz;\n\t\t\tnormals[c] += nx;\n\t\t\tnormals[c + 1] += ny;\n\t\t\tnormals[c + 2] += nz;\n\t\t}\n\t\tfor (let i = 0; i < normals.length; i += 3) {\n\t\t\tconst x = normals[i];\n\t\t\tconst y = normals[i + 1];\n\t\t\tconst z = normals[i + 2];\n\t\t\tconst length = Math.sqrt(x * x + y * y + z * z) || 1;\n\t\t\tnormals[i] = x / length;\n\t\t\tnormals[i + 1] = y / length;\n\t\t\tnormals[i + 2] = z / length;\n\t\t}\n\n\t\tresults.push({\n\t\t\tkey: keyFor(job.kind, job.windows),\n\t\t\tpositions,\n\t\t\tnormals,\n\t\t\tindices: outIndices,\n\t\t\tuvs: outUvs,\n\t\t\tcolors: outColors\n\t\t});\n\t}\n\n\treturn results;\n}\n\n/**\n * Worker script running {@link assembleGeometries} off the main thread. Protocol: receives\n * `{id, input}`, replies `{id, geometries}` with every output buffer transferred, or\n * `{id, error}`. Pinned by a test that evals this source against a stub `self`.\n */\nexport function meshAssemblyWorkerSource(): string {\n\treturn [\n\t\t`const assemble = ${assembleGeometries.toString()};`,\n\t\t`self.onmessage = (event) => {`,\n\t\t` const { id, input } = event.data;`,\n\t\t` try {`,\n\t\t` const geometries = assemble(input);`,\n\t\t` const transfer = [];`,\n\t\t` for (const g of geometries) {`,\n\t\t` transfer.push(g.positions.buffer, g.normals.buffer, g.indices.buffer);`,\n\t\t` if (g.uvs) transfer.push(g.uvs.buffer);`,\n\t\t` if (g.colors) transfer.push(g.colors.buffer);`,\n\t\t` }`,\n\t\t` self.postMessage({ id, geometries }, transfer);`,\n\t\t` } catch (error) {`,\n\t\t` self.postMessage({ id, error: String((error && error.message) || error) });`,\n\t\t` }`,\n\t\t`};`\n\t].join('\\n');\n}\n","import * as THREE from 'three';\n\nimport { applyOffset, computeCombinedBoundingBox } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\n\nimport { parseDisplayItems } from '../display-items/display-items-parser.js';\n\nimport { parseMeshBatchObject } from './batch-parser.js';\n\nimport type { DataItem, GrasshopperComputeResponse } from '@/features/grasshopper/types';\nimport type { DisplayBatch, MeshExtractionOptions, MeshBatchParsingOptions } from './types.js';\nimport type { RhinoModule } from 'rhino3dm';\n\n// Constants\n\n/**\n * Metres per model unit, keyed by Rhino `UnitSystem` name (the `modelunits` string on the compute\n * response). Imperial factors are the exact international definitions (1 in = 0.0254 m,\n * 1 ft = 0.3048 m, 1 mi = 1609.344 m). Units not in this table scale 1 and log a one-time warning\n * — see {@link getScaleFactor}.\n */\nexport const SCALE_FACTORS: Record<string, number> = {\n\t// Metric\n\tAngstroms: 1e-10,\n\tNanometers: 1e-9,\n\tMicrons: 1e-6,\n\tMillimeters: 1e-3,\n\tCentimeters: 1e-2,\n\tDecimeters: 0.1,\n\tMeters: 1,\n\tDekameters: 10,\n\tHectometers: 100,\n\tKilometers: 1000,\n\tMegameters: 1e6,\n\tGigameters: 1e9,\n\t// Imperial (exact: 1 inch = 0.0254 m)\n\tMicroinches: 0.0254e-6,\n\tMils: 0.0254e-3,\n\tInches: 0.0254,\n\tFeet: 0.3048,\n\tYards: 0.9144,\n\tMiles: 1609.344,\n\tNauticalMiles: 1852\n};\n\n/**\n * Wire `type` token identifying a Selva Display payload. The real wire value is namespaced (e.g.\n * `Selva.GH.Features.Display.Services.DisplayBatch`), so dispatch matches exact dot-separated\n * tokens — never substrings, which would misroute any unrelated type merely containing \"Display\".\n */\nconst DISPLAY_COMPONENT_TYPE = 'Display';\nconst DISPLAY_BATCH_TYPE = 'DisplayBatch';\n\n/**\n * True when a wire `type` denotes a Display payload: one of its dot-separated tokens is exactly\n * `Display` or `DisplayBatch`. Matches the bare `Display` used by older servers and the namespaced\n * `Selva.GH.Features.Display.Services.DisplayBatch`, but not e.g. `System.DisplayText`.\n */\nfunction isDisplayItemType(type: string): boolean {\n\tconst tokens = type.split('.');\n\treturn tokens.includes(DISPLAY_COMPONENT_TYPE) || tokens.includes(DISPLAY_BATCH_TYPE);\n}\n\n/** Unknown-unit names already warned about, so a per-solve parse doesn't spam the log. */\nconst warnedUnknownUnits = new Set<string>();\n\n/**\n * Extracts and processes display meshes from a ComputePointerResponse using the Grasshopper WebDisplay component.\n *\n * This is the primary entry point for extracting mesh geometry from Grasshopper compute responses.\n * It handles all aspects of mesh processing: decompression, coordinate transformation, scaling, and positioning.\n *\n * **Note:** The entire pipeline (base64 decode, inflate, dequantization, mesh construction) runs\n * synchronously on the calling thread — large batches will block the UI for their duration. The\n * function is `async` only so its shape can stay stable if parsing moves off-thread later.\n *\n * @param data - The ComputePointerResponse containing Grasshopper output trees.\n * @param options - Configuration for mesh extraction and parsing behavior. All options are optional with sensible defaults.\n * @returns Promise resolving to array of THREE.Mesh objects (may be empty).\n * @throws Rethrows unexpected errors after attempting to dispose any created meshes.\n *\n * @remarks\n * - Only works with the WebDisplay component of GHHeadless.\n * - Requires changes to Rhino.Compute (see https://github.com/TheVessen/compute.rhino3d).\n * - Provides a performant way to display mesh data in Three.js.\n * - All decoding is synchronous on the main thread; there is no Web Worker offload today.\n * - Supports mesh metadata (names, user data) if provided in the compute response.\n *\n * @internal Internal helper: high-level extraction remains public via visualization module, but this\n * function is considered internal implementation detail for mesh extraction.\n *\n * @example\n * ```ts\n * // Simple usage with defaults (all processing enabled)\n * const meshes = await getThreeMeshesFromComputeResponse(response);\n *\n * // With debugging enabled\n * const meshes = await getThreeMeshesFromComputeResponse(response, { debug: true });\n *\n * // Opt in to seating the model on the grid instead of using its Rhino coordinates\n * const meshes = await getThreeMeshesFromComputeResponse(response, {\n * debug: true,\n * allowScaling: true,\n * allowAutoPosition: true,\n * parsing: {\n * mergeByMaterial: false,\n * applyTransforms: true,\n * debug: true,\n * },\n * });\n * ```\n */\nexport async function getThreeMeshesFromComputeResponse(\n\tdata: GrasshopperComputeResponse,\n\toptions?: MeshExtractionOptions\n): Promise<THREE.Object3D[]> {\n\tconst startTime = performance.now();\n\tconst objects: THREE.Object3D[] = [];\n\n\tconst {\n\t\tallowScaling = true,\n\t\t// Defaults to FALSE: geometry renders where Rhino puts it. Grounding used to be on by\n\t\t// default here but was never applied on the WebSocket preview path, so the same definition\n\t\t// sat at a different height depending on transport. Rhino coordinates are the honest frame —\n\t\t// the viewer agrees with the Grasshopper definition, and picked/measured coordinates match.\n\t\tallowAutoPosition = false,\n\t\tgroundAxis = 'z',\n\t\trhino,\n\t\tdebug = false,\n\t\tparsing: parsingOptions = {}\n\t} = options ?? {};\n\n\ttry {\n\t\tconst scaleFactor = allowScaling ? getScaleFactor(data.modelunits) : 1;\n\t\tawait extractDisplayFromData(data, objects, scaleFactor, parsingOptions, rhino, debug);\n\n\t\tif (allowAutoPosition) {\n\t\t\tapplyGroundOffset(objects, groundAxis);\n\t\t}\n\n\t\treturn objects;\n\t} catch (error) {\n\t\thandleError(error, objects);\n\t\tthrow error;\n\t} finally {\n\t\tif (debug) {\n\t\t\tlogProcessingTime(startTime);\n\t\t}\n\t}\n}\n\n/**\n * Gets the metres-per-unit scale factor for the given Rhino unit name. Unknown units fall back to\n * 1 (no scaling) with a one-time warning per unit name — a kilometers model rendering 1000× off\n * should at least say why.\n */\nfunction getScaleFactor(modelUnits: string): number {\n\tconst factor = SCALE_FACTORS[modelUnits];\n\tif (factor !== undefined) {\n\t\treturn factor;\n\t}\n\tif (!warnedUnknownUnits.has(modelUnits)) {\n\t\twarnedUnknownUnits.add(modelUnits);\n\t\tgetLogger().warn(\n\t\t\t`Unknown Rhino model unit \"${modelUnits}\" — geometry will not be scaled (factor 1). ` +\n\t\t\t\t`Known units: ${Object.keys(SCALE_FACTORS).join(', ')}.`\n\t\t);\n\t}\n\treturn 1;\n}\n\n/**\n * Extracts meshes and non-mesh display items (curves, points) from compute response data.\n */\nasync function extractDisplayFromData(\n\tdata: GrasshopperComputeResponse,\n\tobjects: THREE.Object3D[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\trhino: RhinoModule | undefined,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const value of data.values) {\n\t\tconst innerTree = value.InnerTree as { [key: string]: DataItem[] };\n\n\t\tfor (const path in innerTree) {\n\t\t\tconst branch = innerTree[path];\n\t\t\tif (!branch) continue;\n\n\t\t\tawait processDataBranch(branch, objects, scaleFactor, parsingOptions, rhino, debug);\n\t\t}\n\t}\n}\n\n/**\n * Processes a single data branch to extract a DisplayBatch's meshes (binary blob) and items\n * (curves/points JSON). Both get the same unit scale so they share one frame.\n */\nasync function processDataBranch(\n\tbranch: DataItem[],\n\tobjects: THREE.Object3D[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\trhino: RhinoModule | undefined,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const item of branch) {\n\t\tif (!isDisplayItemType(item.type)) continue;\n\n\t\tconst mergedParsingOptions = {\n\t\t\tmergeByMaterial: true,\n\t\t\tapplyTransforms: true,\n\t\t\tdebug: false,\n\t\t\t...parsingOptions\n\t\t};\n\n\t\t// Parse the JSON envelope once — it contains the full multi-MB base64 SLVA blob as a string,\n\t\t// so letting the mesh parser and the display-item extractor each parse it doubles both the\n\t\t// synchronous main-thread CPU and the transient string memory.\n\t\tconst batch = extractBatch(item.data);\n\t\tif (!batch) {\n\t\t\tgetLogger().error('Error parsing display batch envelope: invalid JSON');\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst batchMeshes = await parseMeshBatchObject(batch, mergedParsingOptions);\n\n\t\tconst batchItems = parseDisplayItems(batch.items, {\n\t\t\trhino,\n\t\t\tapplyTransforms: mergedParsingOptions.applyTransforms\n\t\t});\n\n\t\tconst batchObjects: THREE.Object3D[] = [...batchMeshes, ...batchItems];\n\n\t\tif (scaleFactor !== 1) {\n\t\t\tfor (const obj of batchObjects) {\n\t\t\t\tobj.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t}\n\t\t}\n\n\t\tobjects.push(...batchObjects);\n\n\t\tif (debug) {\n\t\t\tgetLogger().debug(\n\t\t\t\t`Extracted ${batchMeshes.length} meshes and ${batchItems.length} items from batch`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Resolves a raw DisplayBatch payload to a parsed object, tolerating either a parsed object or a\n * JSON string (the blob-bearing `item.data` is the same envelope the mesh parser reads).\n */\nfunction extractBatch(data: unknown): DisplayBatch | undefined {\n\treturn typeof data === 'string' ? safeParse(data) : (data as DisplayBatch | undefined);\n}\n\nfunction safeParse(s: string): DisplayBatch | undefined {\n\ttry {\n\t\treturn JSON.parse(s) as DisplayBatch;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Drops objects so their lowest point sits on the ground plane. `axis` is the scene's up axis —\n * `z` for the default Rhino frame geometry arrives in (see ../coordinate-transform.ts). Taking it\n * as a parameter rather than hardcoding `z` keeps grounding correct for a host that configures a\n * different `sceneUp`, where subtracting `min.z` would shove content sideways instead of down.\n */\nfunction applyGroundOffset(meshes: THREE.Object3D[], axis: 'x' | 'y' | 'z'): void {\n\tif (meshes.length === 0) return;\n\n\tconst combinedBoundingBox = computeCombinedBoundingBox(meshes);\n\tapplyOffset(meshes, combinedBoundingBox.min[axis], axis);\n}\n\n/**\n * Handles errors by disposing created objects and logging.\n */\nfunction handleError(error: unknown, meshes: THREE.Object3D[]): void {\n\tgetLogger().error('An unexpected error occurred:', error);\n\tdisposeMeshes(meshes);\n}\n\n/**\n * Disposes of all objects (meshes, lines, points) and their associated resources.\n */\nfunction disposeMeshes(meshes: THREE.Object3D[]): void {\n\tfor (const obj of meshes) {\n\t\tconst mesh = obj as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (mesh.geometry) {\n\t\t\tmesh.geometry.dispose();\n\t\t}\n\n\t\tif (mesh.material) {\n\t\t\tif (Array.isArray(mesh.material)) {\n\t\t\t\tmesh.material.forEach((material) => material.dispose());\n\t\t\t} else {\n\t\t\t\tmesh.material.dispose();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Logs the processing time for mesh extraction.\n */\nfunction logProcessingTime(startTime: number): void {\n\tconst elapsed = performance.now() - startTime;\n\tgetLogger().info('Time to process meshes:', `${elapsed.toFixed(2)}ms`);\n}\n"],"mappings":"gFAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,uBAAAE,GAAA,sBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,qBAAAC,GAAA,oBAAAC,GAAA,qBAAAC,GAAA,kBAAAC,KAAA,UAAYC,MAAW,QAEhB,IAAMP,GAAoB,IAAU,uBAA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,EAExBzB,GACHW,EAAU,EAAE,MACX,aAAaU,EAAY,MAAM,eAAeE,EAAW,MAAM,mBAChE,CAEF,CACD,CAMA,SAASH,GAAa5B,EAAyC,CAC9D,OAAO,OAAOA,GAAS,SAAWmC,GAAUnC,CAAI,EAAKA,CACtD,CAEA,SAASmC,GAAUC,EAAqC,CACvD,GAAI,CACH,OAAO,KAAK,MAAMA,CAAC,CACpB,MAAQ,CACP,MACD,CACD,CAQA,SAASvB,GAAkBwB,EAA0BC,EAA6B,CACjF,GAAID,EAAO,SAAW,EAAG,OAEzB,IAAME,EAAsBC,GAA2BH,CAAM,EAC7DI,GAAYJ,EAAQE,EAAoB,IAAID,CAAI,EAAGA,CAAI,CACxD,CAKA,SAASvB,GAAYD,EAAgBuB,EAAgC,CACpElB,EAAU,EAAE,MAAM,gCAAiCL,CAAK,EACxD4B,GAAcL,CAAM,CACrB,CAKA,SAASK,GAAcL,EAAgC,CACtD,QAAWH,KAAOG,EAAQ,CACzB,IAAMM,EAAOT,EACTS,EAAK,UACRA,EAAK,SAAS,QAAQ,EAGnBA,EAAK,WACJ,MAAM,QAAQA,EAAK,QAAQ,EAC9BA,EAAK,SAAS,QAASC,GAAaA,EAAS,QAAQ,CAAC,EAEtDD,EAAK,SAAS,QAAQ,EAGzB,CACD,CAKA,SAAS3B,GAAkBd,EAAyB,CACnD,IAAM2C,EAAU,YAAY,IAAI,EAAI3C,EACpCiB,EAAU,EAAE,KAAK,0BAA2B,GAAG0B,EAAQ,QAAQ,CAAC,CAAC,IAAI,CACtE","names":["three_materials_exports","__export","CONCRETE_MATERIAL","EMISSIVE_MATERIAL","GLASS_MATERIAL","METAL_MATERIAL","PLASTIC_MATERIAL","RUBBER_MATERIAL","SHARED_MATERIALS","WOOD_MATERIAL","THREE","THREE","buildUpBasis","up","u","worldZ","worldY","seed","right","forward","isoOffset","distance","sunOffset","sideDistance","height","environmentRotationFor","mapZenith","quaternion","upToAxis","ax","ay","az","THREE","CAMERA_CONFIG","updateScene","scene","meshes","camera","controls","initialPositionSet","clearScene","mesh","unionBoundingBox","computeCombinedBoundingBox","center","size","maxDim","distance","isoOffset","parseColor","colorString","getLogger","trimmed","hex","rgb","c","n","named","applyOffset","offset","axis","combinedBoundingBox","bbox","VIEWER_AID_IDS","isViewerAid","object","current","computeContentBounds","box","renderable","PERSISTENT_SCENE_IDS","CACHED_GEOMETRY_USERDATA_FLAG","child","material","SHARED_MATERIALS","value","THREE","buildViewDirections","up","u","forward","right","buildUpBasis","frontPosition","rightPosition","createCameraController","deps","scene","perspective","controls","onActiveCameraChange","VIEW_DIRECTIONS","ortho","projection","aspect","active","activeTween","cancelTween","syncOrthoFrustum","halfH","halfW","setProjection","next","distance","direction","frame","center","maxDim","animate","fov","dir","nudgeOffPole","toPosition","cam","animateMove","setViewDirection","box","computeContentBounds","size","preset","enabled","width","height","d","inPlane","tilt","easeOut","t","camera","toTarget","onTick","durationMs","fromPosition","fromTarget","startTime","rafId","tick","THREE","niceStep","value","exponent","power","mantissa","GRID_VERTEX","GRID_FRAGMENT","createGrid","options","cellSize","majorEvery","cellColor","majorColor","fadeDistance","plane","axes","PLANE_TO_FADE_RATIO","geometry","material","mesh","fadeRadius","planeScale","center","cameraPosition","bounds","sizeVec","axisComponent","v","i","inPlaneExtent","TARGET_CELLS_ACROSS","visible","THREE","ViewHelper","createViewGizmo","deps","camera","domElement","controller","helper","visible","DIM","raycaster","gizmoCamera","AXIS_DIRECTIONS","pickAxis","event","rect","offsetX","offsetY","mouse","hits","hit","type","renderer","prevAutoClear","axis","value","THREE","LineSegmentsGeometry","LineSegments2","LineMaterial","extractEdgeSegments","positions","index","thresholdAngleDeg","thresholdDot","vertexCount","quantX","quantY","quantZ","v","capacity","mask","table","canonical","slot","existing","out","outLength","emit","i0","i1","grown","edgeSlots","pendingIndex0","pendingIndex1","pendingNormals","triCount","t","i2","a","b","c","e0x","e0y","e0z","e1x","e1y","e1z","nx","ny","nz","lengthSq","inverseLength","j","from","to","fromCanonical","toCanonical","reverseKey","reverseSlot","forwardKey","edgeExtractWorkerSource","EDGE_USERDATA_KIND","EDGES_SKIPPED_TRIANGLE_CAP","DEFAULT_EDGE_COLOR","DEFAULT_EDGE_WIDTH","DEFAULT_THRESHOLD_ANGLE","DEFAULT_DARKEN","DEFAULT_MAX_TRIANGLES","DEFAULT_MAX_SEGMENTS","INLINE_TRIANGLE_BUDGET","SEGMENT_CACHE_BYTE_BUDGET","FADE_START_PX","FADE_END_PX","EDGE_OFFSET_FACTOR","EDGE_OFFSET_UNITS","triangleCountOf","geometry","position","fastPathData","index","contentKey","data","thresholdAngle","hash","mix","word","words","head","i","indexLength","headIndex","segmentCache","segmentCacheBytes","segmentCacheGet","key","cached","segmentCachePut","segments","existing","oldestKey","extractViaThree","edges","positions","extractSegmentsSync","extractEdgeSegments","extractionWorker","pendingRequests","nextRequestId","getExtractionWorker","url","edgeExtractWorkerSource","worker","event","id","error","pending","extractInWorker","resolve","reject","transfer","inFlightExtractions","extractSegmentsAsync","inFlight","request","SPACING_PERCENTILE","SPACING_SAMPLE_LIMIT","edgeSpacingOf","segmentCount","stride","lengths","s","length","b","edgeGeometryCache","cachedEntry","storeEntry","byAngle","lineGeometry","LineSegmentsGeometry","entry","releaseEdgeGeometry","overlay","userData","resolveOptions","options","deriveEdgeColor","mesh","darken","source","MaterialPool","__publicField","fade","color","material","createEdgeMaterial","created","used","width","distanceFade","LineMaterial","buildEdgeOverlay","sourceGeometry","LineSegments2","enableDistanceFade","_fadeCenter","_fadeCameraPos","pixelsPerWorldUnit","camera","viewportHeightPx","sphere","perspective","distance","radius","tanHalfFov","worldHeightAtCentre","ortho","worldHeight","edgeSpacing","renderer","_scene","scale","gapPx","isEdgeOverlay","object","collectTargets","root","maxTriangles","targets","c","attachOverlay","materials","resolved","addEdges","rootGenerations","generationOf","isConnected","node","addEdgesAsync","generation","attaches","removeEdges","overlays","THREE","Pass","FullScreenQuad","EDGE_SHADER","EdgeDetectionPass","Pass","scene","camera","width","height","options","__publicField","uniforms","FullScreenQuad","depthTexture","renderer","writeBuffer","readBuffer","normalTarget","previousTarget","previousAutoClear","previousClearColor","previousClearAlpha","previousOverride","perspective","EffectComposer","RenderPass","GTAOPass","SMAAPass","OutputPass","createRenderPipeline","renderer","scene","camera","width","height","options","composer","EffectComposer","renderPass","RenderPass","gtaoPass","GTAOPass","edgeOptions","edgePass","EdgeDetectionPass","smaaPass","SMAAPass","outputPass","OutputPass","aoPixelRatioCap","deltaTime","w","h","pixelRatio","cam","isPerspective","enabled","THREE","CSS2DRenderer","CSS2DObject","createLabelLayer","container","scene","renderer","dom","size","group","labels","text","position","className","el","object","p","t","camera","width","height","THREE","Line2","LineGeometry","LineMaterial","DEFAULT_SNAP_PIXELS","DEFAULT_COLOR","LINE_PICK_FRACTION","UNIT_DISPLAY","makeFormatter","displayUnit","unit","meters","pickThreshold","camera","viewTarget","ortho","snapCandidateIndices","hit","obj","index","snapToVertex","screenSize","snapPixels","raw","indices","pos","toScreen","worldP","ndc","rawScreen","best","bestPx","idx","world","px","createMeasureTool","deps","canvas","scene","getActiveCamera","getViewTarget","labelLayer","options","color","fmt","defaultFormat","d","delta","format","raycaster","pointer","enabled","points","markers","line","label","markerMaterial","hoverMaterial","hoverMarker","showHover","p","geometry","makeMarker","marker","clear","m","drawMeasurement","a","b","material","mid","pickPoint","event","rect","threshold","hits","i","pendingMove","moveRaf","cancelPendingMove","value","point","latest","THREE","TEXTURE_CACHE_MAX_ENTRIES","MAX_KEY_LENGTH","textureCache","inFlight","cacheGeneration","StaleTextureLoadError","url","maxAnisotropy","setTextureAnisotropy","value","texture","applyTextureMap","material","key","cacheKeyFor","cached","loadTexture","error","getLogger","clearTextureCache","fnv1aString","s","hash","i","storeTexture","oldestKey","evicted","pending","generation","resolve","reject","THREE","OrbitControls","HDRLoader","THREE","NEAR_GAP_FRACTION","MAX_NEAR_TO_FAR","APPLY_THRESHOLD","NO_GROUND_NORMALS","createNearPlaneFitter","camera","scene","groundNormals","baseNear","appliedNear","center","size","bounds","computeContentBounds","near","radius","gap","normal","defaultUp","DEFAULT_LOOK","LOOK_PRESETS","materialAppearanceForLook","look","preset","initThree","canvas","options","config","applyDefaults","sceneUp","pixelRatio","scene","createScene","camera","createCamera","renderer","setupRenderer","setTextureAnisotropy","controls","setupControls","cameraController","createCameraController","getActiveCamera","disposed","setupEnvironment","lights","setupLighting","sunlight","updateShadowBounds","fitShadowToContent","computeContentBounds","addFloor","floorMesh","child","grid","createGrid","updateGridScale","gizmo","createViewGizmo","gridPlane","upToAxis","gridNormal","floorNormal","groundNormals","normals","nearFitter","createNearPlaneFitter","labelContainer","labelLayer","createLabelLayer","measureTool","createMeasureTool","eventHandlers","setupEventHandlers","DRAG_SLOP_PX","pressX","pressY","handlePointerDown","event","wasDrag","handleToolClick","handleToolMove","requestRender","applyEdges","root","addEdgesAsync","updateEdgeFallback","hasSkippedMeshes","object","EDGES_SKIPPED_TRIANGLE_CAP","edgeFallbackActive","syncPipeline","clearEdges","removeEdges","parent","getCanvasSize","renderPipeline","aoEnabled","builtWithAo","buildPipeline","withAo","width","height","pipeline","createRenderPipeline","rebuildPipeline","setAmbientOcclusion","enabled","setFillLights","opts","setEnvironmentIntensity","intensity","setToneMappingExposure","exposure","setAoIntensity","setLook","activeLook","mesh","materials","material","getMaterialAppearance","animate","disposeAnimation","invalidate","createAnimationLoop","disposeObjectTree","renderable","disposeMaterialWithTextures","addUserGeometry","removeUserGeometry","clearUserGeometry","scale","defaults","isoOffset","sunOffset","value","light","bounds","center","radius","cam","lightDistance","bgColor","onFrame","getRenderPipeline","onDemand","animationId","lastTime","renderRequested","lastRenderTime","IDLE_REPAINT_INTERVAL_MS","lastWorldMatrix","lastProjectionMatrix","lastCamera","cameraMoved","activeCamera","moved","pointerEvents","type","checkResize","newW","newH","now","delta","isDisposed","HDRLoader","envMap","getLogger","pmrem","prefiltered","envRotation","environmentRotationFor","error","ambient","hemisphere","up","pos","floorSize","floorGeometry","floorColor","floorMaterial","floor","selectedObjects","originalMaterials","raycaster","mouse","mouseDownPosition","isFullyVisible","current","fitToView","box","selectionColorObj","clearSelection","obj","restorable","original","clone","m","applyHighlight","target","updatePickThresholds","diagonal","handleMouseDown","handleCanvasClick","currentMousePosition","rect","intersects","i","clickedObject","handleDoubleClick","handleKeydown","OrbitControls","LOOKS","THREE","Line2","LineGeometry","LineMaterial","rhinoToThree","x","y","z","_apply","DEFAULT_COLOR","CURVE_INITIAL_SEGMENTS","CURVE_CHORD_TOLERANCE_RATIO","CURVE_MAX_SUBDIVISION_DEPTH","CURVE_MAX_TURN_RADIANS","parseDisplayItems","items","options","rhino","applyTransforms","objects","item","line","buildCurveLine","point","buildPoint","unknown","getLogger","DEFAULT_LINE_WIDTH","curve","decodeCurve","points","tessellate","error","deleteRhinoObject","positions","p","geometry","LineGeometry","params","materialParams","material","LineMaterial","styled","Line2","position","x","y","z","rhinoToThree","obj","json","parsed","exact","tryPolylineVertices","sampleUniform","result","polyline","out","i","domain","t0","span","evalAt","t","tolerance","chordTolerance","ta","pa","tb","pb","subdivide","depth","tm","pm","deviation","distanceToSegment","turn","turnAngle","box","min","max","diagonal","a","b","c","abx","aby","abz","bcx","bcy","bcz","lenAb","lenBc","dot","cos","lengthSq","apx","apy","apz","dx","dy","dz","color","opacity","resolved","inflateSync","BINARY_MESH_MAGIC","COMPRESSED_MESH_MAGIC","BINARY_MESH_VERSION","MIN_SUPPORTED_VERSION","FLAG_FLOAT32","FLAG_UINT16_INDICES","FLAG_DELTA_ENCODED","FLAG_HAS_UVS","FLAG_HAS_VERTEX_COLORS","UV_FORMAT_UINT16","UV_FORMAT_FLOAT32","HEADER_PREAMBLE_BYTES","GEOMETRY_HEADER_BYTES","HOST_IS_LITTLE_ENDIAN","parseBinaryMeshBatch","input","raw","parseBinaryMeshBatchRaw","vertices","decodeDeltaVertices","indices","decodeDeltaIndices16","decodeDeltaIndices32","validateIndicesInRange","RhinoComputeError","ErrorCodes","bytes","maybeDecompress","toUint8Array","view","fail","offset","magic","version","metadataLen","metadataBytes","metadata","decodeUtf8","error","flags","originX","originY","originZ","scaleX","scaleY","scaleZ","vertexCount","useFloat32","deltaEncoded","componentCount","verticesByteLength","absoluteOffset","vertexData","readFloat32Vertices","readUint16Array","readInt16Vertices","indexCount","useUint16Indices","indicesByteLength","indexData","readUint32Array","uvs","parsed","parseUvChunk","colors","parseColorChunk","UV_CHUNK_HEADER_BYTES","uvFormat","originU","originV","scaleU","scaleV","dataByteLength","qu","qv","i","unzigzag","byteLength","r","g","b","decodeBase64ToBinary","uncompressedLen","deflated","maxPlausibleLen","out","inflateSync","buffer","byteOffset","count","copy","zz","zigzagged","px","py","pz","prev","message","context","THREE","GEOMETRY_CACHE_BYTE_BUDGET","SAMPLE_WORDS","cache","cacheBytes","fingerprintViews","parts","salt","hash","mix","word","i","part","byteLength","words","head","bytes","bytesOf","geometry","total","attribute","geometryCacheGet","key","entry","geometryCachePut","CACHED_GEOMETRY_USERDATA_FLAG","oldestKey","oldest","assembleGeometries","input","isFloat32","deltaEncoded","origin","scale","uvs","colors","jobs","unzigzag","zz","worldVertices","quantized","zigzagged","px","py","pz","i","ox","oy","oz","sx","sy","sz","indices","out","prev","totalVertexCount","SAMPLE_WORDS","fingerprint","parts","salt","hash","mix","word","part","byteLength","words","head","bytes","keyFor","kind","windows","window","componentStart","componentEnd","results","job","vertexTotal","indexTotal","positions","outIndices","outUvs","outColors","vertexCursor","indexCursor","windowStart","windowEnd","shift","indexValue","normals","a","b","c","cbx","cby","cbz","abx","aby","abz","nx","ny","nz","x","y","z","length","meshAssemblyWorkerSource","parseMeshBatch","batchJson","options","debug","perfStart","batch","parseStart","error","getLogger","parseTime","parseMeshBatchObject","telemetry","mergeByMaterial","applyTransforms","material","workerMeshes","tryBuildViaWorker","decodeStart","parsed","parseBinaryMeshBatch","decodeTime","blobBytes","approximateBase64DecodedBytes","buildMeshesFromParsed","parseMeshBatchBlob","blob","opts","materialAppearance","fallback","materialsSrc","groups","sourceComponentId","isFloat32","FLAG_FLOAT32","validateGroupMetadata","worldVertices","maybeRotateFloat32Vertices","dequantizeInt16","wireBytes","meshCreateStart","materials","m","createMaterial","meshes","group","mergedMesh","createMergedMesh","individualMeshes","createIndividualMeshes","mesh","meshCreateTime","totalTime","metadataFail","message","context","RhinoComputeError","ErrorCodes","materialCount","totalVertexCount","totalIndexCount","fields","field","value","indexOutOfWindow","indexValue","meshMeta","geometryContentKey","kind","allVertices","allIndices","allUvs","allColors","parts","salt","componentStart","componentEnd","fingerprintViews","q","origin","scale","_applyCoordinateTransform","out","ox","oy","oz","sx","sy","sz","i","vertices","ASSEMBLY_WORKER_MIN_TRIANGLES","assemblyWorker","pendingAssemblies","nextAssemblyRequestId","getAssemblyWorker","url","meshAssemblyWorkerSource","worker","event","id","geometries","pending","requestAssembly","input","transfer","resolve","reject","raw","parseBinaryMeshBatchRaw","windowOf","jobs","jobRefs","vertexData","indexData","assembled","result","ref","geometry","geometryCacheGet","geometryCachePut","finalizeMergedMesh","finalizeSingleMesh","METAL_CLEARCOAT_THRESHOLD","METAL_CLEARCOAT","METAL_CLEARCOAT_ROUGHNESS","matData","color","parseColor","vertexColors","appearance","applyVertexColorSRGBDecode","applyTextureMap","shader","cacheKey","mergedVertices","mergedIndices","mergedUvs","mergedColors","vertexWriteCursor","indexWriteCursor","componentLen","uvStart","indicesSlice","indexShift","windowStart","windowEnd","threeMesh","firstMesh","meshNames","name","rebasedIndices","baseIndex","uvs","colors","base64","SCALE_FACTORS","DISPLAY_COMPONENT_TYPE","DISPLAY_BATCH_TYPE","isDisplayItemType","type","tokens","warnedUnknownUnits","getThreeMeshesFromComputeResponse","data","options","startTime","objects","allowScaling","allowAutoPosition","groundAxis","rhino","debug","parsingOptions","scaleFactor","getScaleFactor","extractDisplayFromData","applyGroundOffset","error","handleError","logProcessingTime","modelUnits","factor","getLogger","value","innerTree","path","branch","processDataBranch","item","mergedParsingOptions","batch","extractBatch","batchMeshes","parseMeshBatchObject","batchItems","parseDisplayItems","batchObjects","obj","safeParse","s","meshes","axis","combinedBoundingBox","computeCombinedBoundingBox","applyOffset","disposeMeshes","mesh","material","elapsed"]}
|