@selvajs/compute 3.1.0-beta.6 → 3.1.0-beta.7
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/dist/chunk-AGU3SX3J.cjs +62 -0
- package/dist/chunk-AGU3SX3J.cjs.map +1 -0
- package/dist/chunk-EQ7EMYF6.js +62 -0
- package/dist/chunk-EQ7EMYF6.js.map +1 -0
- package/dist/{chunk-JNFNLKFO.js → chunk-VZK5OUII.js} +2 -2
- package/dist/{chunk-Y5E6RIEH.cjs → chunk-WSOTCJIQ.cjs} +2 -2
- package/dist/{chunk-Y5E6RIEH.cjs.map → chunk-WSOTCJIQ.cjs.map} +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/visualization-ET5JQHLQ.cjs +2 -0
- package/dist/{visualization-36IV2CVU.cjs.map → visualization-ET5JQHLQ.cjs.map} +1 -1
- package/dist/{visualization-QCI36RHC.js → visualization-I6ZHBKFN.js} +2 -2
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-727SRM4E.cjs +0 -62
- package/dist/chunk-727SRM4E.cjs.map +0 -1
- package/dist/chunk-CWODTGNH.js +0 -62
- package/dist/chunk-CWODTGNH.js.map +0 -1
- package/dist/visualization-36IV2CVU.cjs +0 -2
- /package/dist/{chunk-JNFNLKFO.js.map → chunk-VZK5OUII.js.map} +0 -0
- /package/dist/{visualization-QCI36RHC.js.map → visualization-I6ZHBKFN.js.map} +0 -0
package/dist/visualization.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkAGU3SX3Jcjs = require('./chunk-AGU3SX3J.cjs');require('./chunk-CUQQ3ZBV.cjs');exports.EDGE_USERDATA_KIND = _chunkAGU3SX3Jcjs.i; exports.Materials = _chunkAGU3SX3Jcjs.a; exports.SCALE_FACTORS = _chunkAGU3SX3Jcjs.L; exports.addEdges = _chunkAGU3SX3Jcjs.j; exports.applyOffset = _chunkAGU3SX3Jcjs.d; exports.computeCombinedBoundingBox = _chunkAGU3SX3Jcjs.e; exports.createCameraController = _chunkAGU3SX3Jcjs.f; exports.createGrid = _chunkAGU3SX3Jcjs.g; exports.createLabelLayer = _chunkAGU3SX3Jcjs.n; exports.createMeasureTool = _chunkAGU3SX3Jcjs.p; exports.createRenderPipeline = _chunkAGU3SX3Jcjs.m; exports.createViewGizmo = _chunkAGU3SX3Jcjs.h; exports.getThreeMeshesFromComputeResponse = _chunkAGU3SX3Jcjs.M; exports.initThree = _chunkAGU3SX3Jcjs.u; exports.isEdgeOverlay = _chunkAGU3SX3Jcjs.k; exports.parseColor = _chunkAGU3SX3Jcjs.c; exports.parseDisplayItems = _chunkAGU3SX3Jcjs.v; exports.parseMeshBatchBlob = _chunkAGU3SX3Jcjs.K; exports.parseMeshBatchObject = _chunkAGU3SX3Jcjs.J; exports.removeEdges = _chunkAGU3SX3Jcjs.l; exports.snapToVertex = _chunkAGU3SX3Jcjs.o; exports.updateScene = _chunkAGU3SX3Jcjs.b;
|
|
2
2
|
//# sourceMappingURL=visualization.cjs.map
|
package/dist/visualization.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{J as h,K as c,L as v,M as j,a as e,b as r,c as t,d as o,e as i,f as a,g as s,h as p,i as n,j as l,k as f,l as m,m as y,n as u,o as d,p as x,u as C,v as g}from"./chunk-
|
|
1
|
+
import{J as h,K as c,L as v,M as j,a as e,b as r,c as t,d as o,e as i,f as a,g as s,h as p,i as n,j as l,k as f,l as m,m as y,n as u,o as d,p as x,u as C,v as g}from"./chunk-EQ7EMYF6.js";import"./chunk-WPB2LKCD.js";export{n as EDGE_USERDATA_KIND,e as Materials,v as SCALE_FACTORS,l as addEdges,o as applyOffset,i as computeCombinedBoundingBox,a as createCameraController,s as createGrid,u as createLabelLayer,x as createMeasureTool,y as createRenderPipeline,p as createViewGizmo,j as getThreeMeshesFromComputeResponse,C as initThree,f as isEdgeOverlay,t as parseColor,g as parseDisplayItems,c as parseMeshBatchBlob,h as parseMeshBatchObject,m as removeEdges,d as snapToVertex,r as updateScene};
|
|
2
2
|
//# sourceMappingURL=visualization.js.map
|
package/package.json
CHANGED
package/dist/chunk-727SRM4E.cjs
DELETED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkCUQQ3ZBVcjs = require('./chunk-CUQQ3ZBV.cjs');var Rt={};_chunkCUQQ3ZBVcjs.a.call(void 0, Rt,{CONCRETE_MATERIAL:()=>De,EMISSIVE_MATERIAL:()=>Le,GLASS_MATERIAL:()=>Pe,METAL_MATERIAL:()=>Ie,PLASTIC_MATERIAL:()=>Oe,RUBBER_MATERIAL:()=>Be,SHARED_MATERIALS:()=>ge,WOOD_MATERIAL:()=>Ve});var _three = require('three'); var O = _interopRequireWildcard(_three); var U = _interopRequireWildcard(_three); var z = _interopRequireWildcard(_three); var k = _interopRequireWildcard(_three); var W = _interopRequireWildcard(_three); var re = _interopRequireWildcard(_three); var We = _interopRequireWildcard(_three); var D = _interopRequireWildcard(_three); var fe = _interopRequireWildcard(_three); var E = _interopRequireWildcard(_three); var $ = _interopRequireWildcard(_three); var P = _interopRequireWildcard(_three);var Le=new O.MeshPhysicalMaterial({color:0,emissive:new O.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:O.FrontSide,dithering:!0}),Ie=new O.MeshPhysicalMaterial({color:new O.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:O.FrontSide,dithering:!0}),De=new O.MeshPhysicalMaterial({color:new O.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:O.FrontSide,dithering:!0}),Oe=new O.MeshPhysicalMaterial({color:new O.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:O.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Pe=new O.MeshPhysicalMaterial({color:new O.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,depthWrite:!1,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:O.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Be=new O.MeshPhysicalMaterial({color:new O.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:O.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ve=new O.MeshPhysicalMaterial({color:new O.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:O.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ge=new Set([Le,Ie,De,Oe,Pe,Be,Ve]);var q={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Br(e,n,t,r,i){if(wt(e),n.length===0)return;n.forEach(d=>{e.add(d)});let o=ie(n),a=o.getCenter(new U.Vector3),s=o.getSize(new U.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>q.SCALE_RATIO_THRESHOLD||l>q.HUGE_THRESHOLD?(t.near=l*q.NEAR_PLANE_FACTOR.TINY,t.far=l*q.FAR_PLANE_FACTOR.HUGE):l>q.LARGE_THRESHOLD?(t.near=l*q.NEAR_PLANE_FACTOR.SMALL,t.far=l*q.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*q.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*q.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),!i){let d=l*q.INITIAL_DISTANCE_MULTIPLIER;t.position.set(a.x+d*.8,a.y+d,a.z+d*1.2),r.target.copy(a),r.update()}}function Fe(e){if(!e||typeof e!="string")return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new U.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let r=n.startsWith("#")?n:`#${n}`;return new U.Color(r)}catch (e2){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new U.Color(16777215)}if(n.includes(",")){let r=n.split(",").map(i=>parseInt(i.trim(),10));if(r.length===3&&r.every(i=>!isNaN(i)&&i>=0&&i<=255))return new U.Color(r[0]/255,r[1]/255,r[2]/255)}let t=n.toLowerCase();return t in U.Color.NAMES?new U.Color(U.Color.NAMES[t]):(_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new U.Color(16777215))}function ke(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function ie(e){let n=new U.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new U.Box3().setFromObject(t);n.union(r)}),n}var vt=new Set(["floor","grid","label-layer"]);function wt(e){[...e.children].forEach(t=>{vt.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let i=r;if(!i.geometry&&!i.material)return;_optionalChain([i, 'access', _2 => _2.geometry, 'optionalAccess', _3 => _3.dispose, 'call', _4 => _4()]);let o=i.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(s=>{if(!ge.has(s)){for(let l of Object.values(s))l instanceof U.Texture&&l.dispose();s.dispose()}})}),t.removeFromParent())})}function xt(e){let n=e.clone().normalize(),t=new z.Vector3(0,0,1),r=new z.Vector3(0,1,0),i=Math.abs(n.dot(t))>.9?r:t,o=new z.Vector3().crossVectors(n,i).normalize(),a=new z.Vector3().crossVectors(o,n).normalize();return{top:n.clone(),bottom:n.clone().negate(),front:a.clone(),back:a.clone().negate(),right:o.clone(),left:o.clone().negate(),iso:a.clone().multiplyScalar(1.2).add(o.clone()).add(n.clone()).normalize()}}function Ue(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:i}=e,o=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),a=xt(o),s=new z.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(o);let l="perspective",c=t.aspect,d=()=>l==="perspective"?t:s,m=null,u=()=>{_optionalChain([m, 'optionalAccess', _5 => _5.cancel, 'call', _6 => _6()]),m=null},f=()=>{let y=(l==="orthographic"?s:t).position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),x=y*c;s.left=-x,s.right=x,s.top=y,s.bottom=-y,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},b=p=>{if(p!==l){if(u(),p==="orthographic")s.position.copy(t.position),s.up.copy(t.up),s.lookAt(r.target),s.zoom=1,f();else{let y=(s.top-s.bottom)/(2*s.zoom)/Math.tan(t.fov*Math.PI/360),x=s.position.clone().sub(r.target);x.lengthSq()<1e-12&&x.copy(o),x.normalize(),t.position.copy(r.target).add(x.multiplyScalar(y))}l=p,r.object=d(),r.update(),i(d())}},T=(p,v,y,x)=>{let A=t.fov*(Math.PI/180),B=v/(2*Math.tan(A/2))*1.5,G=At(y,o),F=p.clone().add(G.clone().multiplyScalar(B)),Y=d();l==="orthographic"&&(s.zoom=1),u(),x?m=Lt(Y,r,F,p,()=>{l==="orthographic"&&f()}):(Y.position.copy(F),r.target.copy(p),l==="orthographic"&&f(),r.update())},R=(p,v=!0)=>{let y=Ct(n),x=y.isEmpty()?r.target.clone():y.getCenter(new z.Vector3),A=y.isEmpty()?new z.Vector3(1,1,1):y.getSize(new z.Vector3),B=Math.max(A.x,A.y,A.z)||1;T(x,B,p,v)};return{getActiveCamera:d,getProjection:()=>l,setProjection:b,toggleProjection:()=>(b(l==="perspective"?"orthographic":"perspective"),l),setView:(p,v=!0)=>{R(a[p],v)},setViewDirection:R,frameBounds:(p,v=!0)=>{if(p.isEmpty())return;let y=p.getCenter(new z.Vector3),x=p.getSize(new z.Vector3),A=Math.max(x.x,x.y,x.z)||1,B=d().position.clone().sub(r.target);B.lengthSq()<1e-12&&B.copy(a.iso),T(y,A,B.normalize(),v)},setRotateEnabled:p=>{r.enableRotate=p},isRotateEnabled:()=>r.enableRotate,updateAspect:(p,v)=>{c=v===0?c:p/v,l==="orthographic"&&f()},dispose:u}}var Ht=new Set(["grid","floor","label-layer","measure"]);function Mt(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&Ht.has(n.userData.id))return!0;n=n.parent}return!1}function Ct(e){let n=[];return e.traverse(t=>{let r=t;t.visible&&!Mt(t)&&r.geometry&&n.push(t)}),ie(n)}function At(e,n){let t=n.clone().normalize(),r=e.clone().normalize();if(Math.abs(r.dot(t))<.9999)return e;let i=Math.abs(t.dot(new z.Vector3(0,0,1)))>.9?new z.Vector3(0,1,0):new z.Vector3(0,0,1),o=new z.Vector3().crossVectors(t,i).normalize(),a=.5*Math.PI/180;return r.multiplyScalar(Math.cos(a)).add(o.multiplyScalar(Math.sin(a))).normalize()}var St=e=>1-Math.pow(1-e,3);function Lt(e,n,t,r,i,o=250){let a=e.position.clone(),s=n.target.clone(),l=performance.now(),c=null,d=()=>{c=null;let m=St(Math.min((performance.now()-l)/o,1));e.position.lerpVectors(a,t,m),n.target.lerpVectors(s,r,m),i(),n.update(),m<1&&(c=requestAnimationFrame(d))};return c=requestAnimationFrame(d),{cancel:()=>{c!==null&&(cancelAnimationFrame(c),c=null)}}}var It=`
|
|
2
|
-
varying vec3 vWorldPos;
|
|
3
|
-
void main() {
|
|
4
|
-
vec4 world = modelMatrix * vec4(position, 1.0);
|
|
5
|
-
vWorldPos = world.xyz;
|
|
6
|
-
gl_Position = projectionMatrix * viewMatrix * world;
|
|
7
|
-
}
|
|
8
|
-
`,Dt=`
|
|
9
|
-
precision highp float;
|
|
10
|
-
varying vec3 vWorldPos;
|
|
11
|
-
|
|
12
|
-
uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
|
|
13
|
-
uniform float uCell;
|
|
14
|
-
uniform float uMajor;
|
|
15
|
-
uniform vec3 uCellColor;
|
|
16
|
-
uniform vec3 uMajorColor;
|
|
17
|
-
uniform vec3 uCenter; // fade center (camera position), projected onto plane
|
|
18
|
-
uniform float uFade;
|
|
19
|
-
|
|
20
|
-
// Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
|
|
21
|
-
// stay ~1px regardless of zoom (the standard "pristine grid" technique).
|
|
22
|
-
float gridLine(vec2 coord, float spacing) {
|
|
23
|
-
vec2 c = coord / spacing;
|
|
24
|
-
vec2 d = fwidth(c);
|
|
25
|
-
vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
|
|
26
|
-
float line = min(g.x, g.y);
|
|
27
|
-
return 1.0 - clamp(line, 0.0, 1.0);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
|
|
31
|
-
float axis(vec3 v, float i) {
|
|
32
|
-
return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
void main() {
|
|
36
|
-
// Pick the two in-plane world coordinates.
|
|
37
|
-
vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
|
|
38
|
-
|
|
39
|
-
float minor = gridLine(coord, uCell);
|
|
40
|
-
float major = gridLine(coord, uCell * uMajor);
|
|
41
|
-
|
|
42
|
-
vec3 color = mix(uCellColor, uMajorColor, major);
|
|
43
|
-
float alpha = max(minor, major);
|
|
44
|
-
|
|
45
|
-
// Radial fade from the camera-projected center.
|
|
46
|
-
float dist = distance(vWorldPos, uCenter);
|
|
47
|
-
float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
|
|
48
|
-
alpha *= fade * fade;
|
|
49
|
-
|
|
50
|
-
if (alpha < 0.001) discard;
|
|
51
|
-
gl_FragColor = vec4(color, alpha);
|
|
52
|
-
}
|
|
53
|
-
`;function ze(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:i=4473924,fadeDistance:o=100,plane:a="y"}=e,s=a==="y"?new k.Vector2(0,2):a==="z"?new k.Vector2(0,1):new k.Vector2(1,2),l=o*2.5,c=new k.PlaneGeometry(l,l);a==="y"?c.rotateX(-Math.PI/2):a==="x"&&c.rotateY(Math.PI/2);let d=new k.ShaderMaterial({vertexShader:It,fragmentShader:Dt,transparent:!0,depthWrite:!1,side:k.DoubleSide,uniforms:{uAxes:{value:s},uCell:{value:n},uMajor:{value:t},uCellColor:{value:new k.Color(r)},uMajorColor:{value:new k.Color(i)},uCenter:{value:new k.Vector3},uFade:{value:o}}}),m=new k.Mesh(c,d);m.name="grid",m.userData.id="grid",m.renderOrder=-1;let u=new k.Vector3;return{object:m,update:f=>{a==="y"?(m.position.set(f.x,0,f.z),u.set(f.x,0,f.z)):a==="z"?(m.position.set(f.x,f.y,0),u.set(f.x,f.y,0)):(m.position.set(0,f.y,f.z),u.set(0,f.y,f.z)),d.uniforms.uCenter.value.copy(u)},setVisible:f=>{m.visible=f},dispose:()=>{m.removeFromParent(),c.dispose(),d.dispose()}}}var _ViewHelperjs = require('three/addons/helpers/ViewHelper.js');function _e(e){let{camera:n,domElement:t,controller:r}=e,i=new (0, _ViewHelperjs.ViewHelper)(n,t);i.setLabels("X","Y","Z");let o=!0,a=128,s=new W.Raycaster,l=new W.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2),l.updateMatrixWorld();let c={posX:new W.Vector3(1,0,0),negX:new W.Vector3(-1,0,0),posY:new W.Vector3(0,1,0),negY:new W.Vector3(0,-1,0),posZ:new W.Vector3(0,0,1),negZ:new W.Vector3(0,0,-1)},d=u=>{let f=t.getBoundingClientRect(),b=f.left+t.offsetWidth-a-i.location.right,T=f.top+t.offsetHeight-a-i.location.bottom,R=new W.Vector2((u.clientX-b)/a*2-1,-((u.clientY-T)/a)*2+1);if(Math.abs(R.x)>1||Math.abs(R.y)>1)return null;i.quaternion.copy(n.quaternion).invert(),i.updateMatrixWorld(),s.setFromCamera(R,l);let M=s.intersectObjects(i.children,!1);for(let h of M){let w=_optionalChain([h, 'access', _7 => _7.object, 'access', _8 => _8.userData, 'optionalAccess', _9 => _9.type]);if(typeof w=="string"&&w in c)return w}return null};return{render:u=>{if(!o)return;let f=u.autoClear;u.autoClear=!1,i.render(u),u.autoClear=f},update:()=>{},handleClick:u=>{if(!o)return!1;let f=d(u);return f?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[f],!1),!0):!1},isAnimating:!1,setVisible:u=>{o=u},isVisible:()=>o,dispose:()=>i.dispose()}}var _LineSegmentsGeometryjs = require('three/addons/lines/LineSegmentsGeometry.js');var _LineSegments2js = require('three/addons/lines/LineSegments2.js');var _LineMaterialjs = require('three/addons/lines/LineMaterial.js');var ue="edge-overlay",Vt=2236962,Ft=1.5,kt=30,ye=new WeakMap;function Ge(e,n={}){let t=new re.Color(_nullishCoalesce(n.color, () => (Vt))),r=_nullishCoalesce(n.width, () => (Ft)),i=_nullishCoalesce(n.thresholdAngle, () => (kt)),o=[];return e.traverse(a=>{if(!(a instanceof re.Mesh)||a.userData.id==="floor"||a.userData.id==="grid"||a.userData.kind===ue||a.children.some(l=>_optionalChain([l, 'access', _10 => _10.userData, 'optionalAccess', _11 => _11.kind])===ue)||!a.geometry)return;let s=_t(a.geometry,t,r,i);a.add(s),o.push(s)}),o}function Ut(e,n){let t=ye.get(e);t||(t=new Map,ye.set(e,t));let r=t.get(n);if(!r){let i=new re.EdgesGeometry(e,n),o=new _LineSegmentsGeometryjs.LineSegmentsGeometry;o.setPositions(i.attributes.position.array),i.dispose(),r={geometry:o,refCount:0},t.set(n,r)}return r.refCount+=1,r.geometry}function zt(e){let n=e.userData,t=n.edgeSource&&ye.get(n.edgeSource),r=n.edgeThresholdAngle!=null?_optionalChain([t, 'optionalAccess', _12 => _12.get, 'call', _13 => _13(n.edgeThresholdAngle)]):void 0;if(!r||r.geometry!==e.geometry){e.geometry.dispose();return}r.refCount-=1,r.refCount<=0&&(r.geometry.dispose(),t.delete(n.edgeThresholdAngle))}function _t(e,n,t,r){let i=Ut(e,r),o=new (0, _LineMaterialjs.LineMaterial)({color:n});o.linewidth=t,o.polygonOffset=!0,o.polygonOffsetFactor=-1,o.polygonOffsetUnits=-4;let a=new (0, _LineSegments2js.LineSegments2)(i,o);return a.userData.kind=ue,a.userData.edgeSource=e,a.userData.edgeThresholdAngle=r,a.raycast=()=>{},a}function jt(e){return _optionalChain([e, 'access', _14 => _14.userData, 'optionalAccess', _15 => _15.kind])===ue}function Wr(e){let n=[];e.traverse(t=>{t instanceof _LineSegments2js.LineSegments2&&jt(t)&&n.push(t)});for(let t of n)zt(t),t.material.dispose(),t.removeFromParent();return n.length}var _EffectComposerjs = require('three/addons/postprocessing/EffectComposer.js');var _RenderPassjs = require('three/addons/postprocessing/RenderPass.js');var _GTAOPassjs = require('three/addons/postprocessing/GTAOPass.js');var _SMAAPassjs = require('three/addons/postprocessing/SMAAPass.js');var _OutputPassjs = require('three/addons/postprocessing/OutputPass.js');function Ne(e,n,t,r,i,o){let a=new (0, _EffectComposerjs.EffectComposer)(e),s=new (0, _RenderPassjs.RenderPass)(n,t);a.addPass(s);let l=new (0, _GTAOPassjs.GTAOPass)(n,t,r,i);l.blendIntensity=_nullishCoalesce(o.aoIntensity, () => (1)),l.updateGtaoMaterial({screenSpaceRadius:!0}),a.addPass(l);let c=new _SMAAPassjs.SMAAPass;a.addPass(c);let d=new _OutputPassjs.OutputPass;a.addPass(d),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure;let m=_nullishCoalesce(o.aoPixelRatio, () => (1));return a.setSize(r,i),{render:u=>a.render(u),setSize:(u,f,b)=>{a.setPixelRatio(Math.min(b,m)),a.setSize(u,f)},setCamera:u=>{s.camera=u,l.camera=u;let f=u.isPerspectiveCamera?1:0;l.gtaoMaterial.defines.PERSPECTIVE_CAMERA!==f&&(l.gtaoMaterial.defines.PERSPECTIVE_CAMERA=f,l.gtaoMaterial.needsUpdate=!0)},dispose:()=>{a.dispose(),l.dispose(),c.dispose(),d.dispose()}}}var _CSS2DRendererjs = require('three/addons/renderers/CSS2DRenderer.js');function $e(e,n){let t=new _CSS2DRendererjs.CSS2DRenderer,r=t.domElement;r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.overflow="hidden",r.style.pointerEvents="none",r.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(r);let i={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(i.width,i.height);let o=new We.Group;o.name="label-layer",o.userData.id="label-layer",n.add(o);let a=new Set;return{addLabel:(l,c,d)=>{let m=document.createElement("div");m.textContent=l,d?m.className=d:Object.assign(m.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),m.style.pointerEvents="none";let u=new (0, _CSS2DRendererjs.CSS2DObject)(m);return u.position.copy(c),o.add(u),a.add(u),{object:u,setPosition:f=>u.position.copy(f),setText:f=>{m.textContent=f},remove:()=>{u.removeFromParent(),m.remove(),a.delete(u)}}},render:(l,c)=>t.render(l,c),setSize:(l,c)=>t.setSize(l,c),dispose:()=>{a.forEach(l=>{l.removeFromParent(),l.element.remove()}),a.clear(),o.removeFromParent(),r.remove()}}}var _Line2js = require('three/addons/lines/Line2.js');var _LineGeometryjs = require('three/addons/lines/LineGeometry.js');var Qt=12,en=16763904,Ye=.015,Xe={Millimeters:{metersPerUnit:1/1e3,suffix:"mm"},Centimeters:{metersPerUnit:1/100,suffix:"cm"},Meters:{metersPerUnit:1,suffix:"m"},Inches:{metersPerUnit:1/39.37,suffix:"in"},Feet:{metersPerUnit:1/3.28084,suffix:"ft"}};function tn(e){let n=e&&Xe[e]||Xe.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function nn(e,n){if(e.isOrthographicCamera){let r=e;return Math.abs(r.top-r.bottom)/(r.zoom||1)*Ye}return((n?e.position.distanceTo(n):e.position.length())||1)*Ye}function rn(e){let n=e.object;if(n instanceof D.Mesh)return e.face?[e.face.a,e.face.b,e.face.c]:null;if(n instanceof D.Points)return e.index!=null?[e.index]:null;if(n instanceof D.Line){if(e.index==null)return null;let t=n.geometry.index;return t?e.index+1>=t.count?null:[t.getX(e.index),t.getX(e.index+1)]:[e.index,e.index+1]}return null}function on(e,n,t,r){let i=e.point.clone(),o=e.object,a=rn(e);if(!a||!o.geometry)return i;let s=o.geometry.attributes.position;if(!s)return i;let l=u=>{let f=u.clone().project(n);return new D.Vector2((f.x+1)/2*t.width,(1-f.y)/2*t.height)},c=l(i),d=i,m=r;for(let u of a){if(u>=s.count)continue;let b=new D.Vector3().fromBufferAttribute(s,u).applyMatrix4(o.matrixWorld),T=l(b).distanceTo(c);T<m&&(m=T,d=b)}return d}function qe(e){let{canvas:n,scene:t,getActiveCamera:r,getViewTarget:i,labelLayer:o,options:a={}}=e,s=_nullishCoalesce(a.snapPixels, () => (Qt)),l=new D.Color(_nullishCoalesce(a.color, () => (en))),c=tn(a.displayUnit),d=(S,H)=>`${c(S)}
|
|
54
|
-
\u0394x ${c(H.x)} \u0394y ${c(H.y)} \u0394z ${c(H.z)}`,m=_nullishCoalesce(a.format, () => (d)),u=new D.Raycaster,f=new D.Vector2,b=!1,T=[],R=[],M=null,h=null,w=new D.PointsMaterial({color:l,size:8,sizeAttenuation:!1,depthTest:!1}),L=new D.PointsMaterial({color:l,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),p=null,v=S=>{if(!S){p&&(p.visible=!1);return}if(!p){let H=new D.BufferGeometry;H.setAttribute("position",new D.Float32BufferAttribute([0,0,0],3)),p=new D.Points(H,L),p.renderOrder=1e3,p.userData.id="measure",p.raycast=()=>{},t.add(p)}p.position.copy(S),p.visible=!0},y=S=>{let H=new D.BufferGeometry;H.setAttribute("position",new D.Float32BufferAttribute([S.x,S.y,S.z],3));let j=new D.Points(H,w);return j.renderOrder=999,j.userData.id="measure",j.raycast=()=>{},t.add(j),j},x=()=>{T.length=0,R.forEach(S=>{S.geometry.dispose(),S.removeFromParent()}),R.length=0,M&&(M.geometry.dispose(),M.material.dispose(),M.removeFromParent(),M=null),_optionalChain([h, 'optionalAccess', _16 => _16.remove, 'call', _17 => _17()]),h=null},A=()=>{if(T.length!==2)return;let[S,H]=T,j=new _LineGeometryjs.LineGeometry;j.setPositions([S.x,S.y,S.z,H.x,H.y,H.z]);let K=new (0, _LineMaterialjs.LineMaterial)({color:l});K.linewidth=2,K.depthTest=!1,M=new (0, _Line2js.Line2)(j,K),M.renderOrder=998,M.userData.id="measure",M.raycast=()=>{},t.add(M);let Q=S.clone().add(H).multiplyScalar(.5),ee=new D.Vector3(Math.abs(H.x-S.x),Math.abs(H.y-S.y),Math.abs(H.z-S.z));h=o.addLabel(m(S.distanceTo(H),ee),Q,a.labelClassName)},B=S=>{let H=n.getBoundingClientRect();f.x=(S.clientX-H.left)/H.width*2-1,f.y=-((S.clientY-H.top)/H.height)*2+1;let j=r();u.setFromCamera(f,j);let K=nn(j,_optionalChain([i, 'optionalCall', _18 => _18()]));u.params.Line.threshold=K,u.params.Points.threshold=K;let Q=u.intersectObjects(t.children,!0).filter(ee=>ee.object.userData.id!=="measure"&&ee.object.userData.id!=="grid");return Q.length===0?null:on(Q[0],j,{width:H.width,height:H.height},s)},G=null,F=0,Y=()=>{F&&(cancelAnimationFrame(F),F=0),G=null};return{setEnabled:S=>{b=S,S||(Y(),x(),v(null))},isEnabled:()=>b,handleClick:S=>{if(!b)return!1;T.length===2&&x();let H=B(S);return H===null||(T.push(H),R.push(y(H)),T.length===2&&A()),!0},handleMove:S=>{b&&(G=S,!F&&(F=requestAnimationFrame(()=>{F=0;let H=G;G=null,!(!b||!H)&&v(B(H))})))},clear:x,dispose:()=>{Y(),x(),p&&(p.geometry.dispose(),p.removeFromParent(),p=null),w.dispose(),L.dispose()}}}var an=64,sn=256,X=new Map,ae=new Map,de=0,pe=class extends Error{constructor(n){super(`Texture load for ${n} resolved after clearTextureCache(); texture disposed.`),this.name="StaleTextureLoadError"}},me=1;function Ze(e){me=Math.max(1,e);for(let n of X.values())n.anisotropy!==me&&(n.anisotropy=me,n.needsUpdate=!0)}function Ke(e,n){let t=ln(n),r=X.get(t);if(r){X.delete(t),X.set(t,r),e.map=r,e.needsUpdate=!0;return}typeof document>"u"||dn(n,t).then(i=>{e.map=i,e.needsUpdate=!0}).catch(i=>{i instanceof pe||_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Failed to load material texture ${n}:`,i)})}function ao(){de++;for(let e of X.values())e.dispose();X.clear(),ae.clear()}function ln(e){return e.length<=sn?e:`data-uri:${cn(e).toString(16)}:${e.length}`}function cn(e){let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0}function un(e,n){for(X.set(e,n);X.size>an;){let t=X.keys().next().value,r=X.get(t);X.delete(t),r.dispose()}}function dn(e,n){let t=ae.get(n);if(!t){let r=de;t=new Promise((i,o)=>{new fe.TextureLoader().load(e,a=>{if(r!==de){a.dispose(),o(new pe(e));return}a.colorSpace=fe.SRGBColorSpace,a.anisotropy=me,un(n,a),ae.delete(n),i(a)},void 0,a=>{r===de&&ae.delete(n),o(a)})}),ae.set(n,t)}return t}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var oe=new E.Vector3(0,0,1),fn="technical",Te={studio:{toneMapping:E.ACESFilmicToneMapping,toneMappingExposure:1,envMapIntensity:1.3,environmentIntensity:1.2,hemisphereIntensity:1,ambientIntensity:.3,cullBackfaces:!1,ambientOcclusion:!1},technical:{toneMapping:E.NeutralToneMapping,toneMappingExposure:1,envMapIntensity:.5,environmentIntensity:1,hemisphereIntensity:0,ambientIntensity:1,cullBackfaces:!1,ambientOcclusion:!1},showcase:{toneMapping:E.ACESFilmicToneMapping,toneMappingExposure:1.05,envMapIntensity:1.6,environmentIntensity:1.35,hemisphereIntensity:1.2,ambientIntensity:.25,cullBackfaces:!1,ambientOcclusion:!1}};function En(e){let n=Te[e];return{envMapIntensity:n.envMapIntensity,cullBackfaces:n.cullBackfaces}}function hn(e){let n=Math.abs(e.x),t=Math.abs(e.y),r=Math.abs(e.z);return r>=n&&r>=t?"z":t>=n&&t>=r?"y":"x"}var To=function(e,n){let t=gn(n||{}),r=_optionalChain([t, 'access', _19 => _19.environment, 'optionalAccess', _20 => _20.sceneUp])||oe,i=_nullishCoalesce(t.render.pixelRatio, () => (Math.min(window.devicePixelRatio,2))),o=Rn(t),a=Mn(t,e);a.up.copy(r);let s=Cn(e,t,i);Ze(s.capabilities.getMaxAnisotropy());let l=Sn(a,e,t),c=Ue({scene:o,perspective:a,controls:l,onActiveCameraChange:()=>{},up:r}),d=()=>c.getActiveCamera(),m=!1;wn(o,t,()=>m);let u=xn(o,t),f=u.sun,b=()=>{f&&Tn(f,be(o))};_optionalChain([t, 'access', _21 => _21.floor, 'optionalAccess', _22 => _22.enabled])&&Hn(o,t);let T=t.grid.enabled?ze({cellSize:t.grid.cellSize,majorEvery:t.grid.majorEvery,cellColor:t.grid.cellColor,majorColor:t.grid.majorColor,fadeDistance:t.grid.fadeDistance,plane:t.grid.plane}):null;T&&o.add(T.object);let R=t.gizmo.enabled?_e({camera:a,domElement:e,controller:c}):null,M=_nullishCoalesce(e.parentElement, () => (e)),h=t.measure.enabled?$e(M,o):null,w=t.measure.enabled&&h?qe({canvas:e,scene:o,getActiveCamera:d,labelLayer:h,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,L=t.events.enableEventHandlers!==!1?An(e,o,c,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},p=5,v=0,y=0,x=g=>{v=g.clientX,y=g.clientY},A=g=>Math.hypot(g.clientX-v,g.clientY-y)>p,B=g=>{if(!A(g)){if(_optionalChain([w, 'optionalAccess', _23 => _23.handleClick, 'call', _24 => _24(g)])){g.stopImmediatePropagation();return}_optionalChain([R, 'optionalAccess', _25 => _25.handleClick, 'call', _26 => _26(g)])&&g.stopImmediatePropagation()}};(R||w)&&(e.addEventListener("mousedown",x,{capture:!0}),e.addEventListener("click",B,{capture:!0}));let G=g=>_optionalChain([w, 'optionalAccess', _27 => _27.handleMove, 'call', _28 => _28(g)]);w&&e.addEventListener("mousemove",G,{passive:!0});let F=g=>{Ge(g,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},Y=e.parentElement,J=()=>Y?{width:Y.clientWidth,height:Y.clientHeight}:{width:window.innerWidth,height:window.innerHeight},V=null,S=()=>{let{width:g,height:I}=J(),N=Ne(s,o,d(),Math.max(1,g),Math.max(1,I),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (E.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity,aoPixelRatio:t.render.aoPixelRatio});return N.setSize(Math.max(1,g),Math.max(1,I),i),N},H=g=>{g&&!V?V=S():!g&&V&&(V.dispose(),V=null)};t.render.ambientOcclusion&&(V=S());let j=g=>{g.ambientIntensity!==void 0&&(u.ambient.intensity=g.ambientIntensity),g.hemisphereIntensity!==void 0&&!u.hemisphere&&g.hemisphereIntensity>0&&(u.hemisphere=new E.HemisphereLight(_nullishCoalesce(g.hemisphereSkyColor, () => (t.lighting.hemisphereSkyColor)),_nullishCoalesce(g.hemisphereGroundColor, () => (t.lighting.hemisphereGroundColor)),g.hemisphereIntensity),u.hemisphere.position.copy(_nullishCoalesce(t.environment.sceneUp, () => (oe))),o.add(u.hemisphere)),u.hemisphere&&(g.hemisphereIntensity!==void 0&&(u.hemisphere.intensity=g.hemisphereIntensity),g.hemisphereSkyColor!==void 0&&u.hemisphere.color.set(g.hemisphereSkyColor),g.hemisphereGroundColor!==void 0&&u.hemisphere.groundColor.set(g.hemisphereGroundColor))},K=g=>{t.environment.environmentIntensity=g,o.environmentIntensity=g},Q=g=>{t.render.toneMappingExposure=g,s.toneMappingExposure=g,V&&(H(!1),H(!0))},ee=g=>{t.render.aoIntensity=g,V&&(H(!1),H(!0))},mt=g=>{let I=Te[g];Me=g,s.toneMapping=I.toneMapping,s.toneMappingExposure=I.toneMappingExposure,t.render.toneMapping=I.toneMapping,t.render.toneMappingExposure=I.toneMappingExposure,j({hemisphereIntensity:I.hemisphereIntensity,ambientIntensity:I.ambientIntensity}),K(I.environmentIntensity),V&&H(!1),H(I.ambientOcclusion),o.traverse(N=>{if(N.userData.source!=="compute")return;let ce=N,bt=Array.isArray(ce.material)?ce.material:ce.material?[ce.material]:[];for(let Ae of bt)"envMapIntensity"in Ae&&(Ae.envMapIntensity=I.envMapIntensity)})},Me=t.look,pt=()=>En(Me),{animate:ft,dispose:Et}=vn(s,o,a,d,c,l,J,i,t.events.onFrame,T,R,()=>V,h);ft(),o.up.set(r.x,r.y,r.z),b();let Ce=g=>{g.traverse(I=>{let N=I;!N.geometry&&!N.material||(_optionalChain([N, 'access', _29 => _29.geometry, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),Array.isArray(N.material)?N.material.forEach(Ee):N.material&&Ee(N.material))})},ht=g=>{g.userData.source="user",o.add(g)},gt=g=>{g.removeFromParent(),Ce(g)},yt=()=>{o.children.filter(I=>I.userData.source==="user").forEach(I=>{I.removeFromParent(),Ce(I)})};return{scene:o,camera:a,controls:l,renderer:s,cameraController:c,grid:T,gizmo:R,measureTool:w,applyEdges:F,setAmbientOcclusion:H,setLook:mt,setFillLights:j,setEnvironmentIntensity:K,setToneMappingExposure:Q,setAoIntensity:ee,getMaterialAppearance:pt,updateShadowBounds:b,dispose:()=>{m=!0,Et(),L.dispose(),(R||w)&&(e.removeEventListener("mousedown",x,{capture:!0}),e.removeEventListener("click",B,{capture:!0})),w&&e.removeEventListener("mousemove",G),_optionalChain([w, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),_optionalChain([h, 'optionalAccess', _34 => _34.dispose, 'call', _35 => _35()]),_optionalChain([R, 'optionalAccess', _36 => _36.dispose, 'call', _37 => _37()]),_optionalChain([T, 'optionalAccess', _38 => _38.dispose, 'call', _39 => _39()]),_optionalChain([V, 'optionalAccess', _40 => _40.dispose, 'call', _41 => _41()]),c.dispose(),l.dispose(),s.dispose(),s.forceContextLoss(),o.traverse(g=>{let I=g;!I.geometry&&!I.material||(_optionalChain([I, 'access', _42 => _42.geometry, 'optionalAccess', _43 => _43.dispose, 'call', _44 => _44()]),Array.isArray(I.material)?I.material.forEach(Ee):I.material&&Ee(I.material))}),_optionalChain([o, 'access', _45 => _45.environment, 'optionalAccess', _46 => _46.dispose, 'call', _47 => _47()]),o.background instanceof E.Texture&&o.background.dispose()},fitToView:L.fitToView,clearSelection:L.clearSelection,addUserGeometry:ht,removeUserGeometry:gt,clearUserGeometry:yt}};function gn(e){let n=e.sceneScale||"m",r={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[n],i=_nullishCoalesce(e.look, () => (fn)),o=Te[i];return{sceneScale:n,look:i,camera:{position:_optionalChain([e, 'access', _48 => _48.camera, 'optionalAccess', _49 => _49.position])||new E.Vector3(-r.cameraDistance,-r.cameraDistance,r.cameraDistance),fov:_optionalChain([e, 'access', _50 => _50.camera, 'optionalAccess', _51 => _51.fov])||20,near:_optionalChain([e, 'access', _52 => _52.camera, 'optionalAccess', _53 => _53.near])||r.near,far:_optionalChain([e, 'access', _54 => _54.camera, 'optionalAccess', _55 => _55.far])||r.far,target:_optionalChain([e, 'access', _56 => _56.camera, 'optionalAccess', _57 => _57.target])||new E.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _58 => _58.lighting, 'optionalAccess', _59 => _59.enableSunlight]), () => (!0)),sunlightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.lighting, 'optionalAccess', _61 => _61.sunlightIntensity]), () => (1)),sunlightPosition:_optionalChain([e, 'access', _62 => _62.lighting, 'optionalAccess', _63 => _63.sunlightPosition])||new E.Vector3(r.lightDistance,r.lightDistance,r.lightHeight),ambientLightColor:_optionalChain([e, 'access', _64 => _64.lighting, 'optionalAccess', _65 => _65.ambientLightColor])||new E.Color(4210752),ambientLightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _66 => _66.lighting, 'optionalAccess', _67 => _67.ambientLightIntensity]), () => (o.ambientIntensity)),sunlightColor:_optionalChain([e, 'access', _68 => _68.lighting, 'optionalAccess', _69 => _69.sunlightColor])||16777215,enableHemisphereLight:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.lighting, 'optionalAccess', _71 => _71.enableHemisphereLight]), () => (o.hemisphereIntensity>0)),hemisphereSkyColor:_nullishCoalesce(_optionalChain([e, 'access', _72 => _72.lighting, 'optionalAccess', _73 => _73.hemisphereSkyColor]), () => (14673663)),hemisphereGroundColor:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.lighting, 'optionalAccess', _75 => _75.hemisphereGroundColor]), () => (7036754)),hemisphereIntensity:_nullishCoalesce(_optionalChain([e, 'access', _76 => _76.lighting, 'optionalAccess', _77 => _77.hemisphereIntensity]), () => (o.hemisphereIntensity))},environment:{hdrPath:_optionalChain([e, 'access', _78 => _78.environment, 'optionalAccess', _79 => _79.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _80 => _80.environment, 'optionalAccess', _81 => _81.backgroundColor])||new E.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _82 => _82.environment, 'optionalAccess', _83 => _83.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _84 => _84.environment, 'optionalAccess', _85 => _85.sceneUp])||oe,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _86 => _86.environment, 'optionalAccess', _87 => _87.showEnvironment]), () => (!1)),environmentIntensity:_nullishCoalesce(_optionalChain([e, 'access', _88 => _88.environment, 'optionalAccess', _89 => _89.environmentIntensity]), () => (o.environmentIntensity))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _90 => _90.floor, 'optionalAccess', _91 => _91.enabled]), () => (!1)),size:_optionalChain([e, 'access', _92 => _92.floor, 'optionalAccess', _93 => _93.size])||r.floorSize,color:_optionalChain([e, 'access', _94 => _94.floor, 'optionalAccess', _95 => _95.color])||new E.Color(8421504),roughness:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.floor, 'optionalAccess', _97 => _97.roughness]), () => (.7)),metalness:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.floor, 'optionalAccess', _99 => _99.metalness]), () => (0)),receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.floor, 'optionalAccess', _101 => _101.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.render, 'optionalAccess', _103 => _103.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _104 => _104.render, 'optionalAccess', _105 => _105.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _106 => _106.render, 'optionalAccess', _107 => _107.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _108 => _108.render, 'optionalAccess', _109 => _109.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_nullishCoalesce(_optionalChain([e, 'access', _110 => _110.render, 'optionalAccess', _111 => _111.toneMapping]), () => (o.toneMapping)),toneMappingExposure:_nullishCoalesce(_optionalChain([e, 'access', _112 => _112.render, 'optionalAccess', _113 => _113.toneMappingExposure]), () => (o.toneMappingExposure)),preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _114 => _114.render, 'optionalAccess', _115 => _115.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _116 => _116.render, 'optionalAccess', _117 => _117.ambientOcclusion]), () => (o.ambientOcclusion)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _118 => _118.render, 'optionalAccess', _119 => _119.aoIntensity]), () => (1)),aoPixelRatio:_nullishCoalesce(_optionalChain([e, 'access', _120 => _120.render, 'optionalAccess', _121 => _121.aoPixelRatio]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _122 => _122.controls, 'optionalAccess', _123 => _123.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _124 => _124.controls, 'optionalAccess', _125 => _125.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _126 => _126.controls, 'optionalAccess', _127 => _127.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _128 => _128.controls, 'optionalAccess', _129 => _129.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _130 => _130.controls, 'optionalAccess', _131 => _131.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _132 => _132.controls, 'optionalAccess', _133 => _133.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _134 => _134.controls, 'optionalAccess', _135 => _135.minDistance])||r.minDistance,maxDistance:_optionalChain([e, 'access', _136 => _136.controls, 'optionalAccess', _137 => _137.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _138 => _138.grid, 'optionalAccess', _139 => _139.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _140 => _140.grid, 'optionalAccess', _141 => _141.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _142 => _142.grid, 'optionalAccess', _143 => _143.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _144 => _144.grid, 'optionalAccess', _145 => _145.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _146 => _146.grid, 'optionalAccess', _147 => _147.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _148 => _148.grid, 'optionalAccess', _149 => _149.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _150 => _150.grid, 'optionalAccess', _151 => _151.plane]), () => (hn(_nullishCoalesce(_optionalChain([e, 'access', _152 => _152.environment, 'optionalAccess', _153 => _153.sceneUp]), () => (oe)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _154 => _154.gizmo, 'optionalAccess', _155 => _155.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _156 => _156.edges, 'optionalAccess', _157 => _157.enabled]), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _158 => _158.edges, 'optionalAccess', _159 => _159.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _160 => _160.edges, 'optionalAccess', _161 => _161.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _162 => _162.edges, 'optionalAccess', _163 => _163.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _164 => _164.measure, 'optionalAccess', _165 => _165.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _166 => _166.measure, 'optionalAccess', _167 => _167.snapPixels]),color:_optionalChain([e, 'access', _168 => _168.measure, 'optionalAccess', _169 => _169.color]),labelClassName:_optionalChain([e, 'access', _170 => _170.measure, 'optionalAccess', _171 => _171.labelClassName]),displayUnit:_optionalChain([e, 'access', _172 => _172.measure, 'optionalAccess', _173 => _173.displayUnit]),format:_optionalChain([e, 'access', _174 => _174.measure, 'optionalAccess', _175 => _175.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _176 => _176.events, 'optionalAccess', _177 => _177.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _178 => _178.events, 'optionalAccess', _179 => _179.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _180 => _180.events, 'optionalAccess', _181 => _181.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _182 => _182.events, 'optionalAccess', _183 => _183.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _184 => _184.events, 'optionalAccess', _185 => _185.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _186 => _186.events, 'optionalAccess', _187 => _187.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _188 => _188.events, 'optionalAccess', _189 => _189.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _190 => _190.events, 'optionalAccess', _191 => _191.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _192 => _192.events, 'optionalAccess', _193 => _193.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _194 => _194.events, 'optionalAccess', _195 => _195.onReady]),onFrame:_optionalChain([e, 'access', _196 => _196.events, 'optionalAccess', _197 => _197.onFrame])}}}function Ee(e){for(let n of Object.values(e))n instanceof E.Texture&&n.dispose();e.dispose()}var yn=new Set(["grid","floor","label-layer","measure"]);function bn(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&yn.has(n.userData.id))return!0;n=n.parent}return!1}function be(e){let n=new E.Box3;return e.traverse(t=>{let r=t;t.visible&&!bn(t)&&r.geometry&&n.expandByObject(t)}),n}function Tn(e,n){if(n.isEmpty())return;let t=n.getCenter(new E.Vector3),r=n.getSize(new E.Vector3).length()*.5*1.2,i=e.shadow.camera;i.left=-r,i.right=r,i.top=r,i.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let o=e.position.distanceTo(t);i.near=Math.max(r*.01,o-r),i.far=o+r,i.updateProjectionMatrix()}function Rn(e){let n=new E.Scene,t=typeof e.environment.backgroundColor=="string"?new E.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function vn(e,n,t,r,i,o,a,s,l,c,d,m,u){let f=null,b=performance.now(),T=()=>{let{width:h,height:w}=a();if(h===0||w===0)return;let L=Math.floor(h*s),p=Math.floor(w*s);(e.domElement.width!==L||e.domElement.height!==p)&&(e.setPixelRatio(s),e.setSize(h,w,!1),t.aspect=h/w,t.updateProjectionMatrix(),i.updateAspect(h,w),_optionalChain([m, 'optionalCall', _198 => _198(), 'optionalAccess', _199 => _199.setSize, 'call', _200 => _200(h,w,s)]),_optionalChain([u, 'optionalAccess', _201 => _201.setSize, 'call', _202 => _202(h,w)]))},R=function(){f=requestAnimationFrame(R);let h=performance.now(),w=(h-b)/1e3;b=h,T(),(o.enableDamping||o.autoRotate)&&o.update(),c&&c.update(r().position),d&&d.update(w),_optionalChain([l, 'optionalCall', _203 => _203(w)]);let L=r(),p=_optionalChain([m, 'optionalCall', _204 => _204()]);p?(p.setCamera(L),p.render(w)):e.render(n,L),u&&u.render(n,L),d&&d.render(e)};return{animate:R,dispose:()=>{f!==null&&(cancelAnimationFrame(f),f=null)}}}function wn(e,n,t){n.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(n.environment.hdrPath||"/baseHDR.hdr",function(r){if(t()){r.dispose();return}if(!_optionalChain([r, 'optionalAccess', _205 => _205.image])){_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'optionalAccess', _206 => _206.dispose, 'call', _207 => _207()]),_optionalChain([n, 'access', _208 => _208.events, 'access', _209 => _209.onReady, 'optionalCall', _210 => _210()]);return}r.mapping=E.EquirectangularReflectionMapping,e.environment=r,e.environmentIntensity=_nullishCoalesce(n.environment.environmentIntensity, () => (1)),n.environment.showEnvironment&&(e.background=r),_optionalChain([n, 'access', _211 => _211.events, 'access', _212 => _212.onReady, 'optionalCall', _213 => _213()])},void 0,function(r){t()||(_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",r),_optionalChain([n, 'access', _214 => _214.events, 'access', _215 => _215.onReady, 'optionalCall', _216 => _216()]))}):_optionalChain([n, 'access', _217 => _217.events, 'access', _218 => _218.onReady, 'optionalCall', _219 => _219()])}function xn(e,n){let t=new E.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);e.add(t);let r=null;if(n.lighting.enableHemisphereLight){r=new E.HemisphereLight(n.lighting.hemisphereSkyColor,n.lighting.hemisphereGroundColor,n.lighting.hemisphereIntensity);let a=_nullishCoalesce(n.environment.sceneUp, () => (oe));r.position.copy(a),e.add(r)}if(!n.lighting.enableSunlight)return{ambient:t,hemisphere:r,sun:null};let i=new E.DirectionalLight(_nullishCoalesce(n.lighting.sunlightColor, () => (16777215)),n.lighting.sunlightIntensity),o=n.lighting.sunlightPosition;return o&&i.position.set(o.x,o.y,o.z),n.render.enableShadows?(i.castShadow=!0,i.shadow.mapSize.width=n.render.shadowMapSize||2048,i.shadow.mapSize.height=n.render.shadowMapSize||2048,i.shadow.bias=-1e-4,i.shadow.normalBias=.02,i.shadow.radius=4,e.add(i),e.add(i.target),{ambient:t,hemisphere:r,sun:i}):(e.add(i),{ambient:t,hemisphere:r,sun:null})}function Hn(e,n){let t=n.floor.size,r=new E.PlaneGeometry(t,t),i=typeof n.floor.color=="string"?new E.Color(n.floor.color):n.floor.color,o=new E.MeshStandardMaterial({color:i,roughness:n.floor.roughness,metalness:n.floor.metalness,side:E.DoubleSide}),a=new E.Mesh(r,o);a.userData.id="floor",a.name="floor";let s=(_optionalChain([n, 'access', _220 => _220.environment, 'optionalAccess', _221 => _221.sceneUp])||oe).clone().normalize();a.quaternion.setFromUnitVectors(new E.Vector3(0,0,1),s),a.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function Mn(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,i=t?t.clientHeight:window.innerHeight,o=new E.PerspectiveCamera(e.camera.fov,r/i,e.camera.near,e.camera.far),a=e.camera.position;return a&&o.position.set(a.x,a.y,a.z),o}function Cn(e,n,t){let r=new E.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!1}),i=e.parentElement,o=i?i.clientWidth:window.innerWidth,a=i?i.clientHeight:window.innerHeight;return i&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),r.setSize(o,a,!1),r.setPixelRatio(t),n.render.enableShadows&&(r.shadowMap.enabled=!0,r.shadowMap.type=E.VSMShadowMap),r.toneMapping=n.render.toneMapping,r.toneMappingExposure=_nullishCoalesce(n.render.toneMappingExposure, () => (1)),r.outputColorSpace=E.SRGBColorSpace,r.sortObjects=!0,r}function An(e,n,t,r){let i=new Set,o=new Map,a=new E.Raycaster,s=new E.Vector2,l=new E.Vector2,c=()=>t.getActiveCamera(),d=p=>{let v=p;for(;v;){if(!v.visible)return!1;v=v.parent}return!0},m=()=>{let p=be(n);if(p.isEmpty()){_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("No objects to fit to view");return}t.frameBounds(p,!1)},u=typeof r.events.selectionColor=="string"?new E.Color(r.events.selectionColor):r.events.selectionColor instanceof E.Color?r.events.selectionColor:new E.Color("#ff0000"),f=()=>{i.forEach(p=>{let v=p;if(o.has(p)){let y=o.get(p),x=v.material;x instanceof E.Material?x.dispose():Array.isArray(x)&&x.forEach(B=>B.dispose()),v.material=y,o.delete(p);let A=p;for(;A.parent;)A=A.parent;A!==n&&(y instanceof E.Material?y.dispose():y.forEach(B=>B.dispose()))}}),i.clear()},b=p=>{let v=p;if(!(v.material instanceof E.Material))return!1;o.set(p,v.material);let y=v.material.clone();return p instanceof E.Mesh&&"emissive"in y?y.emissive=u.clone():"color"in y&&(y.color=u.clone()),v.material=y,!0},T=()=>{let p=be(n),v=p.isEmpty()?1:p.getSize(new E.Vector3).length();a.params.Points.threshold=v*.01},R=p=>{l.set(p.clientX,p.clientY)},M=p=>{let v=new E.Vector2(p.clientX,p.clientY);if(l.distanceTo(v)>5)return;let y=e.getBoundingClientRect();s.x=(p.clientX-y.left)/y.width*2-1,s.y=-((p.clientY-y.top)/y.height)*2+1,T(),a.setFromCamera(s,c());let x=a.intersectObjects(n.children,!0).filter(A=>d(A.object));if(x.length>0){let A=x[0].object;i.has(A)||(f(),i.add(A),b(A),_optionalChain([r, 'access', _222 => _222.events, 'optionalAccess', _223 => _223.onObjectSelected, 'optionalCall', _224 => _224(A)]),A instanceof E.Mesh&&Object.keys(A.userData).length>0&&_optionalChain([r, 'access', _225 => _225.events, 'optionalAccess', _226 => _226.onMeshMetadataClicked, 'optionalCall', _227 => _227(A.userData)]))}else f(),_optionalChain([r, 'access', _228 => _228.events, 'optionalAccess', _229 => _229.onBackgroundClicked, 'optionalCall', _230 => _230({x:s.x,y:s.y})])},h=p=>{let v=e.getBoundingClientRect();s.x=(p.clientX-v.left)/v.width*2-1,s.y=-((p.clientY-v.top)/v.height)*2+1,T(),a.setFromCamera(s,c());let y=a.intersectObjects(n.children,!0).filter(B=>d(B.object));if(y.length===0)return;let x=y[0].object;if(_optionalChain([r, 'access', _231 => _231.events, 'optionalAccess', _232 => _232.onMeshDoubleClicked, 'optionalCall', _233 => _233(x)]),!_optionalChain([r, 'access', _234 => _234.events, 'optionalAccess', _235 => _235.enableDoubleClickZoom]))return;let A=new E.Box3().setFromObject(x);A.isEmpty()||t.frameBounds(A,!0)},w=p=>{if(_optionalChain([r, 'access', _236 => _236.events, 'optionalAccess', _237 => _237.enableKeyboardControls]))switch(p.key.toLowerCase()){case"f":p.preventDefault(),m();break;case"escape":p.preventDefault(),f();break;case" ":p.preventDefault(),m();break}};return _optionalChain([r, 'access', _238 => _238.events, 'optionalAccess', _239 => _239.enableClickToFocus])&&(e.addEventListener("mousedown",R),e.addEventListener("click",M),e.addEventListener("dblclick",h)),_optionalChain([r, 'access', _240 => _240.events, 'optionalAccess', _241 => _241.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",w)),{dispose:()=>{e.removeEventListener("mousedown",R),e.removeEventListener("click",M),e.removeEventListener("dblclick",h),e.removeEventListener("keydown",w),f()},fitToView:m,clearSelection:f}}function Sn(e,n,t){let r=new (0, _OrbitControlsjs.OrbitControls)(e,n),i=t.camera.target;return i&&r.target.set(i.x,i.y,i.z),r.enableDamping=t.controls.enableDamping||!1,r.dampingFactor=t.controls.dampingFactor||.05,r.autoRotate=t.controls.autoRotate||!1,r.autoRotateSpeed=t.controls.autoRotateSpeed||.5,r.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),r.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),r.minDistance=t.controls.minDistance||.001,r.maxDistance=t.controls.maxDistance||1/0,r.screenSpacePanning=!1,r.maxPolarAngle=Math.PI,r.update(),r}function he(e,n,t,r=!0){return{x:e,y:n,z:t}}var On="#ffffff",Je=12,Pn=4e-4,Bn=12,Vn=.05;function Qe(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,i=[];for(let o of e)switch(o.kind){case"curve":{let a=kn(o,t,r);a&&i.push(a);break}case"point":{let a=Un(o,r);a&&i.push(a);break}default:{let s=o;_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(s.kind)}`);break}}return i}var Fn=2;function kn(e,n,t){if(!n)return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let r=zn(e.json,n);if(!r)return null;let i;try{i=_n(r,t)}catch(m){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("Failed to tessellate curve display item; skipping.",m),null}finally{se(r)}if(i.length<2)return null;let o=[];for(let m of i)o.push(m.x,m.y,m.z);let a=new _LineGeometryjs.LineGeometry;a.setPositions(o);let s=et(e.color,e.opacity),l=new (0, _LineMaterialjs.LineMaterial)({color:s.color}),c=l;c.linewidth=_nullishCoalesce(e.width, () => (Fn)),c.transparent=s.transparent,c.opacity=s.opacity;let d=new (0, _Line2js.Line2)(a,l);return d.computeLineDistances(),d.name=e.name,d.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Un(e,n){let{position:t}=e;if(!t||typeof t.X!="number"||!Number.isFinite(t.X)||typeof t.Y!="number"||!Number.isFinite(t.Y)||typeof t.Z!="number"||!Number.isFinite(t.Z))return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Skipping point display item with missing or non-finite position (id: ${String(e.id)}).`),null;let{x:r,y:i,z:o}=he(t.X,t.Y,t.Z,n),a=new $.BufferGeometry;a.setAttribute("position",new $.Float32BufferAttribute([r,i,o],3));let s=new $.PointsMaterial({...et(e.color,e.opacity),size:6,sizeAttenuation:!1}),l=new $.Points(a,s);return l.name=e.name,l.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},l}function se(e){_optionalChain([e, 'optionalAccess', _242 => _242.delete, 'optionalCall', _243 => _243()])}function zn(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(se(r),_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function _n(e,n){let t=jn(e,n);return t||Gn(e,n)}function jn(e,n){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),r=Array.isArray(t)?t[1]:t;if(!r||typeof r.count!="number"||r.count<2)return se(r),null;let i=[];for(let o=0;o<r.count;o++){let a=r.get(o),{x:s,y:l,z:c}=he(a[0],a[1],a[2],n);i.push(new $.Vector3(s,l,c))}return se(r),i}function Gn(e,n){let t=e.domain,r=t[0],o=t[1]-r,a=m=>{let u=e.pointAt(m),{x:f,y:b,z:T}=he(u[0],u[1],u[2],n);return new $.Vector3(f,b,T)},s=Nn(e),l=r,c=a(r),d=[c];for(let m=0;m<Je;m++){let u=r+o*(m+1)/Je,f=a(u);Re(l,c,u,f,a,s,Bn,d),d.push(f),l=u,c=f}return d}function Re(e,n,t,r,i,o,a,s){if(a<=0)return;let l=(e+t)/2,c=i(l),d=$n(c,n,r),m=Wn(n,c,r);d<=o&&m<=Vn||(Re(e,n,l,c,i,o,a-1,s),s.push(c),Re(l,c,t,r,i,o,a-1,s))}function Nn(e){let n=e.getBoundingBox(),t=n.min,r=n.max;se(n);let i=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(i*Pn,1e-6)}function Wn(e,n,t){let r=n.x-e.x,i=n.y-e.y,o=n.z-e.z,a=t.x-n.x,s=t.y-n.y,l=t.z-n.z,c=Math.sqrt(r*r+i*i+o*o),d=Math.sqrt(a*a+s*s+l*l);if(c===0||d===0)return 0;let m=r*a+i*s+o*l,u=Math.max(-1,Math.min(1,m/(c*d)));return Math.acos(u)}function $n(e,n,t){let r=t.x-n.x,i=t.y-n.y,o=t.z-n.z,a=r*r+i*i+o*o;if(a===0)return e.distanceTo(n);let s=e.x-n.x,l=e.y-n.y,c=e.z-n.z,d=Math.max(0,Math.min(1,(s*r+l*i+c*o)/a)),m=s-r*d,u=l-i*d,f=c-o*d;return Math.sqrt(m*m+u*u+f*f)}function et(e,n){let t=_nullishCoalesce(n, () => (1));return{color:new $.Color(_nullishCoalesce(e, () => (On))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var tt=1096174675,Xn= exports.x =1515605075,nt= exports.y =3,rt= exports.z =1,we= exports.A =1,qn= exports.B =2,Zn= exports.C =4,Kn= exports.D =8,Jn= exports.E =16,Do= exports.F =0,Qn= exports.G =1,ot=12,it=56,er=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;function xe(e){if(!er)throw new (0, _chunkCUQQ3ZBVcjs.d)("SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.",_chunkCUQQ3ZBVcjs.c.ENVIRONMENT_ERROR);let n=or(rr(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<ot)throw _("Blob too small to contain SLVA header.",{expectedBytes:ot,availableBytes:n.byteLength});let r=0,i=t.getUint32(r,!0);if(r+=4,i!==tt)throw _(`Invalid SLVA magic: 0x${i.toString(16)}`,{expectedMagic:`0x${tt.toString(16)}`,actualMagic:`0x${i.toString(16)}`});let o=t.getUint32(r,!0);if(r+=4,o<rt||o>nt)throw _(`Unsupported SLVA version: ${o}`,{minSupportedVersion:rt,maxSupportedVersion:nt,actualVersion:o});let a=t.getUint32(r,!0);if(r+=4,r+a>n.byteLength)throw _("Insufficient data to read metadata JSON.",{expectedBytes:a,availableBytes:n.byteLength-r,offset:r});let s=n.subarray(r,r+a);r+=a;let l;try{l=JSON.parse(ir(s))}catch(V){throw _(`Failed to parse metadata JSON: ${V instanceof Error?V.message:String(V)}`,{metadataLen:a})}if(r+it>n.byteLength)throw _("Insufficient data to read geometry header.",{expectedBytes:it,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let d=t.getFloat64(r,!0);r+=8;let m=t.getFloat64(r,!0);r+=8;let u=t.getFloat64(r,!0);r+=8;let f=t.getFloat64(r,!0);r+=8;let b=t.getFloat64(r,!0);r+=8;let T=t.getFloat64(r,!0);r+=8;let R=t.getUint32(r,!0);r+=4;let M=(c&we)!==0,h=(c&Zn)!==0,w=R*3,p=w*(M?4:2);if(r+p>n.byteLength)throw _("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:n.byteLength-r,offset:r,useFloat32:M,vertexCount:R});let v=n.byteOffset+r,y;if(M?y=st(n.buffer,v,w):h?y=cr(ve(n.buffer,v,w)):y=ar(n.buffer,v,w),r+=p,r+4>n.byteLength)throw _("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let x=t.getUint32(r,!0);r+=4;let A=(c&qn)!==0,G=x*(A?2:4);if(r+G>n.byteLength)throw _("Insufficient data to read indices.",{expectedBytes:G,availableBytes:n.byteLength-r,offset:r,indexCount:x,useUint16Indices:A});let F=A?ve(n.buffer,n.byteOffset+r,x):sr(n.buffer,n.byteOffset+r,x);h&&(F=F instanceof Uint16Array?ur(F):dr(F)),lr(F,R),r+=G;let Y=null;if((c&Kn)!==0){let V=tr(n,t,r,R,h);Y=V.uvs,r=V.offset}let J=null;return(c&Jn)!==0&&(J=nr(n,r,R,h)),{metadata:l,flags:c,vertices:y,indices:F,origin:[d,m,u],scale:[f,b,T],uvs:Y,colors:J}}var at=36;function tr(e,n,t,r,i){if(t+at>e.byteLength)throw _("Insufficient data to read UV chunk header.",{expectedBytes:at,availableBytes:e.byteLength-t,offset:t});let o=n.getUint32(t,!0);t+=4;let a=n.getFloat64(t,!0);t+=8;let s=n.getFloat64(t,!0);t+=8;let l=n.getFloat64(t,!0);t+=8;let c=n.getFloat64(t,!0);t+=8;let d=r*2,m=o===Qn,u=d*(m?4:2);if(t+u>e.byteLength)throw _("Insufficient data to read UV chunk.",{expectedBytes:u,availableBytes:e.byteLength-t,offset:t,uvFormat:o,vertexCount:r});let f=e.byteOffset+t,b;if(m)b=st(e.buffer,f,d).slice();else{let T=ve(e.buffer,f,d);b=new Float32Array(d);let R=0,M=0;for(let h=0;h<d;h+=2)i?(R=R+Z(T[h])&65535,M=M+Z(T[h+1])&65535):(R=T[h],M=T[h+1]),b[h]=a+R*l,b[h+1]=s+M*c}return{uvs:b,offset:t+u}}function nr(e,n,t,r){let i=t*3;if(n+i>e.byteLength)throw _("Insufficient data to read vertex-color chunk.",{expectedBytes:i,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let o=e.subarray(n,n+i);if(!r)return o.slice();let a=new Uint8Array(i),s=0,l=0,c=0;for(let d=0;d<i;d+=3)s=s+Z(o[d])&255,l=l+Z(o[d+1])&255,c=c+Z(o[d+2])&255,a[d]=s,a[d+1]=l,a[d+2]=c;return a}function rr(e){return typeof e=="string"?_chunkCUQQ3ZBVcjs.j.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function or(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==Xn)return e;let t=n.getUint32(4,!0),r=e.subarray(8),i=Math.max(r.byteLength*1032+1024,1<<20);if(t>i)throw _("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:i});let o;try{o=_fflate.inflateSync.call(void 0, r,{out:new Uint8Array(t+1)})}catch(a){throw _(`Failed to inflate SLVZ blob: ${a instanceof Error?a.message:String(a)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}if(o.byteLength!==t)throw _("SLVZ payload inflated to a different size than the header declares.",{declaredLen:t,actualLen:o.byteLength,deflatedBytes:r.byteLength});return o}function ir(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunkCUQQ3ZBVcjs.d)("No UTF-8 decoder available in this environment.",_chunkCUQQ3ZBVcjs.c.INVALID_STATE)}function ar(e,n,t){if(t===0)return new Int16Array(0);if(n%2===0)return new Int16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Int16Array(r.buffer)}function st(e,n,t){if(t===0)return new Float32Array(0);if(n%4===0)return new Float32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Float32Array(r.buffer)}function ve(e,n,t){if(t===0)return new Uint16Array(0);if(n%2===0)return new Uint16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Uint16Array(r.buffer)}function sr(e,n,t){if(t===0)return new Uint32Array(0);if(n%4===0)return new Uint32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Uint32Array(r.buffer)}function lr(e,n){if(e.length!==0&&!(e instanceof Uint16Array&&n>65535)){for(let t=0;t<e.length;t++)if(e[t]>=n)throw _("Index out of range of vertexCount.",{indexPosition:t,indexValue:e[t],vertexCount:n})}}function Z(e){return e>>>1^-(e&1)}function cr(e){let n=new Int16Array(e.length),t=0,r=0,i=0;for(let o=0;o<e.length;o+=3)t=t+Z(e[o])<<16>>16,r=r+Z(e[o+1])<<16>>16,i=i+Z(e[o+2])<<16>>16,n[o]=t,n[o+1]=r,n[o+2]=i;return n}function ur(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+Z(e[r])&65535,n[r]=t;return n}function dr(e){let n=new Uint32Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+Z(e[r])>>>0,n[r]=t;return n}function _(e,n){return new (0, _chunkCUQQ3ZBVcjs.d)(e,_chunkCUQQ3ZBVcjs.c.VALIDATION_ERROR,{context:n})}async function Uo(e,n){let{debug:t=!1}=_nullishCoalesce(n, () => ({})),r=t?performance.now():0,i,o=performance.now();try{i=JSON.parse(e)}catch(s){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).error("Error parsing mesh batch envelope JSON:",s),[]}let a=performance.now()-o;return await He(i,n,{parseTime:a,perfStart:r})}async function He(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:i=!0,debug:o=!1,material:a}=_nullishCoalesce(n, () => ({})),{parseTime:s=0,perfStart:l=o?performance.now():0}=_nullishCoalesce(t, () => ({}));if(!e.compressedData)return[];let c=performance.now(),d=xe(e.compressedData),m=performance.now()-c,u=o?br(e.compressedData):0;return lt(d,{mergeByMaterial:r,applyTransforms:i,debug:o,material:a,parseTime:s,decodeTime:m,perfStart:l,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}async function zo(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:i=!1,material:o}=_nullishCoalesce(n, () => ({})),a=i?performance.now():0,s=performance.now(),l=xe(e),c=performance.now()-s,d=e.byteLength;return lt(l,{mergeByMaterial:t,applyTransforms:r,debug:i,material:o,parseTime:0,decodeTime:c,perfStart:a,blobBytes:d})}function lt(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:i,material:o,parseTime:a,decodeTime:s,perfStart:l,blobBytes:c,fallback:d}=n,m=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([d, 'optionalAccess', _244 => _244.materials]))), () => ([])),u=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([d, 'optionalAccess', _245 => _245.groups]))), () => ([])),f=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _246 => _246.sourceComponentId]), () => (e.metadata.sourceComponentId)),b=(e.flags&we)!==0;mr(u,m.length,e.vertices.length/3,e.indices.length);let T=b?fr(e.vertices,r):pr(e.vertices,e.origin,e.scale,r);if(i){let L=e.vertices.byteLength+e.indices.byteLength;_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Materials: ${m.length} | Groups: ${u.length}`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Format: ${b?"float32":"int16 quantized"}`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(L/1024/1024).toFixed(2)} MB`)}let R=performance.now(),M=m.map(L=>Er(L,{vertexColors:e.colors!=null,appearance:o})),h=[];for(let L of u)if(t&&L.meshes.length>1){let p=gr(L,T,e.indices,M,e.uvs,e.colors);p.userData.sourceComponentId=_nullishCoalesce(f, () => (null)),h.push(p)}else{let p=yr(L,T,e.indices,M,e.uvs,e.colors);for(let v of p)v.userData.sourceComponentId=_nullishCoalesce(f, () => (null));h.push(...p)}let w=performance.now()-R;if(i){let L=performance.now()-l;_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug("Performance:"),a>0&&_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Decode binary: ${s.toFixed(2)}ms`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Create Meshes: ${w.toFixed(2)}ms`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Total: ${L.toFixed(2)}ms`)}return Promise.resolve(h)}function le(e,n){return new (0, _chunkCUQQ3ZBVcjs.d)(e,_chunkCUQQ3ZBVcjs.c.VALIDATION_ERROR,{context:n})}function mr(e,n,t,r){for(let i of e){if(!Number.isInteger(i.materialId)||i.materialId<0||i.materialId>=n)throw le("Group materialId out of range of the materials array.",{materialId:i.materialId,materialCount:n});for(let o of i.meshes){let a={vertexStart:o.vertexStart,vertexCount:o.vertexCount,indexStart:o.indexStart,indexCount:o.indexCount};for(let[s,l]of Object.entries(a))if(!Number.isInteger(l)||l<0)throw le(`Mesh metadata field "${s}" must be a non-negative integer.`,{meshName:o.name,field:s,value:l});if(o.vertexStart+o.vertexCount>t)throw le("Mesh vertex window exceeds the batch vertex buffer.",{meshName:o.name,vertexStart:o.vertexStart,vertexCount:o.vertexCount,totalVertexCount:t});if(o.indexStart+o.indexCount>r)throw le("Mesh index window exceeds the batch index buffer.",{meshName:o.name,indexStart:o.indexStart,indexCount:o.indexCount,totalIndexCount:r})}}}function ct(e,n){if(e<n.vertexStart||e>=n.vertexStart+n.vertexCount)throw le("Index references a vertex outside its mesh's vertex window.",{meshName:n.name,indexValue:e,vertexStart:n.vertexStart,vertexCount:n.vertexCount})}function pr(e,n,t,r){let i=new Float32Array(e.length),o=n[0],a=n[1],s=n[2],l=t[0],c=t[1],d=t[2];for(let m=0;m<e.length;m+=3)i[m]=o+(e[m]+32767)*l,i[m+1]=a+(e[m+1]+32767)*c,i[m+2]=s+(e[m+2]+32767)*d;return i}function fr(e,n){return e}function Er(e,n){let t=Fe(e.color),r=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _247 => _247.vertexColors]), () => (!1)),i=_optionalChain([n, 'optionalAccess', _248 => _248.appearance]),o=new P.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:r,side:_optionalChain([i, 'optionalAccess', _249 => _249.cullBackfaces])?P.FrontSide:P.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return _optionalChain([i, 'optionalAccess', _250 => _250.envMapIntensity])!=null&&(o.envMapIntensity=i.envMapIntensity),r&&hr(o),e.map&&Ke(o,e.map),o}function hr(e){e.onBeforeCompile=n=>{n.vertexShader=n.vertexShader.replace("#include <color_vertex>",`#include <color_vertex>
|
|
55
|
-
#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
|
|
56
|
-
vColor.rgb = mix(
|
|
57
|
-
vColor.rgb / 12.92,
|
|
58
|
-
pow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),
|
|
59
|
-
step( vec3( 0.04045 ), vColor.rgb )
|
|
60
|
-
);
|
|
61
|
-
#endif`)}}function gr(e,n,t,r,i=null,o=null){let a=0,s=0;for(let h of e.meshes)a+=h.vertexCount,s+=h.indexCount;let l=new Float32Array(a*3),c=new Uint32Array(s),d=i?new Float32Array(a*2):null,m=o?new Uint8Array(a*3):null,u=0,f=0;for(let h of e.meshes){let w=h.vertexStart*3,L=h.vertexCount*3;if(l.set(n.subarray(w,w+L),u*3),d&&i){let y=h.vertexStart*2;d.set(i.subarray(y,y+h.vertexCount*2),u*2)}m&&o&&m.set(o.subarray(w,w+L),u*3);let p=t.subarray(h.indexStart,h.indexStart+h.indexCount),v=u-h.vertexStart;for(let y=0;y<p.length;y++){let x=p[y];ct(x,h),c[f+y]=x+v}u+=h.vertexCount,f+=h.indexCount}let b=new P.BufferGeometry;b.setAttribute("position",new P.BufferAttribute(l,3)),b.setIndex(new P.BufferAttribute(c,1)),d&&b.setAttribute("uv",new P.BufferAttribute(d,2)),m&&b.setAttribute("color",new P.BufferAttribute(m,3,!0)),b.computeVertexNormals();let T=new P.Mesh(b,r[e.materialId]),R=e.meshes[0],M=e.meshes.map(h=>h.name).filter(h=>h&&h.length>0);return T.name=M.length>0?M[0]:`merged_material_${e.materialId}`,T.castShadow=!0,T.receiveShadow=!0,T.userData={source:"compute",name:T.name,layer:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _251 => _251.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _252 => _252.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _253 => _253.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(h=>({name:h.name,layer:h.layer,originalIndex:h.originalIndex}))},T}function yr(e,n,t,r,i=null,o=null){let a=[];for(let s of e.meshes){let l=s.vertexStart*3,c=s.vertexCount*3,d=n.slice(l,l+c),m=t.subarray(s.indexStart,s.indexStart+s.indexCount),u=new Uint32Array(m.length),f=s.vertexStart;for(let R=0;R<m.length;R++){let M=m[R];ct(M,s),u[R]=M-f}let b=new P.BufferGeometry;if(b.setAttribute("position",new P.BufferAttribute(d,3)),b.setIndex(new P.BufferAttribute(u,1)),i){let R=s.vertexStart*2,M=i.slice(R,R+s.vertexCount*2);b.setAttribute("uv",new P.BufferAttribute(M,2))}if(o){let R=o.slice(l,l+c);b.setAttribute("color",new P.BufferAttribute(R,3,!0))}b.computeVertexNormals();let T=new P.Mesh(b,r[e.materialId]);T.name=s.name,T.userData={source:"compute",name:s.name,layer:_nullishCoalesce(s.layer, () => ("")),originalIndex:s.originalIndex,metadata:_nullishCoalesce(s.metadata, () => ({}))},T.castShadow=!0,T.receiveShadow=!0,a.push(T)}return a}function br(e){return Math.floor(e.length*3/4)}var ut={Angstroms:1e-10,Nanometers:1e-9,Microns:1e-6,Millimeters:.001,Centimeters:.01,Decimeters:.1,Meters:1,Dekameters:10,Hectometers:100,Kilometers:1e3,Megameters:1e6,Gigameters:1e9,Microinches:254e-10,Mils:254e-7,Inches:.0254,Feet:.3048,Yards:.9144,Miles:1609.344,NauticalMiles:1852},Tr="Display",Rr="DisplayBatch";function vr(e){let n=e.split(".");return n.includes(Tr)||n.includes(Rr)}var dt=new Set;async function $o(e,n){let t=performance.now(),r=[],{allowScaling:i=!0,allowAutoPosition:o=!0,rhino:a,debug:s=!1,parsing:l={}}=_nullishCoalesce(n, () => ({}));try{let c=i?wr(e.modelunits):1;return await xr(e,r,c,l,a,s),o&&Ar(r),r}catch(c){throw Sr(c,r),c}finally{s&&Ir(t)}}function wr(e){let n=ut[e];return n!==void 0?n:(dt.has(e)||(dt.add(e),_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Unknown Rhino model unit "${e}" \u2014 geometry will not be scaled (factor 1). Known units: ${Object.keys(ut).join(", ")}.`)),1)}async function xr(e,n,t,r,i,o){for(let a of e.values){let s=a.InnerTree;for(let l in s){let c=s[l];c&&await Hr(c,n,t,r,i,o)}}}async function Hr(e,n,t,r,i,o){for(let a of e){if(!vr(a.type))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},l=Mr(a.data);if(!l){_chunkCUQQ3ZBVcjs.e.call(void 0, ).error("Error parsing display batch envelope: invalid JSON");continue}let c=await He(l,s),d=Qe(l.items,{rhino:i,applyTransforms:s.applyTransforms}),m=[...c,...d];if(t!==1)for(let u of m)u.scale.set(t,t,t);n.push(...m),o&&_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes and ${d.length} items from batch`)}}function Mr(e){return typeof e=="string"?Cr(e):e}function Cr(e){try{return JSON.parse(e)}catch (e3){return}}function Ar(e){if(e.length===0)return;let n=ie(e);ke(e,n.min.z,"z")}function Sr(e,n){_chunkCUQQ3ZBVcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Lr(n)}function Lr(e){for(let n of e){let t=n;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(r=>r.dispose()):t.material.dispose())}}function Ir(e){let n=performance.now()-e;_chunkCUQQ3ZBVcjs.e.call(void 0, ).info("Time to process meshes:",`${n.toFixed(2)}ms`)}exports.a = Rt; exports.b = Br; exports.c = Fe; exports.d = ke; exports.e = ie; exports.f = Ue; exports.g = ze; exports.h = _e; exports.i = ue; exports.j = Ge; exports.k = jt; exports.l = Wr; exports.m = Ne; exports.n = $e; exports.o = on; exports.p = qe; exports.q = an; exports.r = Ze; exports.s = ao; exports.t = En; exports.u = To; exports.v = Qe; exports.w = tt; exports.x = Xn; exports.y = nt; exports.z = rt; exports.A = we; exports.B = qn; exports.C = Zn; exports.D = Kn; exports.E = Jn; exports.F = Do; exports.G = Qn; exports.H = xe; exports.I = Uo; exports.J = He; exports.K = zo; exports.L = ut; exports.M = $o;
|
|
62
|
-
//# sourceMappingURL=chunk-727SRM4E.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-727SRM4E.cjs","../src/features/visualization/threejs/three-materials.ts","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/grid.ts","../src/features/visualization/threejs/edges.ts","../src/features/visualization/threejs/three-initializer.ts","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"names":["three_materials_exports","__export","CONCRETE_MATERIAL","EMISSIVE_MATERIAL","GLASS_MATERIAL","METAL_MATERIAL","PLASTIC_MATERIAL","RUBBER_MATERIAL","SHARED_MATERIALS","WOOD_MATERIAL","CAMERA_CONFIG","updateScene","scene","meshes","camera","controls","initialPositionSet","clearScene","mesh","unionBoundingBox","computeCombinedBoundingBox","center","size","maxDim","distance","parseColor","colorString","getLogger","trimmed","hex"],"mappings":"AAAA,2/BAAwE,ICAxEA,EAAAA,CAAA,CAAA,CAAA,CAAAC,iCAAAA,EAAAD,CAAA,CAAA,iBAAA,CAAA,CAAA,CAAA,EAAAE,EAAAA,CAAA,iBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,cAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,cAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,gBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,eAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,gBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,aAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAAA,CAAAA,CAAA,6gBAAuB,IAEVN,EAAAA,CAAoB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC/D,KAAA,CAAO,CAAA,CACP,QAAA,CAAU,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAClC,iBAAA,CAAmB,CAAA,CACnB,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,UAAA,CAAY,CAAA,CAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,WAAA,CAAa,CAAA,CAAA,CACb,SAAA,CAAW,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYE,EAAAA,CAAiB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC5D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,CAAQ,CAAA,CAC/B,SAAA,CAAW,EAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,GAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,CAAA,CACd,GAAA,CAAK,GAAA,CACL,SAAA,CAAW,CAAA,CACX,UAAA,CAAY,CAAA,CAAA,CACZ,WAAA,CAAa,CAAA,CAAA,CACb,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYH,EAAAA,CAAoB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC/D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,GAAA,CACX,eAAA,CAAiB,GAAA,CACjB,SAAA,CAAW,GAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,GAAA,CACd,YAAA,CAAc,CAAA,CACd,GAAA,CAAK,IAAA,CACL,SAAA,CAAW,CAAA,CACX,UAAA,CAAY,CAAA,CAAA,CACZ,WAAA,CAAa,CAAA,CAAA,CAGb,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYI,EAAAA,CAAmB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC9D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,WAAA,CAAa,CAAA,CAAA,CACb,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYF,EAAAA,CAAiB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC5D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAGX,YAAA,CAAc,GAAA,CACd,WAAA,CAAa,CAAA,CAAA,CAGb,UAAA,CAAY,CAAA,CAAA,CACZ,eAAA,CAAiB,CAAA,CACjB,SAAA,CAAW,CAAA,CACX,kBAAA,CAAoB,CAAA,CACpB,GAAA,CAAK,IAAA,CACL,YAAA,CAAc,EAAA,CACd,SAAA,CAAW,CAAA,CACX,IAAA,CAAY,CAAA,CAAA,UAAA,CACZ,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYG,EAAAA,CAAkB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC7D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,OAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYE,EAAAA,CAAgB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC3D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,OAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAGYD,EAAAA,CAAgD,IAAI,GAAA,CAAoB,CACpFL,EAAAA,CACAE,EAAAA,CACAH,EAAAA,CACAI,EAAAA,CACAF,EAAAA,CACAG,EAAAA,CACAE,EACD,CAAC,CAAA,CCxJD,IAMMC,CAAAA,CAAgB,CACrB,cAAA,CAAgB,GAAA,CAChB,eAAA,CAAiB,GAAA,CACjB,qBAAA,CAAuB,GAAA,CACvB,iBAAA,CAAmB,CAClB,IAAA,CAAM,IAAA,CACN,KAAA,CAAO,IAAA,CACP,MAAA,CAAQ,GACT,CAAA,CACA,gBAAA,CAAkB,CACjB,IAAA,CAAM,GAAA,CACN,KAAA,CAAO,EAAA,CACP,MAAA,CAAQ,EACT,CAAA,CACA,2BAAA,CAA6B,CAC9B,CAAA,CAGO,SAASC,EAAAA,CACfC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CAGD,EAAA,CAFAC,EAAAA,CAAWL,CAAK,CAAA,CAEZC,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAGzBA,CAAAA,CAAO,OAAA,CAASK,CAAAA,EAAS,CACxBN,CAAAA,CAAM,GAAA,CAAIM,CAAI,CACf,CAAC,CAAA,CAGD,IAAMC,CAAAA,CAAmBC,EAAAA,CAA2BP,CAAM,CAAA,CAGpDQ,CAAAA,CAASF,CAAAA,CAAiB,SAAA,CAAU,IAAU,CAAA,CAAA,OAAS,CAAA,CACvDG,CAAAA,CAAOH,CAAAA,CAAiB,OAAA,CAAQ,IAAU,CAAA,CAAA,OAAS,CAAA,CAGnDI,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAID,CAAAA,CAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,CAAGA,CAAAA,CAAK,CAAC,CAAA,CA0B9C,EAAA,CAtBmBC,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAID,CAAAA,CAAK,CAAA,EAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,EAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,EAAK,CAAC,CAAA,CAEzDZ,CAAAA,CAAc,qBAAA,EAAyBa,CAAAA,CAASb,CAAAA,CAAc,cAAA,CAAA,CAE9EI,CAAAA,CAAO,IAAA,CAAOS,CAAAA,CAASb,CAAAA,CAAc,iBAAA,CAAkB,IAAA,CACvDI,CAAAA,CAAO,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,gBAAA,CAAiB,IAAA,CAAA,CAC3Ca,CAAAA,CAASb,CAAAA,CAAc,eAAA,CAAA,CAEjCI,CAAAA,CAAO,IAAA,CAAOS,CAAAA,CAASb,CAAAA,CAAc,iBAAA,CAAkB,KAAA,CACvDI,CAAAA,CAAO,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,gBAAA,CAAiB,KAAA,CAAA,CAAA,CAGrDI,CAAAA,CAAO,IAAA,CAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,iBAAA,CAAkB,MAAM,CAAA,CAC5EI,CAAAA,CAAO,GAAA,CAAM,IAAA,CAAK,GAAA,CAAI,GAAA,CAAMS,CAAAA,CAASb,CAAAA,CAAc,gBAAA,CAAiB,MAAM,CAAA,CAAA,CAG3EI,CAAAA,CAAO,sBAAA,CAAuB,CAAA,CAM1B,CAACE,CAAAA,CAAoB,CACxB,IAAMQ,CAAAA,CAAWD,CAAAA,CAASb,CAAAA,CAAc,2BAAA,CAExCI,CAAAA,CAAO,QAAA,CAAS,GAAA,CAAIO,CAAAA,CAAO,CAAA,CAAIG,CAAAA,CAAW,EAAA,CAAKH,CAAAA,CAAO,CAAA,CAAIG,CAAAA,CAAUH,CAAAA,CAAO,CAAA,CAAIG,CAAAA,CAAW,GAAG,CAAA,CAC7FT,CAAAA,CAAS,MAAA,CAAO,IAAA,CAAKM,CAAM,CAAA,CAE3BN,CAAAA,CAAS,MAAA,CAAO,CACjB,CACD,CAGO,SAASU,EAAAA,CAAWC,CAAAA,CAAkC,CAC5D,EAAA,CAAI,CAACA,CAAAA,EAAe,OAAOA,CAAAA,EAAgB,QAAA,CAC1C,OAAAC,iCAAAA,CAAU,CAAE,IAAA,CAAK,CAAA,qBAAA,EAAwBD,CAAW,CAAA,aAAA,CAAe,CAAA,CAC5D,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAGhC,IAAME,CAAAA,CAAUF,CAAAA,CAAY,IAAA,CAAK,CAAA,CAGjC,EAAA,CAAI,oBAAA,CAAqB,IAAA,CAAKE,CAAO,CAAA,CACpC,GAAI,CACH,IAAMC,CAAAA,CAAMD,CAAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAU,CAAA,CAAA,EAAIA,CAAO,CAAA,CAAA;AC1D/B;AAAA;AAAA;AAAA;AAAA;AAAA;AASE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AC4GvB;AC1JD,QAAA;AC+dN;AAAA;AAAA;AAAA;AAAA;AAAA;AClPY,SAAA","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-727SRM4E.cjs","sourcesContent":[null,"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';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { getLogger } from '@/core';\n\nimport { SHARED_MATERIALS } from './three-materials';\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\tcamera.position.set(center.x + distance * 0.8, center.y + distance, center.z + distance * 1.2);\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.\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/** IDs of scene infrastructure that survives content updates (floor, grid, label layer). */\nconst PERSISTENT_SCENE_IDS = new Set(['floor', 'grid', 'label-layer']);\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\trenderable.geometry?.dispose();\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';\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/** Plane to lay the grid on. 'y' = horizontal ground (Three Y-up). Default 'y'. */\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\tsetVisible(visible: boolean): void;\n\tdispose(): void;\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\tconst size = fadeDistance * 2.5; // comfortably larger than the fade radius\n\tconst geometry = new THREE.PlaneGeometry(size, size);\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\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},\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 { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';\nimport { LineSegments2 } from 'three/addons/lines/LineSegments2.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\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 * Built with `EdgesGeometry` (which keeps only edges whose adjacent faces meet above a threshold\n * angle, so flat tessellation noise is dropped) rendered as a fat `LineSegments2` using the same\n * `LineMaterial` family as curves (Phase 1) — so edges get controllable thickness, not the 1px cap\n * of `THREE.LineSegments`. The overlay is added as a *child* of each mesh, so it inherits the mesh's\n * transform and is disposed when the mesh subtree is cleared.\n */\n\nexport interface EdgeOptions {\n\t/** Edge color. Default near-black. */\n\tcolor?: THREE.ColorRepresentation;\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 30. Higher = fewer edges (only sharp creases); lower = more (catches gentle bends).\n\t */\n\tthresholdAngle?: 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\nconst DEFAULT_EDGE_COLOR = 0x222222;\nconst DEFAULT_EDGE_WIDTH = 1.5;\nconst DEFAULT_THRESHOLD_ANGLE = 30;\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}\nconst edgeGeometryCache = new WeakMap<THREE.BufferGeometry, Map<number, EdgeGeometryEntry>>();\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/**\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 */\nexport function addEdges(root: THREE.Object3D, options: EdgeOptions = {}): LineSegments2[] {\n\tconst color = new THREE.Color(options.color ?? DEFAULT_EDGE_COLOR);\n\tconst width = options.width ?? DEFAULT_EDGE_WIDTH;\n\tconst thresholdAngle = options.thresholdAngle ?? DEFAULT_THRESHOLD_ANGLE;\n\n\tconst created: LineSegments2[] = [];\n\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\tconst overlay = buildEdgeOverlay(object.geometry, color, width, thresholdAngle);\n\t\tobject.add(overlay); // child → inherits transform, disposed with the parent subtree\n\t\tcreated.push(overlay);\n\t});\n\n\treturn created;\n}\n\n/** Get (or extract and cache) the shared edge line geometry for a source geometry + crease angle. */\nfunction acquireEdgeGeometry(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number\n): LineSegmentsGeometry {\n\tlet byAngle = edgeGeometryCache.get(geometry);\n\tif (!byAngle) {\n\t\tbyAngle = new Map();\n\t\tedgeGeometryCache.set(geometry, byAngle);\n\t}\n\n\tlet entry = byAngle.get(thresholdAngle);\n\tif (!entry) {\n\t\tconst edges = new THREE.EdgesGeometry(geometry, thresholdAngle);\n\n\t\t// EdgesGeometry yields a Float32Array of line-segment endpoint pairs; LineSegmentsGeometry\n\t\t// consumes it as-is (round-tripping through Array.from would box every vertex into a JS array\n\t\t// only for setPositions to convert it straight back).\n\t\tconst lineGeometry = new LineSegmentsGeometry();\n\t\tlineGeometry.setPositions(edges.attributes.position.array as Float32Array);\n\t\tedges.dispose(); // frees only GPU-side state; the CPU array now backs the line geometry\n\n\t\tentry = { geometry: lineGeometry, refCount: 0 };\n\t\tbyAngle.set(thresholdAngle, entry);\n\t}\n\n\tentry.refCount += 1;\n\treturn entry.geometry;\n}\n\n/** Refcounted inverse of {@link acquireEdgeGeometry}: dispose only when the last overlay 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\nfunction buildEdgeOverlay(\n\tgeometry: THREE.BufferGeometry,\n\tcolor: THREE.Color,\n\twidth: number,\n\tthresholdAngle: number\n): LineSegments2 {\n\tconst lineGeometry = acquireEdgeGeometry(geometry, thresholdAngle);\n\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// Pull edges slightly toward the camera in depth so they don't z-fight the shaded surface.\n\t// The fat-line quads face the screen, so their depth slope is ~0 and the slope-scaled factor\n\t// term contributes nothing — the constant `units` term has to do the work. -1 unit is a single\n\t// depth ULP, which still stipples at glancing angles / far zoom on 24-bit depth buffers; a few\n\t// ULPs clears the surface reliably without visibly floating the edges.\n\tmaterial.polygonOffset = true;\n\tmaterial.polygonOffsetFactor = -1;\n\tmaterial.polygonOffsetUnits = -4;\n\n\tconst overlay = new LineSegments2(lineGeometry, 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 = geometry;\n\toverlay.userData.edgeThresholdAngle = thresholdAngle;\n\toverlay.raycast = () => {}; // never pickable; clicks should hit the mesh, not its outline\n\treturn overlay;\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/**\n * Remove every edge overlay under `root`, disposing its geometry and material. The inverse of\n * {@link addEdges}; together they make edges a live on/off toggle. Returns how many were removed.\n */\nexport function removeEdges(root: THREE.Object3D): number {\n\tconst overlays: LineSegments2[] = [];\n\troot.traverse((object) => {\n\t\tif (object instanceof LineSegments2 && isEdgeOverlay(object)) overlays.push(object);\n\t});\n\n\tfor (const overlay of overlays) {\n\t\treleaseEdgeGeometry(overlay); // geometry may be shared across overlays — refcounted dispose\n\t\t(overlay.material as LineMaterial).dispose();\n\t\toverlay.removeFromParent();\n\t}\n\treturn overlays.length;\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 { addEdges } from './edges';\nimport { createRenderPipeline, type RenderPipeline } from './render-pipeline';\nimport { createLabelLayer, type LabelLayer } from './label-layer';\nimport { createMeasureTool, type MeasureTool } from './measure';\nimport { setTextureAnisotropy } from '../webdisplay/texture-cache';\n\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// The default \"just works\" look: ACES + hemisphere fill + lifted HDR so products are well-lit\n\t// regardless of the environment map, while ambient stays low so colour doesn't wash out.\n\tstudio: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.3,\n\t\tenvironmentIntensity: 1.2,\n\t\themisphereIntensity: 1.0,\n\t\tambientIntensity: 0.3,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Flat CAD/drawing look: neutral tone mapping, low IBL, no fill — full flat ambient only.\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.5,\n\t\tenvironmentIntensity: 1,\n\t\themisphereIntensity: 0,\n\t\tambientIntensity: 1,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Punchier presentation: like studio but stronger IBL/fill and a touch more exposure.\n\tshowcase: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1.05,\n\t\tenvMapIntensity: 1.6,\n\t\tenvironmentIntensity: 1.35,\n\t\themisphereIntensity: 1.2,\n\t\tambientIntensity: 0.25,\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/** Map an up vector to the grid's ground-plane axis (the axis the grid is laid perpendicular to). */\nfunction upToGroundPlane(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 (az >= ax && az >= ay) return 'z';\n\tif (ay >= ax && ay >= az) return 'y';\n\treturn 'x';\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.\n\t */\n\tapplyEdges: (root: THREE.Object3D) => 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\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, 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\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\tconst gizmo = config.gizmo.enabled\n\t\t? createViewGizmo({ camera, domElement: canvas, controller: cameraController })\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// 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\tconst applyEdges = (root: THREE.Object3D) => {\n\t\taddEdges(root, {\n\t\t\tcolor: config.edges.color,\n\t\t\twidth: config.edges.width,\n\t\t\tthresholdAngle: config.edges.thresholdAngle\n\t\t});\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 AO postprocessing pipeline. Held in a mutable so it can be toggled at runtime\n\t// (setAmbientOcclusion below); the loop reads it through getRenderPipeline each frame. When null,\n\t// the loop uses the plain renderer.render path. Retargeted to the active camera every frame.\n\tlet renderPipeline: RenderPipeline | null = null;\n\n\tconst buildPipeline = (): 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\taoIntensity: config.render.aoIntensity,\n\t\t\t\taoPixelRatio: config.render.aoPixelRatio\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\tconst setAmbientOcclusion = (enabled: boolean) => {\n\t\tif (enabled && !renderPipeline) {\n\t\t\trenderPipeline = buildPipeline();\n\t\t} else if (!enabled && renderPipeline) {\n\t\t\trenderPipeline.dispose();\n\t\t\trenderPipeline = null;\n\t\t}\n\t};\n\n\tif (config.render.ambientOcclusion) renderPipeline = buildPipeline();\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};\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};\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 AO is on, tone mapping is applied by the composer's OutputPass — rebuild so it adopts\n\t\t// the new exposure.\n\t\tif (renderPipeline) {\n\t\t\tsetAmbientOcclusion(false);\n\t\t\tsetAmbientOcclusion(true);\n\t\t}\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) {\n\t\t\tsetAmbientOcclusion(false);\n\t\t\tsetAmbientOcclusion(true);\n\t\t}\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\tif (renderPipeline) {\n\t\t\t// Rebuild so the composer's OutputPass adopts the new tone mapping, then honor the target AO.\n\t\t\tsetAmbientOcclusion(false);\n\t\t\tsetAmbientOcclusion(preset.ambientOcclusion);\n\t\t} else {\n\t\t\tsetAmbientOcclusion(preset.ambientOcclusion);\n\t\t}\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};\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 { animate, dispose: disposeAnimation } = 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);\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. Hosts that add\n\t// geometry later (via updateScene) should call updateShadowBounds again afterwards.\n\tupdateShadowBounds();\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\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\tsetAmbientOcclusion,\n\t\tsetLook,\n\t\tsetFillLights,\n\t\tsetEnvironmentIntensity,\n\t\tsetToneMappingExposure,\n\t\tsetAoIntensity,\n\t\tgetMaterialAppearance,\n\t\tupdateShadowBounds,\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 for a Z-up scene: back-left and ABOVE (height on +Z).\n\t\t\tposition:\n\t\t\t\toptions.camera?.position ||\n\t\t\t\tnew THREE.Vector3(\n\t\t\t\t\t-defaults.cameraDistance,\n\t\t\t\t\t-defaults.cameraDistance,\n\t\t\t\t\tdefaults.cameraDistance\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},\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 in a Z-up scene: height on +Z, offset across X/Y.\n\t\t\tsunlightPosition:\n\t\t\t\toptions.lighting?.sunlightPosition ||\n\t\t\t\tnew THREE.Vector3(defaults.lightDistance, defaults.lightDistance, defaults.lightHeight),\n\t\t\tambientLightColor: options.lighting?.ambientLightColor || new THREE.Color(0x404040),\n\t\t\t// The look sets ambient (low on studio/showcase, where the hemisphere fill carries the lift\n\t\t\t// instead; full on technical). 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},\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 ?? upToGroundPlane(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\tcolor: options.edges?.color ?? 0x222222,\n\t\t\twidth: options.edges?.width ?? 1.5,\n\t\t\tthresholdAngle: options.edges?.thresholdAngle ?? 30\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 * Viewer aids (grid, floor, label overlay, measure markers) are not scene *content* — exclude them\n * from fit-to-view bounds and other content queries. Tagged via `userData.id` at creation.\n */\nconst VIEWER_AID_IDS = new Set(['grid', 'floor', 'label-layer', 'measure']);\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 bounds of the scene's renderable *content* — every visible mesh/line/points, with\n * viewer aids excluded. The grid (a huge camera-tracking plane) and the floor would otherwise\n * dominate the box. Shared by fit-to-view, pick-threshold scaling, and shadow-frustum fitting so\n * they all measure the same thing. Returns an empty Box3 when there is no content.\n */\nfunction computeContentBounds(scene: THREE.Scene): THREE.Box3 {\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/**\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): { animate: () => void; dispose: () => void } {\n\tlet animationId: number | null = null;\n\tlet lastTime = performance.now();\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}\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\tonFrame?.(delta);\n\n\t\tconst activeCamera = getActiveCamera();\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};\n\n\treturn { animate, dispose };\n}\n\nfunction setupEnvironment(\n\tscene: THREE.Scene,\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\t\t\t\tscene.environment = envMap;\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\tif (config.environment.showEnvironment) {\n\t\t\t\t\tscene.background = envMap;\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 { parseColor } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch } from './binary-parser.js';\nimport { applyTextureMap } from './texture-cache.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\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\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. The\n\t// Z-up -> Y-up rotation, when requested, is folded into the same pass.\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 * Asserts an index value falls inside 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 */\nfunction assertIndexInWindow(indexValue: number, meshMeta: MeshMetadata): void {\n\tif (\n\t\tindexValue < meshMeta.vertexStart ||\n\t\tindexValue >= meshMeta.vertexStart + meshMeta.vertexCount\n\t) {\n\t\tthrow metadataFail(\"Index references a vertex outside its mesh's vertex window.\", {\n\t\t\tmeshName: meshMeta.name,\n\t\t\tindexValue,\n\t\t\tvertexStart: meshMeta.vertexStart,\n\t\t\tvertexCount: meshMeta.vertexCount\n\t\t});\n\t}\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// MATERIAL CONSTRUCTION\n// ============================================================================\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// 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\tlet totalVertexCount = 0;\n\tlet totalIndexCount = 0;\n\tfor (const meshMeta of group.meshes) {\n\t\ttotalVertexCount += meshMeta.vertexCount;\n\t\ttotalIndexCount += meshMeta.indexCount;\n\t}\n\n\tconst mergedVertices = new Float32Array(totalVertexCount * 3);\n\tconst mergedIndices = new Uint32Array(totalIndexCount);\n\tconst mergedUvs = allUvs ? new Float32Array(totalVertexCount * 2) : null;\n\tconst mergedColors = allColors ? new Uint8Array(totalVertexCount * 3) : null;\n\n\tlet vertexWriteCursor = 0;\n\tlet indexWriteCursor = 0;\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\t\tmergedVertices.set(\n\t\t\tallVertices.subarray(componentStart, componentStart + componentLen),\n\t\t\tvertexWriteCursor * 3\n\t\t);\n\n\t\tif (mergedUvs && allUvs) {\n\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\tmergedUvs.set(\n\t\t\t\tallUvs.subarray(uvStart, uvStart + meshMeta.vertexCount * 2),\n\t\t\t\tvertexWriteCursor * 2\n\t\t\t);\n\t\t}\n\n\t\tif (mergedColors && allColors) {\n\t\t\tmergedColors.set(\n\t\t\t\tallColors.subarray(componentStart, componentStart + componentLen),\n\t\t\t\tvertexWriteCursor * 3\n\t\t\t);\n\t\t}\n\n\t\tconst indicesSlice = allIndices.subarray(\n\t\t\tmeshMeta.indexStart,\n\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t);\n\t\tconst indexShift = vertexWriteCursor - meshMeta.vertexStart;\n\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\tassertIndexInWindow(indexValue, meshMeta);\n\t\t\tmergedIndices[indexWriteCursor + i] = indexValue + indexShift;\n\t\t}\n\n\t\tvertexWriteCursor += meshMeta.vertexCount;\n\t\tindexWriteCursor += meshMeta.indexCount;\n\t}\n\n\tconst geometry = new THREE.BufferGeometry();\n\tgeometry.setAttribute('position', new THREE.BufferAttribute(mergedVertices, 3));\n\tgeometry.setIndex(new THREE.BufferAttribute(mergedIndices, 1));\n\tif (mergedUvs) {\n\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(mergedUvs, 2));\n\t}\n\tif (mergedColors) {\n\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(mergedColors, 3, true));\n\t}\n\tgeometry.computeVertexNormals();\n\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// `subarray` returns a view; copy via `slice` so the BufferAttribute owns its memory and\n\t\t// downstream code (dispose/reuse) can't surprise us by sharing the parser's buffer.\n\t\tconst vertices = allVertices.slice(componentStart, componentStart + componentLen);\n\n\t\tconst indicesSlice = allIndices.subarray(\n\t\t\tmeshMeta.indexStart,\n\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t);\n\t\tconst rebasedIndices = new Uint32Array(indicesSlice.length);\n\t\tconst baseIndex = meshMeta.vertexStart;\n\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\tassertIndexInWindow(indexValue, meshMeta);\n\t\t\trebasedIndices[i] = indexValue - baseIndex;\n\t\t}\n\n\t\tconst geometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\t\tgeometry.setIndex(new THREE.BufferAttribute(rebasedIndices, 1));\n\t\tif (allUvs) {\n\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\tconst uvs = allUvs.slice(uvStart, uvStart + meshMeta.vertexCount * 2);\n\t\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));\n\t\t}\n\t\tif (allColors) {\n\t\t\tconst colors = allColors.slice(componentStart, componentStart + componentLen);\n\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3, true));\n\t\t}\n\t\tgeometry.computeVertexNormals();\n\n\t\tconst mesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\t\tmesh.name = meshMeta.name;\n\t\tmesh.userData = {\n\t\t\tsource: 'compute',\n\t\t\tname: meshMeta.name,\n\t\t\tlayer: meshMeta.layer ?? '',\n\t\t\toriginalIndex: meshMeta.originalIndex,\n\t\t\tmetadata: meshMeta.metadata ?? {}\n\t\t};\n\t\tmesh.castShadow = true;\n\t\tmesh.receiveShadow = true;\n\n\t\tmeshes.push(mesh);\n\t}\n\n\treturn meshes;\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 { 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 * // With advanced options\n * const meshes = await getThreeMeshesFromComputeResponse(response, {\n * debug: true,\n * allowScaling: true,\n * allowAutoPosition: false,\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\tallowAutoPosition = true,\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);\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 * Applies vertical offset to position objects on the Z=0 plane (the ground of the unified\n * Z-up scene frame — see ../coordinate-transform.ts).\n */\nfunction applyGroundOffset(meshes: THREE.Object3D[]): void {\n\tif (meshes.length === 0) return;\n\n\tconst combinedBoundingBox = computeCombinedBoundingBox(meshes);\n\tapplyOffset(meshes, combinedBoundingBox.min.z, 'z');\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"]}
|