u-space 0.0.32 → 0.0.33

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/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("./Viewer-BKNV67Jj.cjs"),o=require("three/webgpu"),pe=require("three/addons/loaders/GLTFLoader.js"),Ee=require("three/addons/loaders/FBXLoader.js"),St=require("three/addons/loaders/OBJLoader.js"),Et=require("three/addons/loaders/STLLoader.js"),vt=require("three/addons/loaders/DRACOLoader.js"),It=require("three/addons/loaders/KTX2Loader.js"),de=require("three/addons/libs/meshopt_decoder.module.js"),ee=require("./modelDecodeProtocol-D1Apm9iG.cjs"),Ct=require("three/addons/loaders/HDRLoader.js"),Me=require("three/addons/utils/SkeletonUtils.js"),g=require("three/tsl"),Bt=require("three/addons/tsl/display/OutlineNode.js"),T=require("three/addons/libs/tween.module.js"),Ot=require("three/addons/utils/BufferGeometryUtils.js"),At=require("three/addons/renderers/CSS2DRenderer.js"),et=require("three/addons/renderers/CSS3DRenderer.js");class _t extends o.EventDispatcher{scene;camera;domElement;_container;_selected=new Set;_boxSelectionEnabled=!1;_isSelecting=!1;_startPoint=new o.Vector2;_endPoint=new o.Vector2;_selectionBox=null;_deep=!0;targetObjects=null;constructor(e,t,s){super(),this.domElement=e,this._container=e.parentElement??e,this.scene=t,this.camera=s}get selected(){return this._selected}get selectedArray(){return Array.from(this._selected)}select(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.has(n)||(this._selected.add(n),s.push(n));s.length>0&&(this.dispatchEvent({type:"select",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}deselect(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.delete(n)&&s.push(n);s.length>0&&(this.dispatchEvent({type:"deselect",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}toggle(e){this._selected.has(e)?this.deselect(e):this.select(e)}clear(){if(this._selected.size===0)return;const e=Array.from(this._selected);this._selected.clear(),this.dispatchEvent({type:"deselect",objects:e}),this.dispatchEvent({type:"change",selected:this._selected})}isSelected(e){return this._selected.has(e)}enableBoxSelection(e={}){this._boxSelectionEnabled||(this._boxSelectionEnabled=!0,this._deep=e.deep??!0,this._selectionBox=document.createElement("div"),this._selectionBox.style.cssText=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("./Viewer-BKNV67Jj.cjs"),c=require("three/webgpu"),fe=require("three/addons/loaders/GLTFLoader.js"),ve=require("three/addons/loaders/FBXLoader.js"),vt=require("three/addons/loaders/OBJLoader.js"),Ct=require("three/addons/loaders/STLLoader.js"),It=require("three/addons/loaders/DRACOLoader.js"),Ot=require("three/addons/loaders/KTX2Loader.js"),ue=require("three/addons/libs/meshopt_decoder.module.js"),j=require("./modelDecodeProtocol-pgjndTph.cjs"),Bt=require("three/addons/loaders/HDRLoader.js"),xe=require("three/addons/utils/SkeletonUtils.js"),b=require("three/tsl"),Lt=require("three/addons/tsl/display/OutlineNode.js"),R=require("three/addons/libs/tween.module.js"),At=require("three/addons/utils/BufferGeometryUtils.js"),_t=require("three/addons/renderers/CSS2DRenderer.js"),tt=require("three/addons/renderers/CSS3DRenderer.js");class Tt extends c.EventDispatcher{scene;camera;domElement;_container;_selected=new Set;_boxSelectionEnabled=!1;_isSelecting=!1;_startPoint=new c.Vector2;_endPoint=new c.Vector2;_selectionBox=null;_deep=!0;targetObjects=null;constructor(e,t,s){super(),this.domElement=e,this._container=e.parentElement??e,this.scene=t,this.camera=s}get selected(){return this._selected}get selectedArray(){return Array.from(this._selected)}select(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.has(n)||(this._selected.add(n),s.push(n));s.length>0&&(this.dispatchEvent({type:"select",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}deselect(e){const t=Array.isArray(e)?e:[e],s=[];for(const n of t)this._selected.delete(n)&&s.push(n);s.length>0&&(this.dispatchEvent({type:"deselect",objects:s}),this.dispatchEvent({type:"change",selected:this._selected}))}toggle(e){this._selected.has(e)?this.deselect(e):this.select(e)}clear(){if(this._selected.size===0)return;const e=Array.from(this._selected);this._selected.clear(),this.dispatchEvent({type:"deselect",objects:e}),this.dispatchEvent({type:"change",selected:this._selected})}isSelected(e){return this._selected.has(e)}enableBoxSelection(e={}){this._boxSelectionEnabled||(this._boxSelectionEnabled=!0,this._deep=e.deep??!0,this._selectionBox=document.createElement("div"),this._selectionBox.style.cssText=`
2
2
  position: absolute;
3
3
  border: 1px dashed #55aaff;
4
4
  background: rgba(75, 160, 255, 0.15);
5
5
  pointer-events: none;
6
6
  display: none;
7
7
  z-index: 9999;
8
- `,e.className&&(this._selectionBox.className=e.className),this._container.style.position=this._container.style.position||"relative",this._container.appendChild(this._selectionBox),this.domElement.addEventListener("pointerdown",this._onBoxPointerDown),this.domElement.addEventListener("pointermove",this._onBoxPointerMove),this.domElement.addEventListener("pointerup",this._onBoxPointerUp))}disableBoxSelection(){this._boxSelectionEnabled&&(this._boxSelectionEnabled=!1,this.domElement.removeEventListener("pointerdown",this._onBoxPointerDown),this.domElement.removeEventListener("pointermove",this._onBoxPointerMove),this.domElement.removeEventListener("pointerup",this._onBoxPointerUp),this._selectionBox&&(this._selectionBox.remove(),this._selectionBox=null))}setCamera(e){this.camera=e}_onBoxPointerDown=e=>{if(e.button!==0)return;this._isSelecting=!0;const t=this._container.getBoundingClientRect();this._startPoint.set(e.clientX-t.left,e.clientY-t.top),this._endPoint.copy(this._startPoint),this._selectionBox&&(this._selectionBox.style.display="block",this._updateBoxElement())};_onBoxPointerMove=e=>{if(!this._isSelecting)return;const t=this._container.getBoundingClientRect();this._endPoint.set(e.clientX-t.left,e.clientY-t.top),this._updateBoxElement()};_onBoxPointerUp=()=>{if(!this._isSelecting)return;this._isSelecting=!1,this._selectionBox&&(this._selectionBox.style.display="none");const e=this._getObjectsInBox();this.clear(),e.length>0&&this.select(e)};_updateBoxElement(){if(!this._selectionBox)return;const e=Math.min(this._startPoint.x,this._endPoint.x),t=Math.min(this._startPoint.y,this._endPoint.y),s=Math.abs(this._endPoint.x-this._startPoint.x),n=Math.abs(this._endPoint.y-this._startPoint.y);this._selectionBox.style.left=`${e}px`,this._selectionBox.style.top=`${t}px`,this._selectionBox.style.width=`${s}px`,this._selectionBox.style.height=`${n}px`}_getObjectsInBox(){const e=this._container.getBoundingClientRect(),t=e.width,s=e.height,n=new o.Vector2(this._startPoint.x/t*2-1,-(this._startPoint.y/s)*2+1),r=new o.Vector2(this._endPoint.x/t*2-1,-(this._endPoint.y/s)*2+1),a=new o.Box2(new o.Vector2(Math.min(n.x,r.x),Math.min(n.y,r.y)),new o.Vector2(Math.max(n.x,r.x),Math.max(n.y,r.y))),c=this.targetObjects||this.scene.children,l=[],h=new o.Matrix4;h.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);const d=u=>{if(!u.visible)return;const p=new o.Vector3;if(p.setFromMatrixPosition(u.matrixWorld),p.applyMatrix4(h),p.z>-1&&p.z<1&&a.containsPoint(new o.Vector2(p.x,p.y))&&l.push(u),this._deep)for(const f of u.children)d(f)};for(const u of c)d(u);return l}dispose(){this.disableBoxSelection(),this._selected.clear()}}class Lt{scenes=new Map;_activeSceneKey=null;add(e,t){this.scenes.set(e,t)}create(e,t={}){const s=new o.Scene;return t.background!==void 0&&(s.background=new o.Color(t.background)),this.scenes.set(e,s),s}get(e){return this.scenes.get(e)}remove(e){this.scenes.delete(e),this._activeSceneKey===e&&(this._activeSceneKey=null)}get activeKey(){return this._activeSceneKey}set activeKey(e){this._activeSceneKey=e}keys(){return Array.from(this.scenes.keys())}serialize(e){const t=this.scenes.get(e);if(!t)return null;let s=null;return t.background instanceof o.Color&&(s=`#${t.background.getHexString()}`),{name:t.name||e,background:s,environmentRotation:{x:t.environmentRotation?.x??0,y:t.environmentRotation?.y??0,z:t.environmentRotation?.z??0},children:t.children.map(n=>n.name||n.uuid)}}clear(){this.scenes.clear(),this._activeSceneKey=null}get size(){return this.scenes.size}}class Tt{scene;lights=new Map;helpers=new Map;constructor(e){this.scene=e}addAmbient(e,t={}){const{color:s=16777215,intensity:n=.5}=t,r=new o.AmbientLight(s,n);return r.name=e,this._register(e,r),r}addDirectional(e,t={}){const{color:s=16777215,intensity:n=1,position:r={x:5,y:10,z:5},castShadow:a=!1,shadowMapSize:c=1024}=t,l=new o.DirectionalLight(s,n);return l.position.set(r.x,r.y,r.z),l.castShadow=a,a&&l.shadow.mapSize.setScalar(c),l.name=e,this._register(e,l),l}addPoint(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,decay:a=2,position:c={x:0,y:5,z:0},castShadow:l=!1}=t,h=new o.PointLight(s,n,r,a);return h.position.set(c.x,c.y,c.z),h.castShadow=l,h.name=e,this._register(e,h),h}addSpot(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,angle:a=Math.PI/6,penumbra:c=.1,decay:l=2,position:h={x:0,y:10,z:0},target:d,castShadow:u=!1}=t,p=new o.SpotLight(s,n,r,a,c,l);return p.position.set(h.x,h.y,h.z),d&&p.target.position.set(d.x,d.y,d.z),p.castShadow=u,p.name=e,this._register(e,p),p}addHemisphere(e,t={}){const{skyColor:s=8900331,groundColor:n=3549447,intensity:r=.6}=t,a=new o.HemisphereLight(s,n,r);return a.name=e,this._register(e,a),a}applyPreset(e){switch(this.removeAll(),e){case"indoor":this.addAmbient("preset_ambient",{intensity:.4}),this.addPoint("preset_point1",{position:{x:0,y:3,z:0},intensity:1,castShadow:!0}),this.addPoint("preset_point2",{position:{x:3,y:2,z:-3},intensity:.5});break;case"outdoor":this.addHemisphere("preset_hemi",{skyColor:8900331,groundColor:3549447,intensity:.6}),this.addDirectional("preset_sun",{position:{x:10,y:20,z:10},intensity:1.5,castShadow:!0,shadowMapSize:2048});break;case"studio":this.addAmbient("preset_ambient",{intensity:.3}),this.addDirectional("preset_key",{position:{x:5,y:8,z:5},intensity:1.2,castShadow:!0}),this.addDirectional("preset_fill",{position:{x:-5,y:5,z:-2},intensity:.6}),this.addDirectional("preset_back",{position:{x:0,y:5,z:-8},intensity:.4});break;case"warehouse":this.addAmbient("preset_ambient",{intensity:.2}),this.addPoint("preset_light1",{position:{x:-5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light2",{position:{x:5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light3",{position:{x:-5,y:6,z:5},intensity:2,distance:20}),this.addPoint("preset_light4",{position:{x:5,y:6,z:5},intensity:2,distance:20});break}}get(e){return this.lights.get(e)}remove(e){const t=this.lights.get(e);t&&(this.scene.remove(t),this.lights.delete(e)),this.hideHelper(e)}removeAll(){const e=Array.from(this.lights.keys());for(const t of e)this.remove(t)}showHelper(e){if(this.helpers.has(e))return;const t=this.lights.get(e);if(!t)return;let s=null;t instanceof o.DirectionalLight?s=new o.DirectionalLightHelper(t,1):t instanceof o.PointLight?s=new o.PointLightHelper(t,.5):t instanceof o.SpotLight?s=new o.SpotLightHelper(t):t instanceof o.HemisphereLight&&(s=new o.HemisphereLightHelper(t,1)),s&&(this.scene.add(s),this.helpers.set(e,s))}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),this.helpers.delete(e))}showAllHelpers(){for(const[e]of this.lights)this.showHelper(e)}hideAllHelpers(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t)}_register(e,t){this.lights.has(e)&&this.remove(e),this.lights.set(e,t),this.scene.add(t)}dispose(){this.removeAll(),this.hideAllHelpers()}}class fe extends pe.GLTFLoader{constructor(e){super(e)}parse(e,t,s,n){if(Dt(e.slice(0,8))==="SBMG----"){const a=Nt(e.slice(8));return super.parse(a,t,s,n)}else return super.parse(e,t,s,n)}}function Dt(i){return new TextDecoder().decode(new Uint8Array(i))}function Nt(i){const e=new DataView(i);for(let t=0;t<e.byteLength;t++){const s=e.getUint8(t),n=(s>>4&15)+(s<<4&240);e.setUint8(t,n)}return e.buffer}const Rt=8,Pt=130,ve=66,kt="SBK-----",jt="SBM-----",tt=new TextDecoder,Ut=new TextEncoder;function zt(i){let e=Rt;const t=new Uint8Array(i,0,e);if(tt.decode(t)!==kt)return i;e+=Pt;const n=new Uint8Array(i,0,e);if(n[40]===1){const a=Ut.encode(jt),c=new Uint8Array([n[41]]),l=Ft(n),h=Wt(l);let d=ve%h.length;const u=e+ve,p=new Uint8Array(i,u),f=new Uint8Array(p.length);for(let C=0;C<p.length;C++)f[C]=p[C]^h[d],d=(d+1)%h.length;const S=new Uint8Array(a.length+c.length+f.length);return S.set(a),S.set(c,a.length),S.set(f,a.length+c.length),S.buffer}}function Ft(i){const e=new Uint8Array(128);return e.set(i.slice(42,74),0),e.set(i.slice(74,138),32),e.set(i.slice(8,40),96),e}function Wt(i){const e=new Uint8Array(64);return e.set(i.slice(0,8),0),e.set(i.slice(24,32),8),e.set(i.slice(40,56),16),e.set(i.slice(64,88),32),e.set(i.slice(96,104),56),e}const Gt=(i,e,t)=>{const s=i.buffer.slice(t,t+e);let n=tt.decode(s);return n=n.replace("\\","/"),n.startsWith("Maps/")||(n=`Maps/${n}`),n},Ht=(i,e,t)=>{const[s,n,r,a,c]=e,l=t||a<1;return new o.MeshStandardNodeMaterial({name:i,color:new o.Color(s,n,r),opacity:a,transparent:l,alphaTest:.01,side:c})},$t=i=>i?.toLowerCase().endsWith(".png")??!1;class Vt{data;options;textureLoader;littleEndian=!0;materials=new Map;constructor(e,t){this.data=e,this.options=t,this.textureLoader=new o.TextureLoader(t.manager),this.textureLoader.setCrossOrigin(t.crossOrigin),this.textureLoader.setRequestHeader(t.requestHeader)}parse(e,t){let s=this.data;const n=zt(this.data);n&&(s=n);const r=new DataView(s);let a=8;const c=r.getUint8(a);a+=1,c===1?this._parseV2(r,a,e):c===2?this._parseV2(r,a,e):c===3?this._parseV3(r,a,e):t?.(new Error(`SBMLoader: Unsupported SBM version: ${c}`))}_parseV2(e,t,s){const n=new o.Group,r=e.getUint16(t,this.littleEndian);t+=2;const a=e.getUint16(t,this.littleEndian);t+=2;for(let c=0;c<r;++c){const l=e.getUint16(t,this.littleEndian).toString();t+=2,t+=4,t+=4,t+=4,t+=4;const h=e.getFloat32(t,this.littleEndian);t+=4;const d=e.getFloat32(t,this.littleEndian);t+=4;const u=e.getFloat32(t,this.littleEndian);t+=4;const p=e.getFloat32(t,this.littleEndian);t+=4,t+=4,t+=4,t+=4,t+=4;let f=e.getUint8(t);t+=1,f===0?f=o.FrontSide:f===1?f=o.BackSide:f===2&&(f=o.DoubleSide);const S=e.getUint16(t,this.littleEndian);t+=2;const C=S>0?Gt(e,S,t):"";if(t+=S,!this.materials.has(l)){const O=Ht(l,[h,d,u,p,f],$t(C));this.materials.set(l,O),C&&this.options.path&&this.textureLoader.load(o.LoaderUtils.resolveURL(C,this.options.path),w=>{w.colorSpace=o.SRGBColorSpace,w.wrapS=o.RepeatWrapping,w.wrapT=o.RepeatWrapping,w.flipY=!1,w.anisotropy=16,O.map=w})}}for(let c=0;c<a;++c){const l=e.getUint16(t,this.littleEndian).toString();t+=2;const h=e.getUint16(t,this.littleEndian).toString();t+=2;const d=[],u=[],p=[],f=[],S=e.getUint16(t,this.littleEndian);if(t+=2,S>0)for(let M=0;M<S;M++){const I=new o.Vector3;I.setX(e.getFloat32(t,this.littleEndian)),t+=4,I.setY(e.getFloat32(t,this.littleEndian)),t+=4,I.setZ(e.getFloat32(t,this.littleEndian)),t+=4,d.push(I)}const C=e.getUint16(t,this.littleEndian);if(t+=2,C>0)for(let M=0;M<C;M++)t+=4,t+=4,t+=4;const D=e.getUint16(t,this.littleEndian);if(t+=2,D>0)for(let M=0;M<D;M++){const I=new o.Vector2;I.setX(e.getFloat32(t,this.littleEndian)),t+=4,I.setY(e.getFloat32(t,this.littleEndian)),t+=4,u.push(I)}const O=e.getUint16(t,this.littleEndian);if(t+=2,O>0)for(let M=0;M<O;M++){const I=e.getUint16(t,this.littleEndian);t+=2;const A=e.getUint16(t,this.littleEndian);t+=2;const v=e.getUint16(t,this.littleEndian);t+=2;const B=[I,A,v];p.push(B),u.length>0&&f.push([u[B[0]],u[B[1]],u[B[2]]])}const w=[],x=[];for(let M=0;M<p.length;M++){const I=p[M],A=d[I[0]],v=d[I[1]],B=d[I[2]];w.push(...A.toArray(),...v.toArray(),...B.toArray());let P=new o.Vector2,R=new o.Vector2,m=new o.Vector2;const N=f[M];N!==void 0&&(P=N[0],R=N[1],m=N[2]),x.push(...P.toArray(),...R.toArray(),...m.toArray())}const b=new Float32Array(w),y=new Float32Array(x),E=new o.BufferGeometry;if(b.length>0&&E.setAttribute("position",new o.BufferAttribute(b,3)),y.length>0&&E.setAttribute("uv",new o.BufferAttribute(y,2)),E.computeVertexNormals(),this.materials.has(h)){const M=new o.Mesh(E,this.materials.get(h));M.name=l,M.castShadow=!0,M.receiveShadow=!0,n.add(M)}}s(n)}_parseV3(e,t,s){const n=new o.Group;console.warn("SBMLoader: SBM version 3 is not supported yet."),s(n)}}class me extends o.Loader{load(e,t,s,n){let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=o.LoaderUtils.extractUrlBase(e);r=o.LoaderUtils.resolveURL(l,this.path)}else r=o.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=l=>{n?n(l):console.error(l),this.manager.itemError(e),this.manager.itemEnd(e)},c=new o.FileLoader(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,l=>{try{this.parse(l,r,h=>{t(h),this.manager.itemEnd(e)},a)}catch(h){a(h)}},s,a)}parse(e,t,s,n){const r=new TextDecoder().decode(e.slice(0,8));if(r!=="SBK-----"&&r!=="SBM-----"){n?.(new Error(`SBMLoader: Invalid SBM format: ${r}`));return}new Vt(e,{path:t,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager}).parse(s,n)}parseAsync(e,t){return new Promise((s,n)=>{this.parse(e,t,r=>{s(r)},r=>{n(r)})})}}const Kt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},qt={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Xt={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color"};function Q(i,e){e&&typeof e=="object"&&!Array.isArray(e)&&Object.assign(i.userData,e)}function Yt(i){if(i.protocolVersion!==ee.MODEL_DECODE_PROTOCOL_VERSION)throw new Error(`Unsupported model decode protocol ${i.protocolVersion}; expected ${ee.MODEL_DECODE_PROTOCOL_VERSION}.`);const{document:e,buffers:t,images:s}=i;ee.validateDecodedGltfNodeGraph(e);const n=new Map,r=new Map,a=new Map,c=new Map,l=new Map,h=x=>{const b=n.get(x);if(b)return b;const y=e.accessors?.[x];if(!y||y.bufferView===void 0)throw new Error(`Decoded glTF references missing accessor ${x}.`);const E=e.bufferViews?.[y.bufferView];if(!E)throw new Error(`Decoded glTF references missing bufferView ${y.bufferView}.`);const M=t[E.buffer];if(!M)throw new Error(`Decoded glTF references missing buffer ${E.buffer}.`);const I=Kt[y.componentType],A=qt[y.type];if(!I||!A)throw new Error(`Unsupported decoded glTF accessor type ${y.componentType}/${y.type}.`);const v=I.BYTES_PER_ELEMENT,B=E.byteOffset??0,P=y.byteOffset??0;let R;const m=A*v;if(E.byteStride&&E.byteStride!==m){if(E.byteStride%v!==0||P%v!==0)throw new Error(`Decoded glTF accessor ${x} has an invalid interleaved alignment.`);const N=Math.floor(P/E.byteStride),_=[y.bufferView,y.componentType,N,y.count].join(":");let L=r.get(_);if(!L){const k=new I(M,B+N*E.byteStride,y.count*E.byteStride/v);L=new o.InterleavedBuffer(k,E.byteStride/v),r.set(_,L)}R=new o.InterleavedBufferAttribute(L,A,P%E.byteStride/v,y.normalized??!1)}else{const N=new I(M,B+P,y.count*A);R=new o.BufferAttribute(N,A,y.normalized??!1)}return R.name=y.name??"",n.set(x,R),R},d=(x,b,y)=>{const E=`${x}:${b}:${y}`,M=l.get(E);if(M)return M;const I=e.textures?.[x];if(!I||I.source===void 0)throw new Error(`Decoded glTF references missing texture ${x}.`);const A=s[I.source];if(!A)throw new Error(`Decoded glTF references missing image ${I.source}.`);const v=I.sampler===void 0?void 0:e.samplers?.[I.sampler],B=new o.Texture(A);return B.name=I.name??e.images?.[I.source]?.name??"",B.flipY=!1,B.colorSpace=b,B.channel=y,B.magFilter=v?.magFilter===9728?o.NearestFilter:o.LinearFilter,B.minFilter=(()=>{switch(v?.minFilter){case 9728:return o.NearestFilter;case 9729:return o.LinearFilter;case 9984:return o.NearestMipmapNearestFilter;case 9985:return o.LinearMipmapNearestFilter;case 9986:return o.NearestMipmapLinearFilter;default:return o.LinearMipmapLinearFilter}})(),B.wrapS=(()=>{switch(v?.wrapS){case 33071:return o.ClampToEdgeWrapping;case 33648:return o.MirroredRepeatWrapping;default:return o.RepeatWrapping}})(),B.wrapT=(()=>{switch(v?.wrapT){case 33071:return o.ClampToEdgeWrapping;case 33648:return o.MirroredRepeatWrapping;default:return o.RepeatWrapping}})(),B.needsUpdate=!0,l.set(E,B),B},u=(x,b,y,E)=>{y&&(x[b]=d(y.index,E,y.texCoord??0))},p=(x,b,y,E)=>{const M=[x??"default",b?"derivative-tangents":"",y?"vertex-colors":"",E?"flat-shading":""].join(":"),I=c.get(M);if(I)return I;const A=x===void 0?void 0:e.materials?.[x];if(x!==void 0&&!A)throw new Error(`Decoded glTF references missing material ${x}.`);const v=A??{},B=v.pbrMetallicRoughness??{},P=B.baseColorFactor??[1,1,1,1],R=v.alphaMode??"OPAQUE",m=new o.MeshStandardMaterial({color:new o.Color().setRGB(P[0]??1,P[1]??1,P[2]??1,o.LinearSRGBColorSpace),opacity:P[3]??1,metalness:B.metallicFactor??1,roughness:B.roughnessFactor??1,transparent:R==="BLEND",depthWrite:R!=="BLEND",alphaTest:R==="MASK"?v.alphaCutoff??.5:0});return v.doubleSided&&(m.side=o.DoubleSide),m.vertexColors=y,m.flatShading=E,m.name=v.name??"",u(m,"map",B.baseColorTexture,o.SRGBColorSpace),u(m,"metalnessMap",B.metallicRoughnessTexture,o.NoColorSpace),u(m,"roughnessMap",B.metallicRoughnessTexture,o.NoColorSpace),u(m,"normalMap",v.normalTexture,o.NoColorSpace),u(m,"aoMap",v.occlusionTexture,o.NoColorSpace),u(m,"emissiveMap",v.emissiveTexture,o.SRGBColorSpace),v.normalTexture?.scale!==void 0&&(m.normalScale=new o.Vector2(v.normalTexture.scale,v.normalTexture.scale)),b&&(m.normalScale.y*=-1),v.occlusionTexture?.strength!==void 0&&(m.aoMapIntensity=v.occlusionTexture.strength),v.emissiveFactor&&m.emissive.setRGB(v.emissiveFactor[0]??0,v.emissiveFactor[1]??0,v.emissiveFactor[2]??0,o.LinearSRGBColorSpace),Q(m,v.extras),c.set(M,m),m},f=(x,b)=>{const y=`${x}:${b}`,E=a.get(y);if(E)return E;const M=e.meshes?.[x]?.primitives[b];if(!M)throw new Error(`Decoded glTF references missing primitive ${y}.`);const I=new o.BufferGeometry;for(const[A,v]of Object.entries(M.attributes)){const B=Xt[A]??A.toLowerCase();I.setAttribute(B,h(v))}if(M.indices!==void 0){const A=h(M.indices);if(A instanceof o.InterleavedBufferAttribute)throw new Error(`Decoded glTF index accessor ${M.indices} cannot be interleaved.`);I.setIndex(A)}return a.set(y,I),I},S=x=>{const b=e.meshes?.[x];if(!b)throw new Error(`Decoded glTF references missing mesh ${x}.`);const y=b.primitives.map((M,I)=>{const A=new o.Mesh(f(x,I),p(M.material,M.attributes.TANGENT===void 0,M.attributes.COLOR_0!==void 0,M.attributes.NORMAL===void 0));return A.name=b.name??"",A});if(y.length===1)return Q(y[0],b.extras),y[0];const E=new o.Group;return E.name=b.name??"",E.add(...y),Q(E,b.extras),E},C=x=>{const b=e.nodes?.[x];if(!b)throw new Error(`Decoded glTF references missing node ${x}.`);const y=b.mesh===void 0?new o.Group:S(b.mesh);y.name=b.name??y.name,b.matrix?new o.Matrix4().fromArray(b.matrix).decompose(y.position,y.quaternion,y.scale):(b.translation&&y.position.fromArray(b.translation),b.rotation&&y.quaternion.fromArray(b.rotation),b.scale&&y.scale.fromArray(b.scale)),Q(y,b.extras);for(const E of b.children??[])y.add(C(E));return y},D=e.scene??0,O=e.scenes?.[D];if(!O)throw new Error(`Decoded glTF references missing scene ${D}.`);const w=new o.Group;w.name=O.name??"",Q(w,O.extras);for(const x of O.nodes??[])w.add(C(x));return w.animations=[],w}const Qt=256;function Jt(i){return i instanceof Error?{message:i.message,name:i.name,stack:i.stack}:{message:String(i)}}function Zt(i){const e=new Error(i.message);return e.name=i.name??"Error",e.stack=i.stack,e}class te extends Error{name="ModelDecodeWorkerUnavailableError";constructor(e,t){super(e,t)}}function st(i,e,t=Qt){if(i.images.length!==i.imageKeys.length)throw new Error("Decoded model image identities do not match its image payload.");const s=[];for(let n=0;n<i.images.length;n++){const r=i.imageKeys[n],a=i.images[n],c=e.get(r);if(c)e.delete(r),e.set(r,c),c!==a&&a.close(),i.images[n]=c;else for(e.set(r,a),s.push(r);e.size>Math.max(0,t);){const l=e.keys().next().value;if(l===void 0)break;e.delete(l)}}return s}class nt{worker;#s;#a=1;#t=new Map;#e=new Map;#r=!1;constructor(e,t={}){this.worker=e,this.#s=t.onFatal,e.addEventListener("message",this.#o),e.addEventListener("error",this.#l),e.addEventListener("messageerror",this.#d)}get disposed(){return this.#r}supports(e){const t=e.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase();return t==="sbmx"||t==="gltf"||t==="glb"}async loadAsync(e,t={}){if(this.#r)throw new te("Model decode Worker is unavailable.");const s=this.#a++,{signal:n,loadingManager:r,...a}=t;if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError");const c=await new Promise((h,d)=>{const u={resolve:h,reject:d,manager:r,rootUrl:e,resources:new Map};if(r?.itemStart(e),n){const p=()=>{this.#t.delete(s),this.#h(u,n.reason??new DOMException("Aborted","AbortError")),d(n.reason??new DOMException("Aborted","AbortError"));try{this.#n({type:"cancel",id:s})}catch{}};u.cleanup=()=>n.removeEventListener("abort",p),n.addEventListener("abort",p,{once:!0})}this.#t.set(s,u);try{this.#n({type:"decode",id:s,url:e,options:a})}catch(p){this.#t.delete(s),u.cleanup?.();const f=p instanceof Error?p:new Error(String(p));this.#h(u,f),d(f)}}),l=[];try{return l.push(...st(c,this.#e)),Yt(c)}catch(h){const d=new Set;for(const u of l){const p=c.imageKeys.indexOf(u),f=this.#e.get(u)??c.images[p];this.#e.get(u)===f&&this.#e.delete(u),f&&!d.has(f)&&(f.close(),d.add(f))}throw h}finally{try{this.#n({type:"ack",id:s})}catch{}}}dispose(){if(!this.#r){this.#r=!0;try{this.#n({type:"dispose"})}catch{}this.#i(),this.worker.terminate(),this.#p(new te("Model decode Worker was disposed.")),this.#e.clear()}}#n(e){this.worker.postMessage(e)}#o=e=>{const t=e.data;if(t.type==="disposed")return;if(t.type==="resolve-resource"){this.#c(t.id,t.resourceId,t.url);return}if(t.type==="resource-complete"){const n=this.#t.get(t.id),r=n?.resources.get(t.resourceId);n&&r!==void 0&&(n.resources.delete(t.resourceId),t.ok||n.manager?.itemError(r),n.manager?.itemEnd(r));return}const s=this.#t.get(t.id);if(!s){if(t.type==="decoded"){t.packet.images.forEach(n=>n.close());try{this.#n({type:"ack",id:t.id})}catch{}}return}if(this.#t.delete(t.id),s.cleanup?.(),t.type==="decoded")this.#h(s),s.resolve(t.packet);else if(t.type==="unsupported")this.#h(s,void 0,!1),s.reject(new ee.UnsupportedModelDecodeError(t.reason));else{const n=Zt(t.error);this.#h(s,n),s.reject(n)}};#c(e,t,s){const n=this.#t.get(e);if(!n){try{this.#n({type:"resource-resolved",id:e,resourceId:t,error:{message:"The model decode request is no longer active.",name:"AbortError"}})}catch{}return}let r;try{r=n.manager?.resolveURL(s)??s,n.manager?.itemStart(r),n.manager&&n.resources.set(t,r),this.#n({type:"resource-resolved",id:e,resourceId:t,url:r})}catch(a){r!==void 0&&n.resources.delete(t)&&(n.manager?.itemError(r),n.manager?.itemEnd(r));try{this.#n({type:"resource-resolved",id:e,resourceId:t,error:Jt(a)})}catch(c){this.#u(c instanceof Error?c:new Error(String(c)))}}}#l=e=>{this.#u(e.error instanceof Error?e.error:new Error(e.message))};#d=()=>{this.#u(new Error("Failed to deserialize a model decode Worker response."))};#u(e){if(this.#r)return;this.#r=!0,this.#i(),this.worker.terminate();const t=new te(`Model decode Worker failed: ${e.message}`,{cause:e});this.#p(t),this.#e.clear(),this.#s?.(t)}#i(){this.worker.removeEventListener("message",this.#o),this.worker.removeEventListener("error",this.#l),this.worker.removeEventListener("messageerror",this.#d)}#h(e,t,s=t!==void 0){for(const n of e.resources.values())t&&e.manager?.itemError(n),e.manager?.itemEnd(n);e.resources.clear(),s&&e.manager?.itemError(e.rootUrl),e.manager?.itemEnd(e.rootUrl)}#p(e){for(const t of this.#t.values())t.cleanup?.(),this.#h(t,e),t.reject(e);this.#t.clear()}}const es=["map","alphaMap","aoMap","bumpMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","displacementMap","emissiveMap","envMap","gradientMap","iridescenceMap","iridescenceThicknessMap","lightMap","matcap","metalnessMap","normalMap","roughnessMap","sheenColorMap","sheenRoughnessMap","specularColorMap","specularIntensityMap","specularMap","thicknessMap","transmissionMap"];function J(i){return i.traverse(e=>{if(!(e instanceof o.Mesh))return;const t=Array.isArray(e.material)?e.material:[e.material];for(const s of t){if(!s)continue;let n=!1;for(const r of es){const a=s[r];a?.isTexture&&a.image==null&&(a.dispose(),s[r]=null,n=!0)}n&&(s.needsUpdate=!0)}}),i}class z{static CACHE_NAME="u-space-model-loader-cache";static fileLoader=new o.FileLoader().setResponseType("arraybuffer");static dracoLoader=new vt.DRACOLoader().setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${o.REVISION}.0/examples/jsm/libs/draco/`);static ktx2Loader=new It.KTX2Loader().setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${o.REVISION}.0/examples/jsm/libs/basis/`);static gltfLoader=new pe.GLTFLoader().setDRACOLoader(z.dracoLoader).setKTX2Loader(z.ktx2Loader).setMeshoptDecoder(de.MeshoptDecoder);static sbmxLoader=new fe().setDRACOLoader(z.dracoLoader).setKTX2Loader(z.ktx2Loader).setMeshoptDecoder(de.MeshoptDecoder);static sbmLoader=new me;static fbxLoader=new Ee.FBXLoader;static objLoader=new St.OBJLoader;static stlLoader=new Et.STLLoader;static decodeWorkerClient=null;static setDecodeWorker(e){const t=this.decodeWorkerClient;if(this.decodeWorkerClient=null,t?.dispose(),!e)return()=>{};let s;return s=new nt(e,{onFatal:()=>{this.decodeWorkerClient===s&&(this.decodeWorkerClient=null)}}),this.decodeWorkerClient=s,()=>{this.decodeWorkerClient===s&&(this.decodeWorkerClient=null,s.dispose())}}static get decodeWorkerEnabled(){return this.decodeWorkerClient!==null&&!this.decodeWorkerClient.disposed}static setLoadingManager(e){this.fileLoader.manager=e,this.dracoLoader.manager=e,this.ktx2Loader.manager=e,this.gltfLoader.manager=e,this.sbmxLoader.manager=e,this.sbmLoader.manager=e,this.fbxLoader.manager=e,this.objLoader.manager=e,this.stlLoader.manager=e}static async setRenderer(e){await e.init(),this.ktx2Loader.detectSupport(e)}static setDracoPath(e){this.dracoLoader.setDecoderPath(e)}static setKTX2Path(e){this.ktx2Loader.setTranscoderPath(e)}static async loadAsync(e,t={persistent:!0}){const s=e.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase(),n=t.persistent??!0,r=t.signal;this.throwIfAborted(r);const a=this.decodeWorkerClient;if(a?.supports(e)){const d=this.fileLoader.manager.resolveURL(e),u=typeof location>"u"?e:new URL(e,location.href).href,p=typeof location>"u"?d:new URL(d,location.href).href;try{return await a.loadAsync(p,{persistent:n,headers:this.fileLoader.requestHeader,credentials:this.fileLoader.withCredentials?"include":"same-origin",resourceBaseUrl:u,signal:r,loadingManager:this.fileLoader.manager})}catch(f){if(this.throwIfAborted(r),!(f instanceof ee.UnsupportedModelDecodeError)&&!(f instanceof te))throw f;console.info(`[ModelLoaderManager] Decode Worker fallback for ${e}: ${f.message}`)}}const c=await this.loadSourceBuffer(e,n,r);this.throwIfAborted(r);const l=o.LoaderUtils.extractUrlBase(e),h=this.createParseLoadingManager(r);try{switch(s){case"gltf":case"glb":{const u=await this.configureGltfLoader(new pe.GLTFLoader(h.manager)).parseAsync(c,l);return this.throwIfAborted(r),u.scene.animations=u.animations,J(u.scene)}case"sbmx":{const u=await this.configureGltfLoader(new fe(h.manager)).parseAsync(c,l);return this.throwIfAborted(r),u.scene.animations=u.animations,J(u.scene)}case"sbm":{const u=await new me(h.manager).setCrossOrigin(this.sbmLoader.crossOrigin).setRequestHeader(this.sbmLoader.requestHeader).setWithCredentials(this.sbmLoader.withCredentials).parseAsync(c,l);return this.throwIfAborted(r),J(u)}case"fbx":{const u=new Ee.FBXLoader(h.manager).setCrossOrigin(this.fbxLoader.crossOrigin).setRequestHeader(this.fbxLoader.requestHeader).setWithCredentials(this.fbxLoader.withCredentials).parse(c,l);return this.throwIfAborted(r),J(u)}case"obj":{const d=new TextDecoder().decode(c),u=this.objLoader.parse(d);return this.throwIfAborted(r),J(u)}case"stl":{const d=this.stlLoader.parse(c);return this.throwIfAborted(r),new o.Mesh(d,new o.MeshStandardNodeMaterial)}default:throw new Error(`Unsupported model format: ${s}`)}}finally{h.cleanup()}}static configureGltfLoader(e){return e.setDRACOLoader(this.dracoLoader).setKTX2Loader(this.ktx2Loader).setMeshoptDecoder(de.MeshoptDecoder).setCrossOrigin(this.gltfLoader.crossOrigin).setRequestHeader(this.gltfLoader.requestHeader).setWithCredentials(this.gltfLoader.withCredentials),e}static createParseLoadingManager(e){this.throwIfAborted(e);const t=this.fileLoader.manager,s=new o.LoadingManager;s.setURLModifier(r=>t.resolveURL(r)),s.itemStart=r=>t.itemStart(r),s.itemEnd=r=>t.itemEnd(r),s.itemError=r=>t.itemError(r);const n=()=>s.abort();return e?.addEventListener("abort",n,{once:!0}),{manager:s,cleanup:()=>e?.removeEventListener("abort",n)}}static async loadSourceBuffer(e,t,s){this.throwIfAborted(s);const n=this.fileLoader.manager,r=n.resolveURL(e);n.itemStart(r);try{let a;if(t&&typeof caches<"u")try{a=await caches.open(this.CACHE_NAME);const u=await a.match(r);if(this.throwIfAborted(s),u){const p=await u.arrayBuffer();return this.throwIfAborted(s),p}}catch(u){this.throwIfAborted(s),console.warn(`[ModelLoaderManager] Failed to read Cache Storage for ${r}:`,u)}const c=n.abortController.signal,l=s&&typeof AbortSignal.any=="function"?AbortSignal.any([s,c]):s??c,h=await fetch(r,{headers:this.fileLoader.requestHeader,credentials:this.fileLoader.withCredentials?"include":"same-origin",signal:l});if(!h.ok)throw new Error(`Failed to load model ${r}: ${h.status} ${h.statusText}`);const d=await h.arrayBuffer();if(this.throwIfAborted(s),a)try{await a.put(r,new Response(d.slice(0)))}catch(u){this.throwIfAborted(s),console.warn(`[ModelLoaderManager] Failed to write Cache Storage for ${r}:`,u)}return d}catch(a){throw n.itemError(r),a}finally{n.itemEnd(r)}}static throwIfAborted(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}}class ts{static textureLoader=new o.TextureLoader;static hdrLoader=new Ct.HDRLoader;static cubeTextureLoader=new o.CubeTextureLoader;static setLoadingManager(e){this.textureLoader.manager=e,this.hdrLoader.manager=e,this.cubeTextureLoader.manager=e}static async loadAsyncTexture(e){return await this.textureLoader.loadAsync(e)}static async loadAsyncHDR(e){const t=await this.hdrLoader.loadAsync(e);return t.mapping=o.EquirectangularReflectionMapping,t}static async loadAsyncCubeTexture(e,t){return this.cubeTextureLoader.setPath(e),await this.cubeTextureLoader.loadAsync(t)}}class F extends o.Mesh{isBaseMesh=!0;type="BaseMesh";castShadow=!0;receiveShadow=!0;ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class q extends o.Group{isBaseGroup=!0;type="BaseGroup";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class rt extends o.Sprite{isBaseSprite=!0;type="BaseSprite";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class G extends q{isModel=!0;type="Model";static memoryCache=new Map;mixer=null;animations=[];actions=new Map;constructor(){super()}async loadAsync(e){const{url:t,cache:s=!0,persistent:n=!0,signal:r}=e;try{let a;if(s&&!r)if(G.memoryCache.has(t))a=G.memoryCache.get(t);else{const d=z.loadAsync(t,{persistent:n,signal:r}).catch(u=>{throw G.memoryCache.get(t)===d&&G.memoryCache.delete(t),u});G.memoryCache.set(t,d),a=d}else a=z.loadAsync(t,{persistent:n,signal:r});const c=await a,l=Me.clone(c);return this.add(l),l.animations&&l.animations.length>0&&(this.animations=l.animations,this.mixer=new o.AnimationMixer(l)),l}catch(a){return console.error(`[Model] Failed to load model from ${t}:`,a),null}}playAnimation(e,t={}){if(!this.mixer||this.animations.length===0)return null;const{loop:s=!0,repetitions:n=1/0,timeScale:r=1,clampWhenFinished:a=!1}=t;let c;if(e===void 0?c=this.animations[0]:typeof e=="number"?c=this.animations[e]:c=this.animations.find(h=>h.name===e),!c)return console.warn(`[Model] Animation not found: ${e}`),null;let l=this.actions.get(c.name);return l||(l=this.mixer.clipAction(c),this.actions.set(c.name,l)),l.setLoop(s?o.LoopRepeat:o.LoopOnce,n),l.clampWhenFinished=a,l.timeScale=r,l.reset().play(),l}playAllAnimations(e={}){return this.animations.map((t,s)=>this.playAnimation(s,e)).filter(t=>t!==null)}stopAnimation(e){if(!this.mixer)return;if(e===void 0){this.mixer.stopAllAction();return}let t;typeof e=="number"?t=this.animations[e]?.name:t=e,t&&this.actions.get(t)?.stop()}updateAnimation(e){this.mixer?.update(e)}getBoundingBox(){return new o.Box3().setFromObject(this)}getCenter(){const e=new o.Vector3;return this.getBoundingBox().getCenter(e),e}setMaterial(e){this.traverse(t=>{t instanceof o.Mesh&&(t.material=e)})}static clearMemoryCache(){this.memoryCache.clear()}static async clearPersistentCache(){typeof caches<"u"&&await caches.delete("u-space-model-loader-cache")}}class it extends F{isSphereMesh=!0;type="SphereMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.SphereGeometry(e?.radius,e?.widthSegments,e?.heightSegments,e?.phiStart,e?.phiLength,e?.thetaStart,e?.thetaLength),this.material=new o.MeshStandardNodeMaterial(t)}}class ge extends F{isTubeMesh=!0;type="TubeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.TubeGeometry(e?.path,e?.tubularSegments,e?.radius,e?.radialSegments,e?.closed),this.material=new o.MeshStandardNodeMaterial(t)}}class ss extends q{isTopology=!0;type="Topology";parameters={nodeColor:255,nodeRadius:.5,edgeColor:65280,edgeRadius:.1,pathColor:16711935,pathRadius:.2};nodes=new Map;adjacencyMap=new Map;graphGroup=null;pathMeshes=[];constructor(e){super(),e&&Object.assign(this.parameters,e)}addNode(e,t){this.nodes.has(e)&&console.warn(`[Topology] Node ${e} already exists. Overwriting.`),this.nodes.set(e,t),this.adjacencyMap.has(e)||this.adjacencyMap.set(e,new Map)}removeNode(e){if(!this.nodes.has(e)){console.warn(`[Topology] Node ${e} does not exist.`);return}this.nodes.delete(e),this.adjacencyMap.delete(e)}addEdge(e,t,s,n=!0){const r=this.nodes.get(e),a=this.nodes.get(t);if(!r||!a){console.error(`[Topology] Cannot add edge. One or both nodes not found: ${e}, ${t}`);return}const c=s??r.distanceTo(a);this.getNeighbors(e)?.set(t,c),n&&this.getNeighbors(t)?.set(e,c)}removeEdge(e,t,s=!0){this.getNeighbors(e)?.delete(t),s&&this.getNeighbors(t)?.delete(e)}getShortestPath(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))return console.warn("[Topology] Start or End node not found."),[];const s=new Map,n=new Map,r=new Set;for(const[l]of this.nodes)s.set(l,1/0),n.set(l,null),r.add(l);for(s.set(e,0);r.size>0;){let l=null,h=1/0;for(const u of r){const p=s.get(u);p<h&&(h=p,l=u)}if(l===null||l===t||h===1/0)break;r.delete(l);const d=this.adjacencyMap?.get(l);if(d)for(const[u,p]of d){if(!r.has(u))continue;const f=s.get(l)+p;f<s.get(u)&&(s.set(u,f),n.set(u,l))}}const a=[];let c=t;if(n.get(t)===null&&e!==t)return[];for(;c!==null;){const l=this.nodes.get(c);l&&a.unshift(l),c=n.get(c)||null}return a}renderGraph(){this.clearGraph(),this.graphGroup=new o.Group;const e=new it({geometryParameters:{radius:this.parameters.nodeRadius,widthSegments:16,heightSegments:16},materialParameters:{color:this.parameters.nodeColor}});this.nodes.forEach((s,n)=>{const r=e.clone();r.position.copy(s),Object.assign(r.userData,{id:n,type:"node"}),this.graphGroup.add(r)});const t=new Set;this.adjacencyMap.forEach((s,n)=>{s.forEach((r,a)=>{const c=[n,a].sort().join("-");if(t.has(c))return;t.add(c);const l=this.nodes.get(n),h=this.nodes.get(a);if(l&&h){const d=new o.LineCurve3(l,h),u=new ge({geometryParameters:{path:d,tubularSegments:1,radius:this.parameters.edgeRadius,radialSegments:8,closed:!1},materialParameters:{color:this.parameters.edgeColor}});Object.assign(u.userData,{from:n,to:a,weight:r,type:"edge"}),this.graphGroup.add(u)}})}),this.add(this.graphGroup)}clearGraph(){this.graphGroup&&(this.remove(this.graphGroup),this.graphGroup.traverse(e=>{e instanceof o.Mesh&&(e.geometry.dispose(),e.material.dispose())}),this.graphGroup=null)}renderPath(e,t=this.parameters.pathColor){if(e.length<2)return;const s=new o.CatmullRomCurve3(e,!1,"catmullrom",0),n=new ge({geometryParameters:{path:s,tubularSegments:e.length*10,radius:this.parameters.pathRadius,closed:!1},materialParameters:{color:t}});return this.add(n),this.pathMeshes.push(n),n}clearPaths(){this.pathMeshes.forEach(e=>{this.remove(e),e.geometry.dispose(),e.material.dispose()}),this.pathMeshes=[]}exportData(){const e={};this.nodes.forEach((n,r)=>{e[r]={x:n.x,y:n.y,z:n.z}});const t=[],s=new Set;return this.adjacencyMap.forEach((n,r)=>{n.forEach((a,c)=>{const l=[r,c].sort().join("-");s.has(l)||(s.add(l),t.push({from:r,to:c,weight:a}))})}),{nodes:e,edges:t}}importData(e){this.clearGraph(),this.clearPaths(),this.nodes.clear(),this.adjacencyMap.clear(),Object.entries(e.nodes).forEach(([t,s])=>{this.addNode(t,new o.Vector3(s.x,s.y,s.z))}),e.edges.forEach(({from:t,to:s,weight:n})=>{this.addEdge(t,s,n)}),this.renderGraph()}dispose(){this.clearGraph(),this.clearPaths()}getNeighbors(e){return this.adjacencyMap.get(e)}}class ns extends rt{isPoi=!0;type="Poi";parameters={img:"",text:"",fontSize:32,fontFamily:"Arial",color:"#ffffff",iconSize:64,padding:10,backgroundColor:"rgba(0, 0, 0, 0)",borderRadius:8,textPosition:"right",scaleFactor:.01};_canvas=document.createElement("canvas");_lastParametersJSON="";constructor(e={}){super(new o.SpriteNodeMaterial),Object.assign(this.parameters,e),this.updateAsync()}async updateAsync(e={}){Object.assign(this.parameters,e);const t=JSON.stringify(this.parameters);if(t===this._lastParametersJSON)return;this._lastParametersJSON=t;const s=this._canvas,n=s.getContext("2d");if(!n)return;n.font=`${this.parameters.fontSize}px ${this.parameters.fontFamily}`;let r=null;this.parameters.img&&(r=await this._loadImage(this.parameters.img));const{text:a,fontSize:c,color:l,iconSize:h,padding:d,backgroundColor:u,borderRadius:p,textPosition:f,scaleFactor:S}=this.parameters,C=n.measureText(a),D=a?C.width:0,O=a?c:0;let w=0,x=0,b=0,y=0,E=0,M=0;const I=!!r,A=!!a;if(I&&A)switch(f){case"top":w=Math.max(h,D),x=h+d+O,E=(w-D)/2,M=O/2,b=(w-h)/2,y=O+d;break;case"bottom":w=Math.max(h,D),x=h+d+O,b=(w-h)/2,y=0,E=(w-D)/2,M=h+d+O/2;break;case"left":w=h+d+D,x=Math.max(h,O),E=0,M=x/2,b=D+d,y=(x-h)/2;break;default:w=h+d+D,x=Math.max(h,O),b=0,y=(x-h)/2,E=h+d,M=x/2;break}else I?(w=h,x=h,b=0,y=0):A&&(w=D,x=O,E=0,M=O/2);const v=w+d*2,B=x+d*2;if(s.width=v,s.height=B,n.font=`${c}px ${this.parameters.fontFamily}`,u&&(n.fillStyle=u,this._drawRoundedRect(n,0,0,v,B,p),n.fill()),I&&n.drawImage(r,b+d,y+d,h,h),A){n.fillStyle=l;const m=n.measureText(a),N=m.actualBoundingBoxAscent+m.actualBoundingBoxDescent,_=m.actualBoundingBoxAscent-N/2;n.textBaseline="alphabetic",n.fillText(a,E+d,M+d+_)}const P=this.material.map,R=new o.CanvasTexture(s);R.colorSpace=o.SRGBColorSpace,this.material.map=R,P?.dispose(),this.scale.set(v*S,B*S,1)}_loadImage(e){return new Promise((t,s)=>{if(typeof e=="string"){const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=()=>s(new Error(`Failed to load image: ${e}`)),n.src=e}else t(e)})}_drawRoundedRect(e,t,s,n,r,a){e.beginPath(),e.moveTo(t+a,s),e.lineTo(t+n-a,s),e.quadraticCurveTo(t+n,s,t+n,s+a),e.lineTo(t+n,s+r-a),e.quadraticCurveTo(t+n,s+r,t+n-a,s+r),e.lineTo(t+a,s+r),e.quadraticCurveTo(t,s+r,t,s+r-a),e.lineTo(t,s+a),e.quadraticCurveTo(t,s,t+a,s),e.closePath()}dispose(){this.material.map?.dispose(),this.material.dispose()}}class xe extends F{isShapeMesh=!0;type="ShapeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.ShapeGeometry(e?.shape,e?.curveSegments),this.material=new o.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return new xe({...t,geometryParameters:{...t.geometryParameters,shape:new o.Shape(e.map(s=>new o.Vector2(s.x,-s.z)))}})}}class Se extends F{isExtrudeMesh=!0;type="ExtrudeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.ExtrudeGeometry(e?.shape,e?.options),this.material=new o.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return e&&e.length===0&&(e=void 0),new Se({...t,geometryParameters:{...t.geometryParameters,shape:new o.Shape(e?.map(s=>new o.Vector2(s.x,-s.z)))}})}}class rs extends F{isPlaneMesh=!0;type="PlaneMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new o.PlaneGeometry(e?.width,e?.height,e?.widthSegments,e?.heightSegments),this.material=new o.MeshStandardNodeMaterial(t)}}class is extends F{isCircleMesh=!0;type="CircleMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(new o.CircleGeometry(e?.radius,e?.segments,e?.thetaStart,e?.thetaLength),new o.MeshStandardNodeMaterial(t)),this.geometry.rotateX(-Math.PI/2)}}class W{static traverseMeshes(e,t){e.traverse(s=>{s instanceof o.Mesh&&t(s)})}}const as=3,os=1,cs=0,ls=2,hs=.001,Ie=new o.Vector3,$=new o.Vector3,ds=new o.Quaternion;function Ce(i){return i.isInstanceObject===!0}function Be(i){let e=!1;return i.traverse(t=>{if(e)return;const s=t;e=s.isMesh===!0||s.isSprite===!0}),e}function us(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Oe(i){return i===void 0||!Number.isFinite(i)||i<=0?ls:i}class ps{static flow(e={}){const{baseColor:t=16777215,flowColor:s=65280,speed:n=1,scale:r=3,intensity:a=4}=e,c=g.color(new o.Color(t)),l=g.color(new o.Color(s)),h=g.uv().x.mul(r).sub(g.time.mul(n)),d=g.pow(g.sin(h).add(1).mul(.5),a);return g.mix(c,l,d)}static breathe(e={}){const{baseColor:t=16777215,breathColor:s=65280,speed:n=1,intensity:r=2}=e,a=g.color(new o.Color(t)),c=g.color(new o.Color(s)),l=g.sin(g.time.mul(n)).add(1).mul(.5),h=g.pow(l,r);return g.mix(a,c,h)}static fluid(e={}){const{baseColor:t=16777215,flowColor:s=255,speed:n=1,scale:r=1,intensity:a=1,distortion:c=.5}=e,l=g.color(new o.Color(t)),h=g.color(new o.Color(s)),d=g.uv().mul(r),u=g.time.mul(n),p=g.mx_noise_float(d.add(u),1,0),f=d.add(p.mul(c)),S=g.mx_noise_float(f,1,0).add(1).mul(.5),C=g.pow(S,a);return g.mix(l,h,C)}static outline(e={}){let t=[...e.selectedObjects??[]];const s=[],n=new Map,r=new o.Box3;let a=null,c=null,l=null,h=null,d=null,u=e.instanceBoundsProxy??!0,p=e.instanceBoundsPadding??0,f=e.instanceBoundsMinSize??hs,S=Oe(e.downSampleRatio);const C=g.uniform(e.edgeStrength??as),D=g.uniform(e.edgeThickness??os),O=g.uniform(e.edgeGlow??cs),w=g.uniform(new o.Color(e.visibleEdgeColor??16777215)),x=g.uniform(new o.Color(e.hiddenEdgeColor??5125686)),b=()=>(h??=new o.BoxGeometry(1,1,1),h),y=()=>(d||(d=new o.MeshBasicNodeMaterial({color:16777215}),d.colorWrite=!1,d.depthWrite=!1,d.name="u-space.outline.instanceBoundsProxy"),d),E=m=>{const{source:N,mesh:_}=m,L=N.getInstanceBoundingBox?.(r,!0);if(!L||L.isEmpty()||!us(N)){_.visible=!1;return}L.getCenter(Ie),L.getSize($);const k=Math.max(0,p),Y=Math.max(0,f);$.set(Math.max($.x+k*2,Y),Math.max($.y+k*2,Y),Math.max($.z+k*2,Y)),_.visible=!0,_.layers.mask=N.layers.mask,_.matrix.compose(Ie,ds,$),_.matrixWorldNeedsUpdate=!0},M=m=>{m.unsubscribe?.(),m.mesh.removeFromParent()},I=(m,N)=>{let _=n.get(m);if(!_){const L=new o.Mesh(b(),y());L.name=`u-space.outline.instanceBoundsProxy:${m.uuid}`,L.matrixAutoUpdate=!1,L.castShadow=!1,L.receiveShadow=!1,L.frustumCulled=!1,L.raycast=()=>{},L.userData.instanceObject=m,_={source:m,mesh:L,unsubscribe:m.onInstanceRenderDirty?.(()=>E(_))??null},n.set(m,_)}return _.mesh.parent!==N&&(_.mesh.removeFromParent(),N.add(_.mesh)),E(_),_.mesh.visible?_.mesh:null},A=(m,N)=>{const _=m.getInstanceRenderObject?.();return _&&Be(_)?_:Be(m)?m:u&&m.getInstanceBoundingBox?I(m,N):null},v=m=>{const N=new Set,_=new Set;for(const L of t){const k=Ce(L)?A(L,m):L;k&&(N.add(k),Ce(L)&&n.get(L)?.mesh===k&&_.add(L))}n.forEach((L,k)=>{_.has(k)||(M(L),n.delete(k))}),s.length=0,N.forEach(L=>s.push(L))},B=()=>{a?.dispose(),a=null},P=(m,N)=>{if(a&&c===m&&l===N)return a.downSampleRatio=S,a;B(),c=m,l=N,a=Bt.outline(m,N,{selectedObjects:s,edgeThickness:D,edgeGlow:O,downSampleRatio:S});const _=a.updateBefore.bind(a);return a.updateBefore=L=>(v(m),_(L)),a},R=((m,N)=>{const _=m.scene,L=m.camera;v(_);const k=P(_,L),Y=k.visibleEdge.mul(w).add(k.hiddenEdge.mul(x)).mul(C);return g.add(N,g.vec4(Y,0))});return Object.defineProperties(R,{outlineNode:{get:()=>a},selectedObjects:{get:()=>t}}),R.setSelectedObjects=m=>(t=[...m],c&&v(c),R),R.update=m=>(m.edgeStrength!==void 0&&(C.value=m.edgeStrength),m.edgeThickness!==void 0&&(D.value=m.edgeThickness),m.edgeGlow!==void 0&&(O.value=m.edgeGlow),m.visibleEdgeColor!==void 0&&w.value.set(m.visibleEdgeColor),m.hiddenEdgeColor!==void 0&&x.value.set(m.hiddenEdgeColor),m.instanceBoundsProxy!==void 0&&(u=m.instanceBoundsProxy),m.instanceBoundsPadding!==void 0&&(p=m.instanceBoundsPadding),m.instanceBoundsMinSize!==void 0&&(f=m.instanceBoundsMinSize),m.downSampleRatio!==void 0&&(S=Oe(m.downSampleRatio),a&&(a.downSampleRatio=S)),c&&v(c),R),R.dispose=()=>{B(),n.forEach(M),n.clear(),h?.dispose(),d?.dispose(),h=null,d=null,t=[],s.length=0,c=null,l=null},R}}function fs(i){}const X="uSpaceHighlight",ne=`${X}/enabled`,at=`${X}/opacity`,ot=`${X}/color`,ct=`${X}/overwrite`,lt=`${X}/multiplyOpacity`,oe=`${X}/instancedOriginalOpacity`,he="uSpaceBreathe",ce=`${he}/enabled`,ht=`${he}/color`,dt=`${he}/speed`,ut=`${he}/intensity`,le=new WeakMap,ms=g.Fn(()=>{const i=g.userData(ne,"uint"),e=g.userData(ot,"uint"),t=g.userData(ct,"uint"),s=Le(e),n=g.materialColor.mul(s),r=g.select(t.greaterThan(0),s,n),a=g.select(i.greaterThan(0),r,g.materialColor),c=g.userData(ce,"uint"),l=g.userData(ht,"uint"),h=g.userData(dt,"float"),d=g.userData(ut,"float"),u=Le(l),p=g.sin(g.time.mul(h)).add(1).mul(.5),f=g.pow(p,d),S=g.mix(a,u,f);return g.select(c.greaterThan(0),S,a)})(),gs=g.Fn(()=>{const i=g.userData(ne,"uint"),e=g.userData(at,"float"),t=g.userData(lt,"uint"),s=g.select(t.greaterThan(0),g.materialOpacity.mul(e),e);return g.select(i.greaterThan(0),s,g.materialOpacity)})();function se(i){return Array.isArray(i.material)?i.material:[i.material]}function Ae(i){se(i).forEach(t=>{if(!t)return;let s=le.get(t);s||(s={colorNode:t.colorNode,opacityNode:t.opacityNode,transparent:t.transparent,depthWrite:t.depthWrite,activeMeshes:new Set},le.set(t,s)),s.activeMeshes.add(i),t.transparent=!0,t.colorNode=ms,t.opacityNode=gs,t.needsUpdate=!0})}function _e(i){const e=i.userData[ne],t=i.userData[ce];if(e||t)return;se(i).forEach(n=>{if(!n)return;const r=le.get(n);r&&(r.activeMeshes.delete(i),!(r.activeMeshes.size>0)&&(n.colorNode=r.colorNode,n.opacityNode=r.opacityNode,n.transparent=r.transparent,n.depthWrite=r.depthWrite,n.needsUpdate=!0,le.delete(n)))})}function ys(i,e,t,s){const n=i,r=n.setInstanceHighlight;if(r)return r.call(i,e,t,s),!0;const a=n.setInstanceColor,c=n.setInstanceOpacity,l=n.getInstanceOpacity,h=n.getInstanceColor,d=n.hasInstanceColor;return!a||!c?!1:(i.userData[oe]===void 0&&(i.userData[oe]={hasColor:d?.call(i)??!1,color:h?.call(i,new o.Color).getHex()??16777215,opacity:l?.call(i)??1}),a.call(i,e),c.call(i,t),!0)}function bs(i){const e=i,t=e.clearInstanceHighlight;if(t)return t.call(i),!0;const s=e.resetInstanceColor,n=e.setInstanceColor,r=e.setInstanceOpacity;if(!s||!r)return!1;const a=i.userData[oe];return a&&(a.hasColor&&n?n.call(i,a.color):s.call(i),r.call(i,a.opacity),Reflect.deleteProperty(i.userData,oe)),!0}class H{static highlightColor(e,t={}){const s=Array.isArray(e)?e:[e],{opacity:n=.5,color:r=16711680,overwrite:a=!1,depthWrite:c,multiplyOpacity:l=!1}=t,h=new o.Color(r).getHex();for(const d of s)ys(d,r,n,a)||W.traverseMeshes(d,u=>{u.userData[ne]=1,u.userData[at]=n,u.userData[ot]=h,u.userData[ct]=a?1:0,u.userData[lt]=l?1:0,Ae(u),c!==void 0&&se(u).forEach(f=>{f&&(f.depthWrite=c)})})}static removeHighlightColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)bs(s)||W.traverseMeshes(s,n=>{n.userData[ne]=0,_e(n)})}static breatheColor(e,t={}){const s=Array.isArray(e)?e:[e],n=Object.assign({color:65280,speed:1,intensity:2},t);n.color=new o.Color(n.color).getHex();for(const r of s)W.traverseMeshes(r,a=>{a.userData[ce]=1,a.userData[ht]=n.color,a.userData[dt]=n.speed,a.userData[ut]=n.intensity,Ae(a)})}static removeBreatheColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)W.traverseMeshes(s,n=>{n.userData[ce]=0,_e(n)})}static wireframe(e,t=!0){const s=Array.isArray(e)?e:[e];for(const n of s)W.traverseMeshes(n,r=>{se(r).forEach(a=>{if(!a)return;const c=a;c.wireframe=t,c.needsUpdate=!0})})}static removeWireframe(e){H.wireframe(e,!1)}static fadeIn(e,t={}){const{duration:s=500}=t;return H._fade(e,0,1,s)}static fadeOut(e,t={}){const{duration:s=500}=t;return H._fade(e,1,0,s)}static _fade(e,t,s,n){const r=Array.isArray(e)?e:[e],a=new Map;for(const c of r)W.traverseMeshes(c,l=>{se(l).forEach(h=>{if(!h||a.has(h))return;const d=h.opacity,u=h.transparent,p=s>=1?d:s;a.set(h,{material:h,targetOpacity:p,originalOpacity:d,originalTransparent:u}),h.transparent=!0,h.opacity=t,h.needsUpdate=!0})});return a.size===0?Promise.resolve():new Promise(c=>{const l=performance.now();let h=0;const d=()=>{const u=performance.now()-l,p=Math.min(u/n,1);if(!r[0].parent){cancelAnimationFrame(h),c();return}for(const{material:S,targetOpacity:C}of a.values())S.opacity=t+(C-t)*p,S.needsUpdate=!0;if(p<1)h=requestAnimationFrame(d);else{if(s>=1)for(const{material:S,originalOpacity:C,originalTransparent:D}of a.values())S.opacity=C,S.transparent=D,S.needsUpdate=!0;c()}};h=requestAnimationFrame(d)})}}const Le=i=>{const e=i.shiftRight(16).bitAnd(255).toFloat().div(255),t=i.shiftRight(8).bitAnd(255).toFloat().div(255),s=i.bitAnd(255).toFloat().div(255);return g.vec3(e,t,s)};class pt extends T.Tween{viewer;constructor(e,t){super(t),this.viewer=e}_update=({time:e})=>{const t=this.update(e);this.viewer.invalidate(),t||this.viewer.removeEventListener("afterControlsUpdate",this._update)};easingByMode(e){const t=Ms[e];return super.easing(t)}start(e,t){return this.viewer.addEventListener("afterControlsUpdate",this._update),super.start(e,t)}stop(){return this.viewer.removeEventListener("afterControlsUpdate",this._update),super.stop()}}function ws(i,e,t,s={},n,r){return new Promise((a,c)=>{const{duration:l=1e3,delay:h=0,repeat:d=!1,mode:u="Linear.None",yoyo:p=!1}=s,f=new pt(i,e).to(t,l).easingByMode(u).delay(h).onUpdate(S=>{n?.(S,f)}).onComplete(()=>{a()}).onStop(()=>{c("animation stop")}).onStart(()=>{r?.(f)});typeof d=="number"?f.repeat(d):typeof d=="boolean"&&d&&f.repeat(1/0),p&&f.repeatDelay(20),f.yoyo(p),f.start()})}const Ms={"Linear.None":T.Easing.Linear.None,"Quadratic.In":T.Easing.Quadratic.In,"Quadratic.Out":T.Easing.Quadratic.Out,"Quadratic.InOut":T.Easing.Quadratic.InOut,"Cubic.In":T.Easing.Cubic.In,"Cubic.Out":T.Easing.Cubic.Out,"Cubic.InOut":T.Easing.Cubic.InOut,"Quartic.In":T.Easing.Quartic.In,"Quartic.Out":T.Easing.Quartic.Out,"Quartic.InOut":T.Easing.Quartic.InOut,"Quintic.In":T.Easing.Quintic.In,"Quintic.Out":T.Easing.Quintic.Out,"Quintic.InOut":T.Easing.Quintic.InOut,"Sinusoidal.In":T.Easing.Sinusoidal.In,"Sinusoidal.Out":T.Easing.Sinusoidal.Out,"Sinusoidal.InOut":T.Easing.Sinusoidal.InOut,"Exponential.In":T.Easing.Exponential.In,"Exponential.Out":T.Easing.Exponential.Out,"Exponential.InOut":T.Easing.Exponential.InOut,"Circular.In":T.Easing.Circular.In,"Circular.Out":T.Easing.Circular.Out,"Circular.InOut":T.Easing.Circular.InOut,"Elastic.In":T.Easing.Elastic.In,"Elastic.Out":T.Easing.Elastic.Out,"Elastic.InOut":T.Easing.Elastic.InOut,"Back.In":T.Easing.Back.In,"Back.Out":T.Easing.Back.Out,"Back.InOut":T.Easing.Back.InOut,"Bounce.In":T.Easing.Bounce.In,"Bounce.Out":T.Easing.Bounce.Out,"Bounce.InOut":T.Easing.Bounce.InOut};class xs{scene;planes=new Map;helpers=new Map;group;constructor(e){this.scene=e,this.group=new o.ClippingGroup,this.group.name="__clippingToolGroup",this.scene.add(this.group)}attach(){const e=[...this.scene.children];for(const t of e)t!==this.group&&this.group.add(t)}detach(){const e=[...this.group.children];for(const t of e)this.helpers.has(t.name)||this.scene.add(t)}enable(){this.group.enabled=!0}disable(){this.group.enabled=!1}addPlane(e,t={}){const{normal:s={x:0,y:-1,z:0},constant:n=0,showHelper:r=!1,helperSize:a=5,helperColor:c=16711680}=t,l=new o.Plane(new o.Vector3(s.x,s.y,s.z),n);return this.planes.set(e,l),this._syncPlanes(),r&&this.showHelper(e,a,c),l}addBox(e,t,s={}){const{showHelpers:n=!1,helperColor:r=16711680}=s,a=t.min,c=t.max,l=[{suffix:"+x",normal:{x:-1,y:0,z:0},constant:c.x},{suffix:"-x",normal:{x:1,y:0,z:0},constant:-a.x},{suffix:"+y",normal:{x:0,y:-1,z:0},constant:c.y},{suffix:"-y",normal:{x:0,y:1,z:0},constant:-a.y},{suffix:"+z",normal:{x:0,y:0,z:-1},constant:c.z},{suffix:"-z",normal:{x:0,y:0,z:1},constant:-a.z}],h=[];for(const d of l){const u=`${e}_${d.suffix}`;this.addPlane(u,{normal:d.normal,constant:d.constant,showHelper:n,helperColor:r}),h.push(u)}return h}addBoxFromObject(e,t,s=0,n={}){const r=new o.Box3().setFromObject(t);return r.expandByScalar(s),this.addBox(e,r,n)}setPlaneConstant(e,t){const s=this.planes.get(e);s&&(s.constant=t)}removePlane(e){this.planes.delete(e),this.hideHelper(e),this._syncPlanes()}removeBox(e){const t=["+x","-x","+y","-y","+z","-z"];for(const s of t)this.removePlane(`${e}_${s}`)}removeAll(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t);this.planes.clear(),this._syncPlanes()}showHelper(e,t=5,s=16711680){this.hideHelper(e);const n=this.planes.get(e);if(!n)return;const r=new o.PlaneHelper(n,t,new o.Color(s).getHex());r.name=e,this.helpers.set(e,r),this.scene.add(r)}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),t.dispose(),this.helpers.delete(e))}get(e){return this.planes.get(e)}_syncPlanes(){this.group.clippingPlanes=Array.from(this.planes.values())}dispose(){this.detach(),this.removeAll(),this.scene.remove(this.group)}}class Ss{scene;measurements=new Map;_idCounter=0;constructor(e){this.scene=e}measureDistance(e,t,s={}){const{lineColor:n=16776960}=s,r=new o.Vector3(e.x,e.y,e.z),a=new o.Vector3(t.x,t.y,t.z),c=r.distanceTo(a),l=`measure_dist_${this._idCounter++}`,h=new o.Group;h.name=l;const d=new o.BufferGeometry().setFromPoints([r,a]),u=new o.LineBasicMaterial({color:n}),p=new o.Line(d,u);h.add(p),this.scene.add(h);const f={id:l,type:"distance",value:c,unit:"m",points:[r,a],object:h};return this.measurements.set(l,f),f}measureArea(e,t={}){const{lineColor:s=65280}=t;if(e.length<3)throw new Error("MeasureTool.measureArea requires at least 3 points");const n=e.map(f=>new o.Vector3(f.x,f.y,f.z)),r=this._calculatePolygonArea(n),a=`measure_area_${this._idCounter++}`,c=new o.Group;c.name=a;const l=[...n,n[0]],h=new o.BufferGeometry().setFromPoints(l),d=new o.LineBasicMaterial({color:s}),u=new o.Line(h,d);c.add(u),this.scene.add(c);const p={id:a,type:"area",value:r,unit:"m²",points:n,object:c};return this.measurements.set(a,p),p}measureAngle(e,t,s,n={}){const{lineColor:r=16746496}=n,a=new o.Vector3(e.x,e.y,e.z),c=new o.Vector3(t.x,t.y,t.z),l=new o.Vector3(s.x,s.y,s.z),h=a.clone().sub(c).normalize(),d=l.clone().sub(c).normalize(),p=Math.acos(Math.max(-1,Math.min(1,h.dot(d))))*180/Math.PI,f=`measure_angle_${this._idCounter++}`,S=new o.Group;S.name=f;const C=new o.BufferGeometry().setFromPoints([a,c,l]),D=new o.LineBasicMaterial({color:r}),O=new o.Line(C,D);S.add(O),this.scene.add(S);const w={id:f,type:"angle",value:p,unit:"°",points:[a,c,l],object:S};return this.measurements.set(f,w),w}get(e){return this.measurements.get(e)}remove(e){const t=this.measurements.get(e);t&&(this.scene.remove(t.object),t.object.traverse(s=>{s.geometry?.dispose(),s.material?.dispose()}),this.measurements.delete(e))}removeAll(){const e=Array.from(this.measurements.keys());for(const t of e)this.remove(t)}getAll(){return Array.from(this.measurements.values())}_calculatePolygonArea(e){const t=e.length,s=new o.Vector3;for(let r=0;r<t;r++){const a=e[r],c=e[(r+1)%t],l=new o.Vector3().crossVectors(a,c);s.add(l)}const n=new o.Vector3;if(t>=3){const r=e[1].clone().sub(e[0]),a=e[2].clone().sub(e[0]);n.crossVectors(r,a).normalize()}return Math.abs(s.dot(n))/2}dispose(){this.removeAll()}}class Es{scene;annotations=new Map;_idCounter=0;_createCSSObject=null;constructor(e){this.scene=e}setCSSObjectFactory(e){this._createCSSObject=e}add(e,t){this.annotations.has(e)&&this.remove(e);const s=new o.Group;s.name=`annotation_${e}`;const n=new o.Vector3(t.position.x,t.position.y,t.position.z);s.position.copy(n);const r=document.createElement("div");if(r.innerHTML=t.content,r.style.cssText=`
8
+ `,e.className&&(this._selectionBox.className=e.className),this._container.style.position=this._container.style.position||"relative",this._container.appendChild(this._selectionBox),this.domElement.addEventListener("pointerdown",this._onBoxPointerDown),this.domElement.addEventListener("pointermove",this._onBoxPointerMove),this.domElement.addEventListener("pointerup",this._onBoxPointerUp))}disableBoxSelection(){this._boxSelectionEnabled&&(this._boxSelectionEnabled=!1,this.domElement.removeEventListener("pointerdown",this._onBoxPointerDown),this.domElement.removeEventListener("pointermove",this._onBoxPointerMove),this.domElement.removeEventListener("pointerup",this._onBoxPointerUp),this._selectionBox&&(this._selectionBox.remove(),this._selectionBox=null))}setCamera(e){this.camera=e}_onBoxPointerDown=e=>{if(e.button!==0)return;this._isSelecting=!0;const t=this._container.getBoundingClientRect();this._startPoint.set(e.clientX-t.left,e.clientY-t.top),this._endPoint.copy(this._startPoint),this._selectionBox&&(this._selectionBox.style.display="block",this._updateBoxElement())};_onBoxPointerMove=e=>{if(!this._isSelecting)return;const t=this._container.getBoundingClientRect();this._endPoint.set(e.clientX-t.left,e.clientY-t.top),this._updateBoxElement()};_onBoxPointerUp=()=>{if(!this._isSelecting)return;this._isSelecting=!1,this._selectionBox&&(this._selectionBox.style.display="none");const e=this._getObjectsInBox();this.clear(),e.length>0&&this.select(e)};_updateBoxElement(){if(!this._selectionBox)return;const e=Math.min(this._startPoint.x,this._endPoint.x),t=Math.min(this._startPoint.y,this._endPoint.y),s=Math.abs(this._endPoint.x-this._startPoint.x),n=Math.abs(this._endPoint.y-this._startPoint.y);this._selectionBox.style.left=`${e}px`,this._selectionBox.style.top=`${t}px`,this._selectionBox.style.width=`${s}px`,this._selectionBox.style.height=`${n}px`}_getObjectsInBox(){const e=this._container.getBoundingClientRect(),t=e.width,s=e.height,n=new c.Vector2(this._startPoint.x/t*2-1,-(this._startPoint.y/s)*2+1),r=new c.Vector2(this._endPoint.x/t*2-1,-(this._endPoint.y/s)*2+1),a=new c.Box2(new c.Vector2(Math.min(n.x,r.x),Math.min(n.y,r.y)),new c.Vector2(Math.max(n.x,r.x),Math.max(n.y,r.y))),o=this.targetObjects||this.scene.children,l=[],h=new c.Matrix4;h.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);const d=p=>{if(!p.visible)return;const u=new c.Vector3;if(u.setFromMatrixPosition(p.matrixWorld),u.applyMatrix4(h),u.z>-1&&u.z<1&&a.containsPoint(new c.Vector2(u.x,u.y))&&l.push(p),this._deep)for(const f of p.children)d(f)};for(const p of o)d(p);return l}dispose(){this.disableBoxSelection(),this._selected.clear()}}class Rt{scenes=new Map;_activeSceneKey=null;add(e,t){this.scenes.set(e,t)}create(e,t={}){const s=new c.Scene;return t.background!==void 0&&(s.background=new c.Color(t.background)),this.scenes.set(e,s),s}get(e){return this.scenes.get(e)}remove(e){this.scenes.delete(e),this._activeSceneKey===e&&(this._activeSceneKey=null)}get activeKey(){return this._activeSceneKey}set activeKey(e){this._activeSceneKey=e}keys(){return Array.from(this.scenes.keys())}serialize(e){const t=this.scenes.get(e);if(!t)return null;let s=null;return t.background instanceof c.Color&&(s=`#${t.background.getHexString()}`),{name:t.name||e,background:s,environmentRotation:{x:t.environmentRotation?.x??0,y:t.environmentRotation?.y??0,z:t.environmentRotation?.z??0},children:t.children.map(n=>n.name||n.uuid)}}clear(){this.scenes.clear(),this._activeSceneKey=null}get size(){return this.scenes.size}}class Dt{scene;lights=new Map;helpers=new Map;constructor(e){this.scene=e}addAmbient(e,t={}){const{color:s=16777215,intensity:n=.5}=t,r=new c.AmbientLight(s,n);return r.name=e,this._register(e,r),r}addDirectional(e,t={}){const{color:s=16777215,intensity:n=1,position:r={x:5,y:10,z:5},castShadow:a=!1,shadowMapSize:o=1024}=t,l=new c.DirectionalLight(s,n);return l.position.set(r.x,r.y,r.z),l.castShadow=a,a&&l.shadow.mapSize.setScalar(o),l.name=e,this._register(e,l),l}addPoint(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,decay:a=2,position:o={x:0,y:5,z:0},castShadow:l=!1}=t,h=new c.PointLight(s,n,r,a);return h.position.set(o.x,o.y,o.z),h.castShadow=l,h.name=e,this._register(e,h),h}addSpot(e,t={}){const{color:s=16777215,intensity:n=1,distance:r=0,angle:a=Math.PI/6,penumbra:o=.1,decay:l=2,position:h={x:0,y:10,z:0},target:d,castShadow:p=!1}=t,u=new c.SpotLight(s,n,r,a,o,l);return u.position.set(h.x,h.y,h.z),d&&u.target.position.set(d.x,d.y,d.z),u.castShadow=p,u.name=e,this._register(e,u),u}addHemisphere(e,t={}){const{skyColor:s=8900331,groundColor:n=3549447,intensity:r=.6}=t,a=new c.HemisphereLight(s,n,r);return a.name=e,this._register(e,a),a}applyPreset(e){switch(this.removeAll(),e){case"indoor":this.addAmbient("preset_ambient",{intensity:.4}),this.addPoint("preset_point1",{position:{x:0,y:3,z:0},intensity:1,castShadow:!0}),this.addPoint("preset_point2",{position:{x:3,y:2,z:-3},intensity:.5});break;case"outdoor":this.addHemisphere("preset_hemi",{skyColor:8900331,groundColor:3549447,intensity:.6}),this.addDirectional("preset_sun",{position:{x:10,y:20,z:10},intensity:1.5,castShadow:!0,shadowMapSize:2048});break;case"studio":this.addAmbient("preset_ambient",{intensity:.3}),this.addDirectional("preset_key",{position:{x:5,y:8,z:5},intensity:1.2,castShadow:!0}),this.addDirectional("preset_fill",{position:{x:-5,y:5,z:-2},intensity:.6}),this.addDirectional("preset_back",{position:{x:0,y:5,z:-8},intensity:.4});break;case"warehouse":this.addAmbient("preset_ambient",{intensity:.2}),this.addPoint("preset_light1",{position:{x:-5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light2",{position:{x:5,y:6,z:-5},intensity:2,distance:20}),this.addPoint("preset_light3",{position:{x:-5,y:6,z:5},intensity:2,distance:20}),this.addPoint("preset_light4",{position:{x:5,y:6,z:5},intensity:2,distance:20});break}}get(e){return this.lights.get(e)}remove(e){const t=this.lights.get(e);t&&(this.scene.remove(t),this.lights.delete(e)),this.hideHelper(e)}removeAll(){const e=Array.from(this.lights.keys());for(const t of e)this.remove(t)}showHelper(e){if(this.helpers.has(e))return;const t=this.lights.get(e);if(!t)return;let s=null;t instanceof c.DirectionalLight?s=new c.DirectionalLightHelper(t,1):t instanceof c.PointLight?s=new c.PointLightHelper(t,.5):t instanceof c.SpotLight?s=new c.SpotLightHelper(t):t instanceof c.HemisphereLight&&(s=new c.HemisphereLightHelper(t,1)),s&&(this.scene.add(s),this.helpers.set(e,s))}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),this.helpers.delete(e))}showAllHelpers(){for(const[e]of this.lights)this.showHelper(e)}hideAllHelpers(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t)}_register(e,t){this.lights.has(e)&&this.remove(e),this.lights.set(e,t),this.scene.add(t)}dispose(){this.removeAll(),this.hideAllHelpers()}}class me extends fe.GLTFLoader{constructor(e){super(e)}parse(e,t,s,n){if(Nt(e.slice(0,8))==="SBMG----"){const a=Pt(e.slice(8));return super.parse(a,t,s,n)}else return super.parse(e,t,s,n)}}function Nt(i){return new TextDecoder().decode(new Uint8Array(i))}function Pt(i){const e=new DataView(i);for(let t=0;t<e.byteLength;t++){const s=e.getUint8(t),n=(s>>4&15)+(s<<4&240);e.setUint8(t,n)}return e.buffer}const Ut=8,kt=130,Ce=66,jt="SBK-----",zt="SBM-----",st=new TextDecoder,Ft=new TextEncoder;function Wt(i){let e=Ut;const t=new Uint8Array(i,0,e);if(st.decode(t)!==jt)return i;e+=kt;const n=new Uint8Array(i,0,e);if(n[40]===1){const a=Ft.encode(zt),o=new Uint8Array([n[41]]),l=Gt(n),h=Ht(l);let d=Ce%h.length;const p=e+Ce,u=new Uint8Array(i,p),f=new Uint8Array(u.length);for(let C=0;C<u.length;C++)f[C]=u[C]^h[d],d=(d+1)%h.length;const M=new Uint8Array(a.length+o.length+f.length);return M.set(a),M.set(o,a.length),M.set(f,a.length+o.length),M.buffer}}function Gt(i){const e=new Uint8Array(128);return e.set(i.slice(42,74),0),e.set(i.slice(74,138),32),e.set(i.slice(8,40),96),e}function Ht(i){const e=new Uint8Array(64);return e.set(i.slice(0,8),0),e.set(i.slice(24,32),8),e.set(i.slice(40,56),16),e.set(i.slice(64,88),32),e.set(i.slice(96,104),56),e}const $t=(i,e,t)=>{const s=i.buffer.slice(t,t+e);let n=st.decode(s);return n=n.replace("\\","/"),n.startsWith("Maps/")||(n=`Maps/${n}`),n},Vt=(i,e,t)=>{const[s,n,r,a,o]=e,l=t||a<1;return new c.MeshStandardNodeMaterial({name:i,color:new c.Color(s,n,r),opacity:a,transparent:l,alphaTest:.01,side:o})},Kt=i=>i?.toLowerCase().endsWith(".png")??!1;class qt{data;options;textureLoader;littleEndian=!0;materials=new Map;constructor(e,t){this.data=e,this.options=t,this.textureLoader=new c.TextureLoader(t.manager),this.textureLoader.setCrossOrigin(t.crossOrigin),this.textureLoader.setRequestHeader(t.requestHeader)}parse(e,t){let s=this.data;const n=Wt(this.data);n&&(s=n);const r=new DataView(s);let a=8;const o=r.getUint8(a);a+=1,o===1?this._parseV2(r,a,e):o===2?this._parseV2(r,a,e):o===3?this._parseV3(r,a,e):t?.(new Error(`SBMLoader: Unsupported SBM version: ${o}`))}_parseV2(e,t,s){const n=new c.Group,r=e.getUint16(t,this.littleEndian);t+=2;const a=e.getUint16(t,this.littleEndian);t+=2;for(let o=0;o<r;++o){const l=e.getUint16(t,this.littleEndian).toString();t+=2,t+=4,t+=4,t+=4,t+=4;const h=e.getFloat32(t,this.littleEndian);t+=4;const d=e.getFloat32(t,this.littleEndian);t+=4;const p=e.getFloat32(t,this.littleEndian);t+=4;const u=e.getFloat32(t,this.littleEndian);t+=4,t+=4,t+=4,t+=4,t+=4;let f=e.getUint8(t);t+=1,f===0?f=c.FrontSide:f===1?f=c.BackSide:f===2&&(f=c.DoubleSide);const M=e.getUint16(t,this.littleEndian);t+=2;const C=M>0?$t(e,M,t):"";if(t+=M,!this.materials.has(l)){const O=Vt(l,[h,d,p,u,f],Kt(C));this.materials.set(l,O),C&&this.options.path&&this.textureLoader.load(c.LoaderUtils.resolveURL(C,this.options.path),S=>{S.colorSpace=c.SRGBColorSpace,S.wrapS=c.RepeatWrapping,S.wrapT=c.RepeatWrapping,S.flipY=!1,S.anisotropy=16,O.map=S})}}for(let o=0;o<a;++o){const l=e.getUint16(t,this.littleEndian).toString();t+=2;const h=e.getUint16(t,this.littleEndian).toString();t+=2;const d=[],p=[],u=[],f=[],M=e.getUint16(t,this.littleEndian);if(t+=2,M>0)for(let w=0;w<M;w++){const v=new c.Vector3;v.setX(e.getFloat32(t,this.littleEndian)),t+=4,v.setY(e.getFloat32(t,this.littleEndian)),t+=4,v.setZ(e.getFloat32(t,this.littleEndian)),t+=4,d.push(v)}const C=e.getUint16(t,this.littleEndian);if(t+=2,C>0)for(let w=0;w<C;w++)t+=4,t+=4,t+=4;const A=e.getUint16(t,this.littleEndian);if(t+=2,A>0)for(let w=0;w<A;w++){const v=new c.Vector2;v.setX(e.getFloat32(t,this.littleEndian)),t+=4,v.setY(e.getFloat32(t,this.littleEndian)),t+=4,p.push(v)}const O=e.getUint16(t,this.littleEndian);if(t+=2,O>0)for(let w=0;w<O;w++){const v=e.getUint16(t,this.littleEndian);t+=2;const B=e.getUint16(t,this.littleEndian);t+=2;const I=e.getUint16(t,this.littleEndian);t+=2;const L=[v,B,I];u.push(L),p.length>0&&f.push([p[L[0]],p[L[1]],p[L[2]]])}const S=[],y=[];for(let w=0;w<u.length;w++){const v=u[w],B=d[v[0]],I=d[v[1]],L=d[v[2]];S.push(...B.toArray(),...I.toArray(),...L.toArray());let P=new c.Vector2,N=new c.Vector2,g=new c.Vector2;const D=f[w];D!==void 0&&(P=D[0],N=D[1],g=D[2]),y.push(...P.toArray(),...N.toArray(),...g.toArray())}const x=new Float32Array(S),m=new Float32Array(y),E=new c.BufferGeometry;if(x.length>0&&E.setAttribute("position",new c.BufferAttribute(x,3)),m.length>0&&E.setAttribute("uv",new c.BufferAttribute(m,2)),E.computeVertexNormals(),this.materials.has(h)){const w=new c.Mesh(E,this.materials.get(h));w.name=l,w.castShadow=!0,w.receiveShadow=!0,n.add(w)}}s(n)}_parseV3(e,t,s){const n=new c.Group;console.warn("SBMLoader: SBM version 3 is not supported yet."),s(n)}}class ge extends c.Loader{load(e,t,s,n){let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=c.LoaderUtils.extractUrlBase(e);r=c.LoaderUtils.resolveURL(l,this.path)}else r=c.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=l=>{n?n(l):console.error(l),this.manager.itemError(e),this.manager.itemEnd(e)},o=new c.FileLoader(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,l=>{try{this.parse(l,r,h=>{t(h),this.manager.itemEnd(e)},a)}catch(h){a(h)}},s,a)}parse(e,t,s,n){const r=new TextDecoder().decode(e.slice(0,8));if(r!=="SBK-----"&&r!=="SBM-----"){n?.(new Error(`SBMLoader: Invalid SBM format: ${r}`));return}new qt(e,{path:t,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager}).parse(s,n)}parseAsync(e,t){return new Promise((s,n)=>{this.parse(e,t,r=>{s(r)},r=>{n(r)})})}}const Xt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Yt={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Qt={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color"};function Z(i,e){e&&typeof e=="object"&&!Array.isArray(e)&&Object.assign(i.userData,e)}function Jt(i){if(i.protocolVersion!==j.MODEL_DECODE_PROTOCOL_VERSION)throw new Error(`Unsupported model decode protocol ${i.protocolVersion}; expected ${j.MODEL_DECODE_PROTOCOL_VERSION}.`);const{document:e,buffers:t,images:s}=i;j.validateDecodedGltfNodeGraph(e);const n=new Map,r=new Map,a=new Map,o=new Map,l=new Map,h=y=>{const x=n.get(y);if(x)return x;const m=e.accessors?.[y];if(!m||m.bufferView===void 0)throw new Error(`Decoded glTF references missing accessor ${y}.`);const E=e.bufferViews?.[m.bufferView];if(!E)throw new Error(`Decoded glTF references missing bufferView ${m.bufferView}.`);const w=t[E.buffer];if(!w)throw new Error(`Decoded glTF references missing buffer ${E.buffer}.`);const v=Xt[m.componentType],B=Yt[m.type];if(!v||!B)throw new Error(`Unsupported decoded glTF accessor type ${m.componentType}/${m.type}.`);const I=v.BYTES_PER_ELEMENT,L=E.byteOffset??0,P=m.byteOffset??0;let N;const g=B*I;if(E.byteStride&&E.byteStride!==g){if(E.byteStride%I!==0||P%I!==0)throw new Error(`Decoded glTF accessor ${y} has an invalid interleaved alignment.`);const D=Math.floor(P/E.byteStride),_=[m.bufferView,m.componentType,D,m.count].join(":");let T=r.get(_);if(!T){const U=new v(w,L+D*E.byteStride,m.count*E.byteStride/I);T=new c.InterleavedBuffer(U,E.byteStride/I),r.set(_,T)}N=new c.InterleavedBufferAttribute(T,B,P%E.byteStride/I,m.normalized??!1)}else{const D=new v(w,L+P,m.count*B);N=new c.BufferAttribute(D,B,m.normalized??!1)}return N.name=m.name??"",n.set(y,N),N},d=(y,x,m)=>{const E=`${y}:${x}:${m}`,w=l.get(E);if(w)return w;const v=e.textures?.[y];if(!v||v.source===void 0)throw new Error(`Decoded glTF references missing texture ${y}.`);const B=s[v.source];if(!B)throw new Error(`Decoded glTF references missing image ${v.source}.`);const I=v.sampler===void 0?void 0:e.samplers?.[v.sampler],L=new c.Texture(B);return L.name=v.name??e.images?.[v.source]?.name??"",L.flipY=!1,L.colorSpace=x,L.channel=m,L.magFilter=I?.magFilter===9728?c.NearestFilter:c.LinearFilter,L.minFilter=(()=>{switch(I?.minFilter){case 9728:return c.NearestFilter;case 9729:return c.LinearFilter;case 9984:return c.NearestMipmapNearestFilter;case 9985:return c.LinearMipmapNearestFilter;case 9986:return c.NearestMipmapLinearFilter;default:return c.LinearMipmapLinearFilter}})(),L.wrapS=(()=>{switch(I?.wrapS){case 33071:return c.ClampToEdgeWrapping;case 33648:return c.MirroredRepeatWrapping;default:return c.RepeatWrapping}})(),L.wrapT=(()=>{switch(I?.wrapT){case 33071:return c.ClampToEdgeWrapping;case 33648:return c.MirroredRepeatWrapping;default:return c.RepeatWrapping}})(),L.needsUpdate=!0,l.set(E,L),L},p=(y,x,m,E)=>{m&&(y[x]=d(m.index,E,m.texCoord??0))},u=(y,x,m,E)=>{const w=[y??"default",x?"derivative-tangents":"",m?"vertex-colors":"",E?"flat-shading":""].join(":"),v=o.get(w);if(v)return v;const B=y===void 0?void 0:e.materials?.[y];if(y!==void 0&&!B)throw new Error(`Decoded glTF references missing material ${y}.`);const I=B??{},L=I.pbrMetallicRoughness??{},P=L.baseColorFactor??[1,1,1,1],N=I.alphaMode??"OPAQUE",g=new c.MeshStandardMaterial({color:new c.Color().setRGB(P[0]??1,P[1]??1,P[2]??1,c.LinearSRGBColorSpace),opacity:P[3]??1,metalness:L.metallicFactor??1,roughness:L.roughnessFactor??1,transparent:N==="BLEND",depthWrite:N!=="BLEND",alphaTest:N==="MASK"?I.alphaCutoff??.5:0});return I.doubleSided&&(g.side=c.DoubleSide),g.vertexColors=m,g.flatShading=E,g.name=I.name??"",p(g,"map",L.baseColorTexture,c.SRGBColorSpace),p(g,"metalnessMap",L.metallicRoughnessTexture,c.NoColorSpace),p(g,"roughnessMap",L.metallicRoughnessTexture,c.NoColorSpace),p(g,"normalMap",I.normalTexture,c.NoColorSpace),p(g,"aoMap",I.occlusionTexture,c.NoColorSpace),p(g,"emissiveMap",I.emissiveTexture,c.SRGBColorSpace),I.normalTexture?.scale!==void 0&&(g.normalScale=new c.Vector2(I.normalTexture.scale,I.normalTexture.scale)),x&&(g.normalScale.y*=-1),I.occlusionTexture?.strength!==void 0&&(g.aoMapIntensity=I.occlusionTexture.strength),I.emissiveFactor&&g.emissive.setRGB(I.emissiveFactor[0]??0,I.emissiveFactor[1]??0,I.emissiveFactor[2]??0,c.LinearSRGBColorSpace),Z(g,I.extras),o.set(w,g),g},f=(y,x)=>{const m=`${y}:${x}`,E=a.get(m);if(E)return E;const w=e.meshes?.[y]?.primitives[x];if(!w)throw new Error(`Decoded glTF references missing primitive ${m}.`);const v=new c.BufferGeometry;for(const[B,I]of Object.entries(w.attributes)){const L=Qt[B]??B.toLowerCase();v.setAttribute(L,h(I))}if(w.indices!==void 0){const B=h(w.indices);if(B instanceof c.InterleavedBufferAttribute)throw new Error(`Decoded glTF index accessor ${w.indices} cannot be interleaved.`);v.setIndex(B)}return a.set(m,v),v},M=y=>{const x=e.meshes?.[y];if(!x)throw new Error(`Decoded glTF references missing mesh ${y}.`);const m=x.primitives.map((w,v)=>{const B=new c.Mesh(f(y,v),u(w.material,w.attributes.TANGENT===void 0,w.attributes.COLOR_0!==void 0,w.attributes.NORMAL===void 0));return B.name=x.name??"",B});if(m.length===1)return Z(m[0],x.extras),m[0];const E=new c.Group;return E.name=x.name??"",E.add(...m),Z(E,x.extras),E},C=y=>{const x=e.nodes?.[y];if(!x)throw new Error(`Decoded glTF references missing node ${y}.`);const m=x.mesh===void 0?new c.Group:M(x.mesh);m.name=x.name??m.name,x.matrix?new c.Matrix4().fromArray(x.matrix).decompose(m.position,m.quaternion,m.scale):(x.translation&&m.position.fromArray(x.translation),x.rotation&&m.quaternion.fromArray(x.rotation),x.scale&&m.scale.fromArray(x.scale)),Z(m,x.extras);for(const E of x.children??[])m.add(C(E));return m},A=e.scene??0,O=e.scenes?.[A];if(!O)throw new Error(`Decoded glTF references missing scene ${A}.`);const S=new c.Group;S.name=O.name??"",Z(S,O.extras);for(const y of O.nodes??[])S.add(C(y));return S.animations=[],S}const Zt=256;function es(i){return i instanceof Error?{message:i.message,name:i.name,stack:i.stack}:{message:String(i)}}function ts(i){const e=new Error(i.message);return e.name=i.name??"Error",e.stack=i.stack,e}class se extends Error{name="ModelDecodeWorkerUnavailableError";constructor(e,t){super(e,t)}}function nt(i,e,t=Zt){if(i.images.length!==i.imageKeys.length)throw new Error("Decoded model image identities do not match its image payload.");const s=[];for(let n=0;n<i.images.length;n++){const r=i.imageKeys[n],a=i.images[n],o=e.get(r);if(o)e.delete(r),e.set(r,o),o!==a&&a.close(),i.images[n]=o;else for(e.set(r,a),s.push(r);e.size>Math.max(0,t);){const l=e.keys().next().value;if(l===void 0)break;e.delete(l)}}return s}class rt{worker;#s;#a=1;#t=new Map;#e=new Map;#r=!1;constructor(e,t={}){this.worker=e,this.#s=t.onFatal,e.addEventListener("message",this.#o),e.addEventListener("error",this.#l),e.addEventListener("messageerror",this.#d)}get disposed(){return this.#r}supports(e){const t=e.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase();return t==="sbmx"||t==="gltf"||t==="glb"}async loadAsync(e,t={}){if(this.#r)throw new se("Model decode Worker is unavailable.");const s=this.#a++,{signal:n,loadingManager:r,...a}=t;if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError");const o=await new Promise((h,d)=>{const p={resolve:h,reject:d,manager:r,rootUrl:e,resources:new Map};if(r?.itemStart(e),n){const u=()=>{this.#t.delete(s),this.#h(p,n.reason??new DOMException("Aborted","AbortError")),d(n.reason??new DOMException("Aborted","AbortError"));try{this.#n({type:"cancel",id:s})}catch{}};p.cleanup=()=>n.removeEventListener("abort",u),n.addEventListener("abort",u,{once:!0})}this.#t.set(s,p);try{this.#n({type:"decode",id:s,url:e,options:a})}catch(u){this.#t.delete(s),p.cleanup?.();const f=u instanceof Error?u:new Error(String(u));this.#h(p,f),d(f)}}),l=[];try{return l.push(...nt(o,this.#e)),Jt(o)}catch(h){const d=new Set;for(const p of l){const u=o.imageKeys.indexOf(p),f=this.#e.get(p)??o.images[u];this.#e.get(p)===f&&this.#e.delete(p),f&&!d.has(f)&&(f.close(),d.add(f))}throw h}finally{try{this.#n({type:"ack",id:s})}catch{}}}dispose(){if(!this.#r){this.#r=!0;try{this.#n({type:"dispose"})}catch{}this.#i(),this.worker.terminate(),this.#p(new se("Model decode Worker was disposed.")),this.#e.clear()}}#n(e){this.worker.postMessage(e)}#o=e=>{const t=e.data;if(t.type==="disposed")return;if(t.type==="resolve-resource"){this.#c(t.id,t.resourceId,t.url);return}if(t.type==="resource-complete"){const n=this.#t.get(t.id),r=n?.resources.get(t.resourceId);n&&r!==void 0&&(n.resources.delete(t.resourceId),t.ok||n.manager?.itemError(r),n.manager?.itemEnd(r));return}const s=this.#t.get(t.id);if(!s){if(t.type==="decoded"){t.packet.images.forEach(n=>n.close());try{this.#n({type:"ack",id:t.id})}catch{}}return}if(this.#t.delete(t.id),s.cleanup?.(),t.type==="decoded")this.#h(s),s.resolve(t.packet);else if(t.type==="unsupported")this.#h(s,void 0,!1),s.reject(new j.UnsupportedModelDecodeError(t.reason));else{const n=ts(t.error);this.#h(s,n),s.reject(n)}};#c(e,t,s){const n=this.#t.get(e);if(!n){try{this.#n({type:"resource-resolved",id:e,resourceId:t,error:{message:"The model decode request is no longer active.",name:"AbortError"}})}catch{}return}let r;try{r=n.manager?.resolveURL(s)??s,n.manager?.itemStart(r),n.manager&&n.resources.set(t,r),this.#n({type:"resource-resolved",id:e,resourceId:t,url:r})}catch(a){r!==void 0&&n.resources.delete(t)&&(n.manager?.itemError(r),n.manager?.itemEnd(r));try{this.#n({type:"resource-resolved",id:e,resourceId:t,error:es(a)})}catch(o){this.#u(o instanceof Error?o:new Error(String(o)))}}}#l=e=>{this.#u(e.error instanceof Error?e.error:new Error(e.message))};#d=()=>{this.#u(new Error("Failed to deserialize a model decode Worker response."))};#u(e){if(this.#r)return;this.#r=!0,this.#i(),this.worker.terminate();const t=new se(`Model decode Worker failed: ${e.message}`,{cause:e});this.#p(t),this.#e.clear(),this.#s?.(t)}#i(){this.worker.removeEventListener("message",this.#o),this.worker.removeEventListener("error",this.#l),this.worker.removeEventListener("messageerror",this.#d)}#h(e,t,s=t!==void 0){for(const n of e.resources.values())t&&e.manager?.itemError(n),e.manager?.itemEnd(n);e.resources.clear(),s&&e.manager?.itemError(e.rootUrl),e.manager?.itemEnd(e.rootUrl)}#p(e){for(const t of this.#t.values())t.cleanup?.(),this.#h(t,e),t.reject(e);this.#t.clear()}}const ss=["map","alphaMap","aoMap","bumpMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","displacementMap","emissiveMap","envMap","gradientMap","iridescenceMap","iridescenceThicknessMap","lightMap","matcap","metalnessMap","normalMap","roughnessMap","sheenColorMap","sheenRoughnessMap","specularColorMap","specularIntensityMap","specularMap","thicknessMap","transmissionMap"],ns=1179937895,rs=1313821514,is="SBMG----",it=new TextDecoder;function as(i){if(i.byteLength<8||it.decode(new Uint8Array(i,0,8))!==is)return i;const e=new Uint8Array(i.byteLength-8),t=new Uint8Array(i,8);for(let s=0;s<t.length;s++){const n=t[s];e[s]=n>>4&15|n<<4&240}return e.buffer}function os(i){const e=as(i),t=new DataView(e);let s=e;if(e.byteLength>=12&&t.getUint32(0,!0)===ns){const n=Math.min(t.getUint32(8,!0),e.byteLength);let r=12,a;for(;r+8<=n;){const o=t.getUint32(r,!0),l=t.getUint32(r+4,!0);if(r+=8,r+o>n)break;if(l===rs){a=e.slice(r,r+o);break}r+=o}if(!a)throw new Error("GLB does not contain a JSON chunk.");s=a}return JSON.parse(it.decode(s).replace(/^\uFEFF/u,"").replace(/\u0000+$/u,""))}function cs(i){const e=os(i),t=new Map;for(const s of e.buffers??[])!s.uri||s.uri.startsWith("data:")||s.uri.startsWith("blob:")||t.set(s.uri,{uri:s.uri,expectedSize:s.byteLength});for(const s of e.images??[]){if(!s.uri||s.uri.startsWith("data:")||s.uri.startsWith("blob:"))continue;const n=t.get(s.uri);t.set(s.uri,{uri:s.uri,expectedSize:n?.expectedSize,mimeType:s.mimeType??n?.mimeType})}return Array.from(t.values())}function V(i){return typeof location>"u"?new URL(i).href:new URL(i,location.href).href}function ls(i){let e=0;return i.traverse(t=>{if(!t.isMesh)return;const s=t,n=Array.isArray(s.material)?s.material:[s.material];for(const r of n){if(!r)continue;let a=!1;for(const o of ss){const l=r[o];l?.isTexture&&l.image==null&&(l.dispose(),r[o]=null,a=!0,e++)}a&&(r.needsUpdate=!0)}}),e}function ee(i,e){if(ls(i)>0&&e)throw new Error("Cached model resource produced an undecoded texture.");return i}class W{static fileLoader=new c.FileLoader().setResponseType("arraybuffer");static dracoLoader=new It.DRACOLoader().setDecoderPath(`https://cdn.jsdelivr.net/npm/three@0.${c.REVISION}.0/examples/jsm/libs/draco/`);static ktx2Loader=new Ot.KTX2Loader().setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.${c.REVISION}.0/examples/jsm/libs/basis/`);static gltfLoader=new fe.GLTFLoader().setDRACOLoader(W.dracoLoader).setKTX2Loader(W.ktx2Loader).setMeshoptDecoder(ue.MeshoptDecoder);static sbmxLoader=new me().setDRACOLoader(W.dracoLoader).setKTX2Loader(W.ktx2Loader).setMeshoptDecoder(ue.MeshoptDecoder);static sbmLoader=new ge;static fbxLoader=new ve.FBXLoader;static objLoader=new vt.OBJLoader;static stlLoader=new Ct.STLLoader;static decodeWorkerClient=null;static setDecodeWorker(e){const t=this.decodeWorkerClient;if(this.decodeWorkerClient=null,t?.dispose(),!e)return()=>{};let s;return s=new rt(e,{onFatal:()=>{this.decodeWorkerClient===s&&(this.decodeWorkerClient=null)}}),this.decodeWorkerClient=s,()=>{this.decodeWorkerClient===s&&(this.decodeWorkerClient=null,s.dispose())}}static get decodeWorkerEnabled(){return this.decodeWorkerClient!==null&&!this.decodeWorkerClient.disposed}static setLoadingManager(e){this.fileLoader.manager=e,this.dracoLoader.manager=e,this.ktx2Loader.manager=e,this.gltfLoader.manager=e,this.sbmxLoader.manager=e,this.sbmLoader.manager=e,this.fbxLoader.manager=e,this.objLoader.manager=e,this.stlLoader.manager=e}static async setRenderer(e){await e.init(),this.ktx2Loader.detectSupport(e)}static setDracoPath(e){this.dracoLoader.setDecoderPath(e)}static setKTX2Path(e){this.ktx2Loader.setTranscoderPath(e)}static getMemoryCacheKey(e,t,s,n){const r=this.fileLoader.manager.resolveURL(e),a=Object.entries(this.fileLoader.requestHeader).map(([o,l])=>[o.toLowerCase(),l]).sort(([o],[l])=>o.localeCompare(l));return JSON.stringify([r,t,s,n,this.fileLoader.withCredentials?"include":"same-origin",a])}static clearPersistentCache(){return j.clearModelPersistentCache()}static deletePersistentCache(e,t={}){return j.deleteModelResourceCache(this.fileLoader.manager.resolveURL(e),{headers:{...this.fileLoader.requestHeader},credentials:this.fileLoader.withCredentials?"include":"same-origin",cacheKey:t.cacheKey})}static async loadAsync(e,t={persistent:!0}){const s=e.split(/[?#]/,1)[0].split(".").pop()?.toLowerCase(),n=t.persistent??!0,r=t.cacheMode,a=t.cacheKey,o=t.signal;this.throwIfAborted(o);const l=this.decodeWorkerClient;if(l?.supports(e)){const h=this.fileLoader.manager.resolveURL(e),d=typeof location>"u"?e:new URL(e,location.href).href,p=typeof location>"u"?h:new URL(h,location.href).href;try{return await l.loadAsync(p,{persistent:n,cacheMode:r,cacheKey:a,headers:this.fileLoader.requestHeader,credentials:this.fileLoader.withCredentials?"include":"same-origin",resourceBaseUrl:d,signal:o,loadingManager:this.fileLoader.manager})}catch(u){if(this.throwIfAborted(o),!(u instanceof j.UnsupportedModelDecodeError)&&!(u instanceof se))throw u;console.info(`[ModelLoaderManager] Decode Worker fallback for ${e}: ${u.message}`)}}return this.loadRegularModel(e,s,n,o,!0,r,a)}static async loadRegularModel(e,t,s,n,r=!0,a,o){const l=await this.loadSourceBuffer(e,s,n,a,o);this.throwIfAborted(n);let h;try{h=await this.prepareExternalGltfResources(e,t,l,s,n,a,o)}catch(u){if(this.throwIfAborted(n),!r||!l.fromCache)throw u;const f=this.cacheUseFor(l.url,o);return await j.deleteModelResourceCache(f.url,f.options),this.loadRegularModel(e,t,s,n,!1,a,o)}const d=c.LoaderUtils.extractUrlBase(e),p=this.createParseLoadingManager(n,h.replacements,h.blobUrls);try{switch(t){case"gltf":case"glb":{const f=await this.configureGltfLoader(new fe.GLTFLoader(p.manager)).parseAsync(l.buffer,d);return this.throwIfAborted(n),f.scene.animations=f.animations,ee(f.scene,l.fromCache||h.cachedResources.length>0)}case"sbmx":{const f=await this.configureGltfLoader(new me(p.manager)).parseAsync(l.buffer,d);return this.throwIfAborted(n),f.scene.animations=f.animations,ee(f.scene,l.fromCache||h.cachedResources.length>0)}case"sbm":{const f=await new ge(p.manager).setCrossOrigin(this.sbmLoader.crossOrigin).setRequestHeader(this.sbmLoader.requestHeader).setWithCredentials(this.sbmLoader.withCredentials).parseAsync(l.buffer,d);return this.throwIfAborted(n),ee(f,l.fromCache||h.cachedResources.length>0)}case"fbx":{const f=new ve.FBXLoader(p.manager).setCrossOrigin(this.fbxLoader.crossOrigin).setRequestHeader(this.fbxLoader.requestHeader).setWithCredentials(this.fbxLoader.withCredentials).parse(l.buffer,d);return this.throwIfAborted(n),ee(f,l.fromCache||h.cachedResources.length>0)}case"obj":{const u=new TextDecoder().decode(l.buffer),f=this.objLoader.parse(u);return this.throwIfAborted(n),ee(f,l.fromCache||h.cachedResources.length>0)}case"stl":{const u=this.stlLoader.parse(l.buffer);return this.throwIfAborted(n),new c.Mesh(u,new c.MeshStandardNodeMaterial)}default:throw new Error(`Unsupported model format: ${t}`)}}catch(u){this.throwIfAborted(n);const f=[...l.fromCache?[this.cacheUseFor(l.url,o)]:[],...h.cachedResources];if(!r||f.length===0)throw u;return await Promise.all(f.map(M=>j.deleteModelResourceCache(M.url,M.options))),this.loadRegularModel(e,t,s,n,!1,a,o)}finally{p.cleanup(),h.cleanup()}}static configureGltfLoader(e){return e.setDRACOLoader(this.dracoLoader).setKTX2Loader(this.ktx2Loader).setMeshoptDecoder(ue.MeshoptDecoder).setCrossOrigin(this.gltfLoader.crossOrigin).setRequestHeader(this.gltfLoader.requestHeader).setWithCredentials(this.gltfLoader.withCredentials),e}static createParseLoadingManager(e,t=new Map,s=new Set){this.throwIfAborted(e);const n=this.fileLoader.manager,r=new c.LoadingManager;r.setURLModifier(o=>{const l=n.resolveURL(o),h=(()=>{try{return V(l)}catch{return l}})();return t.get(l)??t.get(h)??l}),r.itemStart=o=>{s.has(o)||n.itemStart(o)},r.itemEnd=o=>{s.has(o)||n.itemEnd(o)},r.itemError=o=>{s.has(o)||n.itemError(o)};const a=()=>r.abort();return e?.addEventListener("abort",a,{once:!0}),{manager:r,cleanup:()=>e?.removeEventListener("abort",a)}}static rootResourceOptions(e,t,s,n){const r=this.fileLoader.manager.abortController.signal,a=t&&typeof AbortSignal.any=="function"?AbortSignal.any([t,r]):t??r;return{persistent:e,cacheMode:s,cacheKey:n,signal:a,headers:{...this.fileLoader.requestHeader},credentials:this.fileLoader.withCredentials?"include":"same-origin"}}static cacheUseFor(e,t){return{url:e,options:{headers:{...this.fileLoader.requestHeader},credentials:this.fileLoader.withCredentials?"include":"same-origin",cacheKey:t}}}static dependencyResourceOptions(e,t,s,n,r,a){let o=!1;try{const l=new URL(V(e)),h=new URL(V(t));o=(l.protocol==="http:"||l.protocol==="https:")&&l.origin===h.origin}catch{o=!1}return{persistent:s,cacheMode:r,cacheKey:a,signal:n,headers:o?{...this.fileLoader.requestHeader}:void 0,credentials:o?this.fileLoader.withCredentials?"include":"same-origin":"omit"}}static async loadManagedResource(e,t){const s=this.fileLoader.manager;s.itemStart(e);try{return await j.loadModelResource(e,t)}catch(n){throw s.itemError(e),n}finally{s.itemEnd(e)}}static async prepareExternalGltfResources(e,t,s,n,r,a,o){const l=new Map,h=new Set,d=[],p=()=>{for(const y of h)URL.revokeObjectURL(y);h.clear(),l.clear()},u={replacements:l,blobUrls:h,cachedResources:d,cleanup:p};if(!n||!j.modelPersistentCacheAvailable()||!["gltf","glb","sbmx"].includes(t??"")||typeof URL.createObjectURL!="function")return u;const f=cs(s.buffer);if(f.length===0)return u;const M=this.fileLoader.manager,C=V(e),A=V(M.resolveURL(e));let O=0;const S=async()=>{for(;O<f.length;){const y=f[O++],x=new URL(y.uri,C).href,m=V(M.resolveURL(x)),E=this.dependencyResourceOptions(m,A,n,r,a,o);let w=await this.loadManagedResource(m,E);if(y.expectedSize!==void 0&&w.buffer.byteLength<y.expectedSize&&w.fromCache&&(await j.deleteModelResourceCache(m,E),w=await this.loadManagedResource(m,E)),y.expectedSize!==void 0&&w.buffer.byteLength<y.expectedSize)throw new Error(`glTF resource is truncated: expected ${y.expectedSize}, received ${w.buffer.byteLength} from ${m}.`);w.fromCache&&d.push({url:m,options:{headers:E.headers,credentials:E.credentials,cacheKey:E.cacheKey}});const v=new Blob([w.buffer],{type:w.headers.get("content-type")??y.mimeType??"application/octet-stream"}),B=URL.createObjectURL(v);h.add(B),l.set(x,B),l.set(m,B)}};try{return await Promise.all(Array.from({length:Math.min(6,f.length)},()=>S())),u}catch(y){throw p(),y}}static async loadSourceBuffer(e,t,s,n,r){this.throwIfAborted(s);const a=this.fileLoader.manager,o=a.resolveURL(e);a.itemStart(o);try{const l=await j.loadModelResource(o,this.rootResourceOptions(t,s,n,r));return this.throwIfAborted(s),l}catch(l){throw a.itemError(o),l}finally{a.itemEnd(o)}}static throwIfAborted(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}}class hs{static textureLoader=new c.TextureLoader;static hdrLoader=new Bt.HDRLoader;static cubeTextureLoader=new c.CubeTextureLoader;static setLoadingManager(e){this.textureLoader.manager=e,this.hdrLoader.manager=e,this.cubeTextureLoader.manager=e}static async loadAsyncTexture(e){return await this.textureLoader.loadAsync(e)}static async loadAsyncHDR(e){const t=await this.hdrLoader.loadAsync(e);return t.mapping=c.EquirectangularReflectionMapping,t}static async loadAsyncCubeTexture(e,t){return this.cubeTextureLoader.setPath(e),await this.cubeTextureLoader.loadAsync(t)}}class G extends c.Mesh{isBaseMesh=!0;type="BaseMesh";castShadow=!0;receiveShadow=!0;ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class Y extends c.Group{isBaseGroup=!0;type="BaseGroup";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class at extends c.Sprite{isBaseSprite=!0;type="BaseSprite";ignoreInvisibleWhenRaycast=!0;constructor(...e){super(...e)}raycast(e,t){return this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0?!1:super.raycast(e,t)}}class k extends Y{static MAX_MEMORY_CACHE_ENTRIES=32;isModel=!0;type="Model";static memoryCache=new Map;mixer=null;animations=[];actions=new Map;constructor(){super()}async loadAsync(e){const{url:t,cache:s=!0,persistent:n=!0,cacheMode:r,cacheKey:a,signal:o}=e;try{let l;const h=["no-store","reload","revalidate"].includes(r??"");if(s&&!o&&!h){const u=W.getMemoryCacheKey(t,n,r,a);if(k.memoryCache.has(u))l=k.memoryCache.get(u),k.memoryCache.delete(u),k.memoryCache.set(u,l);else{const M=W.loadAsync(t,{persistent:n,cacheMode:r,cacheKey:a,signal:o}).catch(C=>{throw k.memoryCache.get(u)===M&&k.memoryCache.delete(u),C});for(k.memoryCache.set(u,M);k.memoryCache.size>k.MAX_MEMORY_CACHE_ENTRIES;){const C=k.memoryCache.keys().next().value;if(C===void 0)break;k.memoryCache.delete(C)}l=M}}else l=W.loadAsync(t,{persistent:n,cacheMode:r,cacheKey:a,signal:o});const d=await l,p=xe.clone(d);return this.add(p),p.animations&&p.animations.length>0&&(this.animations=p.animations,this.mixer=new c.AnimationMixer(p)),p}catch(l){return console.error(`[Model] Failed to load model from ${t}:`,l),null}}playAnimation(e,t={}){if(!this.mixer||this.animations.length===0)return null;const{loop:s=!0,repetitions:n=1/0,timeScale:r=1,clampWhenFinished:a=!1}=t;let o;if(e===void 0?o=this.animations[0]:typeof e=="number"?o=this.animations[e]:o=this.animations.find(h=>h.name===e),!o)return console.warn(`[Model] Animation not found: ${e}`),null;let l=this.actions.get(o.name);return l||(l=this.mixer.clipAction(o),this.actions.set(o.name,l)),l.setLoop(s?c.LoopRepeat:c.LoopOnce,n),l.clampWhenFinished=a,l.timeScale=r,l.reset().play(),l}playAllAnimations(e={}){return this.animations.map((t,s)=>this.playAnimation(s,e)).filter(t=>t!==null)}stopAnimation(e){if(!this.mixer)return;if(e===void 0){this.mixer.stopAllAction();return}let t;typeof e=="number"?t=this.animations[e]?.name:t=e,t&&this.actions.get(t)?.stop()}updateAnimation(e){this.mixer?.update(e)}getBoundingBox(){return new c.Box3().setFromObject(this)}getCenter(){const e=new c.Vector3;return this.getBoundingBox().getCenter(e),e}setMaterial(e){this.traverse(t=>{t instanceof c.Mesh&&(t.material=e)})}static clearMemoryCache(){this.memoryCache.clear()}static async clearPersistentCache(){await W.clearPersistentCache()}}class ot extends G{isSphereMesh=!0;type="SphereMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new c.SphereGeometry(e?.radius,e?.widthSegments,e?.heightSegments,e?.phiStart,e?.phiLength,e?.thetaStart,e?.thetaLength),this.material=new c.MeshStandardNodeMaterial(t)}}class ye extends G{isTubeMesh=!0;type="TubeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new c.TubeGeometry(e?.path,e?.tubularSegments,e?.radius,e?.radialSegments,e?.closed),this.material=new c.MeshStandardNodeMaterial(t)}}class ds extends Y{isTopology=!0;type="Topology";parameters={nodeColor:255,nodeRadius:.5,edgeColor:65280,edgeRadius:.1,pathColor:16711935,pathRadius:.2};nodes=new Map;adjacencyMap=new Map;graphGroup=null;pathMeshes=[];constructor(e){super(),e&&Object.assign(this.parameters,e)}addNode(e,t){this.nodes.has(e)&&console.warn(`[Topology] Node ${e} already exists. Overwriting.`),this.nodes.set(e,t),this.adjacencyMap.has(e)||this.adjacencyMap.set(e,new Map)}removeNode(e){if(!this.nodes.has(e)){console.warn(`[Topology] Node ${e} does not exist.`);return}this.nodes.delete(e),this.adjacencyMap.delete(e)}addEdge(e,t,s,n=!0){const r=this.nodes.get(e),a=this.nodes.get(t);if(!r||!a){console.error(`[Topology] Cannot add edge. One or both nodes not found: ${e}, ${t}`);return}const o=s??r.distanceTo(a);this.getNeighbors(e)?.set(t,o),n&&this.getNeighbors(t)?.set(e,o)}removeEdge(e,t,s=!0){this.getNeighbors(e)?.delete(t),s&&this.getNeighbors(t)?.delete(e)}getShortestPath(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))return console.warn("[Topology] Start or End node not found."),[];const s=new Map,n=new Map,r=new Set;for(const[l]of this.nodes)s.set(l,1/0),n.set(l,null),r.add(l);for(s.set(e,0);r.size>0;){let l=null,h=1/0;for(const p of r){const u=s.get(p);u<h&&(h=u,l=p)}if(l===null||l===t||h===1/0)break;r.delete(l);const d=this.adjacencyMap?.get(l);if(d)for(const[p,u]of d){if(!r.has(p))continue;const f=s.get(l)+u;f<s.get(p)&&(s.set(p,f),n.set(p,l))}}const a=[];let o=t;if(n.get(t)===null&&e!==t)return[];for(;o!==null;){const l=this.nodes.get(o);l&&a.unshift(l),o=n.get(o)||null}return a}renderGraph(){this.clearGraph(),this.graphGroup=new c.Group;const e=new ot({geometryParameters:{radius:this.parameters.nodeRadius,widthSegments:16,heightSegments:16},materialParameters:{color:this.parameters.nodeColor}});this.nodes.forEach((s,n)=>{const r=e.clone();r.position.copy(s),Object.assign(r.userData,{id:n,type:"node"}),this.graphGroup.add(r)});const t=new Set;this.adjacencyMap.forEach((s,n)=>{s.forEach((r,a)=>{const o=[n,a].sort().join("-");if(t.has(o))return;t.add(o);const l=this.nodes.get(n),h=this.nodes.get(a);if(l&&h){const d=new c.LineCurve3(l,h),p=new ye({geometryParameters:{path:d,tubularSegments:1,radius:this.parameters.edgeRadius,radialSegments:8,closed:!1},materialParameters:{color:this.parameters.edgeColor}});Object.assign(p.userData,{from:n,to:a,weight:r,type:"edge"}),this.graphGroup.add(p)}})}),this.add(this.graphGroup)}clearGraph(){this.graphGroup&&(this.remove(this.graphGroup),this.graphGroup.traverse(e=>{e instanceof c.Mesh&&(e.geometry.dispose(),e.material.dispose())}),this.graphGroup=null)}renderPath(e,t=this.parameters.pathColor){if(e.length<2)return;const s=new c.CatmullRomCurve3(e,!1,"catmullrom",0),n=new ye({geometryParameters:{path:s,tubularSegments:e.length*10,radius:this.parameters.pathRadius,closed:!1},materialParameters:{color:t}});return this.add(n),this.pathMeshes.push(n),n}clearPaths(){this.pathMeshes.forEach(e=>{this.remove(e),e.geometry.dispose(),e.material.dispose()}),this.pathMeshes=[]}exportData(){const e={};this.nodes.forEach((n,r)=>{e[r]={x:n.x,y:n.y,z:n.z}});const t=[],s=new Set;return this.adjacencyMap.forEach((n,r)=>{n.forEach((a,o)=>{const l=[r,o].sort().join("-");s.has(l)||(s.add(l),t.push({from:r,to:o,weight:a}))})}),{nodes:e,edges:t}}importData(e){this.clearGraph(),this.clearPaths(),this.nodes.clear(),this.adjacencyMap.clear(),Object.entries(e.nodes).forEach(([t,s])=>{this.addNode(t,new c.Vector3(s.x,s.y,s.z))}),e.edges.forEach(({from:t,to:s,weight:n})=>{this.addEdge(t,s,n)}),this.renderGraph()}dispose(){this.clearGraph(),this.clearPaths()}getNeighbors(e){return this.adjacencyMap.get(e)}}class us extends at{isPoi=!0;type="Poi";parameters={img:"",text:"",fontSize:32,fontFamily:"Arial",color:"#ffffff",iconSize:64,padding:10,backgroundColor:"rgba(0, 0, 0, 0)",borderRadius:8,textPosition:"right",scaleFactor:.01};_canvas=document.createElement("canvas");_lastParametersJSON="";constructor(e={}){super(new c.SpriteNodeMaterial),Object.assign(this.parameters,e),this.updateAsync()}async updateAsync(e={}){Object.assign(this.parameters,e);const t=JSON.stringify(this.parameters);if(t===this._lastParametersJSON)return;this._lastParametersJSON=t;const s=this._canvas,n=s.getContext("2d");if(!n)return;n.font=`${this.parameters.fontSize}px ${this.parameters.fontFamily}`;let r=null;this.parameters.img&&(r=await this._loadImage(this.parameters.img));const{text:a,fontSize:o,color:l,iconSize:h,padding:d,backgroundColor:p,borderRadius:u,textPosition:f,scaleFactor:M}=this.parameters,C=n.measureText(a),A=a?C.width:0,O=a?o:0;let S=0,y=0,x=0,m=0,E=0,w=0;const v=!!r,B=!!a;if(v&&B)switch(f){case"top":S=Math.max(h,A),y=h+d+O,E=(S-A)/2,w=O/2,x=(S-h)/2,m=O+d;break;case"bottom":S=Math.max(h,A),y=h+d+O,x=(S-h)/2,m=0,E=(S-A)/2,w=h+d+O/2;break;case"left":S=h+d+A,y=Math.max(h,O),E=0,w=y/2,x=A+d,m=(y-h)/2;break;default:S=h+d+A,y=Math.max(h,O),x=0,m=(y-h)/2,E=h+d,w=y/2;break}else v?(S=h,y=h,x=0,m=0):B&&(S=A,y=O,E=0,w=O/2);const I=S+d*2,L=y+d*2;if(s.width=I,s.height=L,n.font=`${o}px ${this.parameters.fontFamily}`,p&&(n.fillStyle=p,this._drawRoundedRect(n,0,0,I,L,u),n.fill()),v&&n.drawImage(r,x+d,m+d,h,h),B){n.fillStyle=l;const g=n.measureText(a),D=g.actualBoundingBoxAscent+g.actualBoundingBoxDescent,_=g.actualBoundingBoxAscent-D/2;n.textBaseline="alphabetic",n.fillText(a,E+d,w+d+_)}const P=this.material.map,N=new c.CanvasTexture(s);N.colorSpace=c.SRGBColorSpace,this.material.map=N,P?.dispose(),this.scale.set(I*M,L*M,1)}_loadImage(e){return new Promise((t,s)=>{if(typeof e=="string"){const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=()=>s(new Error(`Failed to load image: ${e}`)),n.src=e}else t(e)})}_drawRoundedRect(e,t,s,n,r,a){e.beginPath(),e.moveTo(t+a,s),e.lineTo(t+n-a,s),e.quadraticCurveTo(t+n,s,t+n,s+a),e.lineTo(t+n,s+r-a),e.quadraticCurveTo(t+n,s+r,t+n-a,s+r),e.lineTo(t+a,s+r),e.quadraticCurveTo(t,s+r,t,s+r-a),e.lineTo(t,s+a),e.quadraticCurveTo(t,s,t+a,s),e.closePath()}dispose(){this.material.map?.dispose(),this.material.dispose()}}class Se extends G{isShapeMesh=!0;type="ShapeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new c.ShapeGeometry(e?.shape,e?.curveSegments),this.material=new c.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return new Se({...t,geometryParameters:{...t.geometryParameters,shape:new c.Shape(e.map(s=>new c.Vector2(s.x,-s.z)))}})}}class Ee extends G{isExtrudeMesh=!0;type="ExtrudeMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new c.ExtrudeGeometry(e?.shape,e?.options),this.material=new c.MeshStandardNodeMaterial(t),this.geometry.rotateX(-Math.PI/2)}static createFromPoints(e,t={}){return e&&e.length===0&&(e=void 0),new Ee({...t,geometryParameters:{...t.geometryParameters,shape:new c.Shape(e?.map(s=>new c.Vector2(s.x,-s.z)))}})}}class ps extends G{isPlaneMesh=!0;type="PlaneMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(),this.geometry=new c.PlaneGeometry(e?.width,e?.height,e?.widthSegments,e?.heightSegments),this.material=new c.MeshStandardNodeMaterial(t)}}class fs extends G{isCircleMesh=!0;type="CircleMesh";constructor({geometryParameters:e,materialParameters:t}={}){super(new c.CircleGeometry(e?.radius,e?.segments,e?.thetaStart,e?.thetaLength),new c.MeshStandardNodeMaterial(t)),this.geometry.rotateX(-Math.PI/2)}}class H{static traverseMeshes(e,t){e.traverse(s=>{s instanceof c.Mesh&&t(s)})}}const ms=3,gs=1,ys=0,bs=2,ws=.001,Ie=new c.Vector3,K=new c.Vector3,Ms=new c.Quaternion;function Oe(i){return i.isInstanceObject===!0}function Be(i){let e=!1;return i.traverse(t=>{if(e)return;const s=t;e=s.isMesh===!0||s.isSprite===!0}),e}function xs(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Le(i){return i===void 0||!Number.isFinite(i)||i<=0?bs:i}class Ss{static flow(e={}){const{baseColor:t=16777215,flowColor:s=65280,speed:n=1,scale:r=3,intensity:a=4}=e,o=b.color(new c.Color(t)),l=b.color(new c.Color(s)),h=b.uv().x.mul(r).sub(b.time.mul(n)),d=b.pow(b.sin(h).add(1).mul(.5),a);return b.mix(o,l,d)}static breathe(e={}){const{baseColor:t=16777215,breathColor:s=65280,speed:n=1,intensity:r=2}=e,a=b.color(new c.Color(t)),o=b.color(new c.Color(s)),l=b.sin(b.time.mul(n)).add(1).mul(.5),h=b.pow(l,r);return b.mix(a,o,h)}static fluid(e={}){const{baseColor:t=16777215,flowColor:s=255,speed:n=1,scale:r=1,intensity:a=1,distortion:o=.5}=e,l=b.color(new c.Color(t)),h=b.color(new c.Color(s)),d=b.uv().mul(r),p=b.time.mul(n),u=b.mx_noise_float(d.add(p),1,0),f=d.add(u.mul(o)),M=b.mx_noise_float(f,1,0).add(1).mul(.5),C=b.pow(M,a);return b.mix(l,h,C)}static outline(e={}){let t=[...e.selectedObjects??[]];const s=[],n=new Map,r=new c.Box3;let a=null,o=null,l=null,h=null,d=null,p=e.instanceBoundsProxy??!0,u=e.instanceBoundsPadding??0,f=e.instanceBoundsMinSize??ws,M=Le(e.downSampleRatio);const C=b.uniform(e.edgeStrength??ms),A=b.uniform(e.edgeThickness??gs),O=b.uniform(e.edgeGlow??ys),S=b.uniform(new c.Color(e.visibleEdgeColor??16777215)),y=b.uniform(new c.Color(e.hiddenEdgeColor??5125686)),x=()=>(h??=new c.BoxGeometry(1,1,1),h),m=()=>(d||(d=new c.MeshBasicNodeMaterial({color:16777215}),d.colorWrite=!1,d.depthWrite=!1,d.name="u-space.outline.instanceBoundsProxy"),d),E=g=>{const{source:D,mesh:_}=g,T=D.getInstanceBoundingBox?.(r,!0);if(!T||T.isEmpty()||!xs(D)){_.visible=!1;return}T.getCenter(Ie),T.getSize(K);const U=Math.max(0,u),J=Math.max(0,f);K.set(Math.max(K.x+U*2,J),Math.max(K.y+U*2,J),Math.max(K.z+U*2,J)),_.visible=!0,_.layers.mask=D.layers.mask,_.matrix.compose(Ie,Ms,K),_.matrixWorldNeedsUpdate=!0},w=g=>{g.unsubscribe?.(),g.mesh.removeFromParent()},v=(g,D)=>{let _=n.get(g);if(!_){const T=new c.Mesh(x(),m());T.name=`u-space.outline.instanceBoundsProxy:${g.uuid}`,T.matrixAutoUpdate=!1,T.castShadow=!1,T.receiveShadow=!1,T.frustumCulled=!1,T.raycast=()=>{},T.userData.instanceObject=g,_={source:g,mesh:T,unsubscribe:g.onInstanceRenderDirty?.(()=>E(_))??null},n.set(g,_)}return _.mesh.parent!==D&&(_.mesh.removeFromParent(),D.add(_.mesh)),E(_),_.mesh.visible?_.mesh:null},B=(g,D)=>{const _=g.getInstanceRenderObject?.();return _&&Be(_)?_:Be(g)?g:p&&g.getInstanceBoundingBox?v(g,D):null},I=g=>{const D=new Set,_=new Set;for(const T of t){const U=Oe(T)?B(T,g):T;U&&(D.add(U),Oe(T)&&n.get(T)?.mesh===U&&_.add(T))}n.forEach((T,U)=>{_.has(U)||(w(T),n.delete(U))}),s.length=0,D.forEach(T=>s.push(T))},L=()=>{a?.dispose(),a=null},P=(g,D)=>{if(a&&o===g&&l===D)return a.downSampleRatio=M,a;L(),o=g,l=D,a=Lt.outline(g,D,{selectedObjects:s,edgeThickness:A,edgeGlow:O,downSampleRatio:M});const _=a.updateBefore.bind(a);return a.updateBefore=T=>(I(g),_(T)),a},N=((g,D)=>{const _=g.scene,T=g.camera;I(_);const U=P(_,T),J=U.visibleEdge.mul(S).add(U.hiddenEdge.mul(y)).mul(C);return b.add(D,b.vec4(J,0))});return Object.defineProperties(N,{outlineNode:{get:()=>a},selectedObjects:{get:()=>t}}),N.setSelectedObjects=g=>(t=[...g],o&&I(o),N),N.update=g=>(g.edgeStrength!==void 0&&(C.value=g.edgeStrength),g.edgeThickness!==void 0&&(A.value=g.edgeThickness),g.edgeGlow!==void 0&&(O.value=g.edgeGlow),g.visibleEdgeColor!==void 0&&S.value.set(g.visibleEdgeColor),g.hiddenEdgeColor!==void 0&&y.value.set(g.hiddenEdgeColor),g.instanceBoundsProxy!==void 0&&(p=g.instanceBoundsProxy),g.instanceBoundsPadding!==void 0&&(u=g.instanceBoundsPadding),g.instanceBoundsMinSize!==void 0&&(f=g.instanceBoundsMinSize),g.downSampleRatio!==void 0&&(M=Le(g.downSampleRatio),a&&(a.downSampleRatio=M)),o&&I(o),N),N.dispose=()=>{L(),n.forEach(w),n.clear(),h?.dispose(),d?.dispose(),h=null,d=null,t=[],s.length=0,o=null,l=null},N}}function Es(i){}const Q="uSpaceHighlight",re=`${Q}/enabled`,ct=`${Q}/opacity`,lt=`${Q}/color`,ht=`${Q}/overwrite`,dt=`${Q}/multiplyOpacity`,ce=`${Q}/instancedOriginalOpacity`,de="uSpaceBreathe",le=`${de}/enabled`,ut=`${de}/color`,pt=`${de}/speed`,ft=`${de}/intensity`,he=new WeakMap,vs=b.Fn(()=>{const i=b.userData(re,"uint"),e=b.userData(lt,"uint"),t=b.userData(ht,"uint"),s=Te(e),n=b.materialColor.mul(s),r=b.select(t.greaterThan(0),s,n),a=b.select(i.greaterThan(0),r,b.materialColor),o=b.userData(le,"uint"),l=b.userData(ut,"uint"),h=b.userData(pt,"float"),d=b.userData(ft,"float"),p=Te(l),u=b.sin(b.time.mul(h)).add(1).mul(.5),f=b.pow(u,d),M=b.mix(a,p,f);return b.select(o.greaterThan(0),M,a)})(),Cs=b.Fn(()=>{const i=b.userData(re,"uint"),e=b.userData(ct,"float"),t=b.userData(dt,"uint"),s=b.select(t.greaterThan(0),b.materialOpacity.mul(e),e);return b.select(i.greaterThan(0),s,b.materialOpacity)})();function ne(i){return Array.isArray(i.material)?i.material:[i.material]}function Ae(i){ne(i).forEach(t=>{if(!t)return;let s=he.get(t);s||(s={colorNode:t.colorNode,opacityNode:t.opacityNode,transparent:t.transparent,depthWrite:t.depthWrite,activeMeshes:new Set},he.set(t,s)),s.activeMeshes.add(i),t.transparent=!0,t.colorNode=vs,t.opacityNode=Cs,t.needsUpdate=!0})}function _e(i){const e=i.userData[re],t=i.userData[le];if(e||t)return;ne(i).forEach(n=>{if(!n)return;const r=he.get(n);r&&(r.activeMeshes.delete(i),!(r.activeMeshes.size>0)&&(n.colorNode=r.colorNode,n.opacityNode=r.opacityNode,n.transparent=r.transparent,n.depthWrite=r.depthWrite,n.needsUpdate=!0,he.delete(n)))})}function Is(i,e,t,s){const n=i,r=n.setInstanceHighlight;if(r)return r.call(i,e,t,s),!0;const a=n.setInstanceColor,o=n.setInstanceOpacity,l=n.getInstanceOpacity,h=n.getInstanceColor,d=n.hasInstanceColor;return!a||!o?!1:(i.userData[ce]===void 0&&(i.userData[ce]={hasColor:d?.call(i)??!1,color:h?.call(i,new c.Color).getHex()??16777215,opacity:l?.call(i)??1}),a.call(i,e),o.call(i,t),!0)}function Os(i){const e=i,t=e.clearInstanceHighlight;if(t)return t.call(i),!0;const s=e.resetInstanceColor,n=e.setInstanceColor,r=e.setInstanceOpacity;if(!s||!r)return!1;const a=i.userData[ce];return a&&(a.hasColor&&n?n.call(i,a.color):s.call(i),r.call(i,a.opacity),Reflect.deleteProperty(i.userData,ce)),!0}class ${static highlightColor(e,t={}){const s=Array.isArray(e)?e:[e],{opacity:n=.5,color:r=16711680,overwrite:a=!1,depthWrite:o,multiplyOpacity:l=!1}=t,h=new c.Color(r).getHex();for(const d of s)Is(d,r,n,a)||H.traverseMeshes(d,p=>{p.userData[re]=1,p.userData[ct]=n,p.userData[lt]=h,p.userData[ht]=a?1:0,p.userData[dt]=l?1:0,Ae(p),o!==void 0&&ne(p).forEach(f=>{f&&(f.depthWrite=o)})})}static removeHighlightColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)Os(s)||H.traverseMeshes(s,n=>{n.userData[re]=0,_e(n)})}static breatheColor(e,t={}){const s=Array.isArray(e)?e:[e],n=Object.assign({color:65280,speed:1,intensity:2},t);n.color=new c.Color(n.color).getHex();for(const r of s)H.traverseMeshes(r,a=>{a.userData[le]=1,a.userData[ut]=n.color,a.userData[pt]=n.speed,a.userData[ft]=n.intensity,Ae(a)})}static removeBreatheColor(e){const t=Array.isArray(e)?e:[e];for(const s of t)H.traverseMeshes(s,n=>{n.userData[le]=0,_e(n)})}static wireframe(e,t=!0){const s=Array.isArray(e)?e:[e];for(const n of s)H.traverseMeshes(n,r=>{ne(r).forEach(a=>{if(!a)return;const o=a;o.wireframe=t,o.needsUpdate=!0})})}static removeWireframe(e){$.wireframe(e,!1)}static fadeIn(e,t={}){const{duration:s=500}=t;return $._fade(e,0,1,s)}static fadeOut(e,t={}){const{duration:s=500}=t;return $._fade(e,1,0,s)}static _fade(e,t,s,n){const r=Array.isArray(e)?e:[e],a=new Map;for(const o of r)H.traverseMeshes(o,l=>{ne(l).forEach(h=>{if(!h||a.has(h))return;const d=h.opacity,p=h.transparent,u=s>=1?d:s;a.set(h,{material:h,targetOpacity:u,originalOpacity:d,originalTransparent:p}),h.transparent=!0,h.opacity=t,h.needsUpdate=!0})});return a.size===0?Promise.resolve():new Promise(o=>{const l=performance.now();let h=0;const d=()=>{const p=performance.now()-l,u=Math.min(p/n,1);if(!r[0].parent){cancelAnimationFrame(h),o();return}for(const{material:M,targetOpacity:C}of a.values())M.opacity=t+(C-t)*u,M.needsUpdate=!0;if(u<1)h=requestAnimationFrame(d);else{if(s>=1)for(const{material:M,originalOpacity:C,originalTransparent:A}of a.values())M.opacity=C,M.transparent=A,M.needsUpdate=!0;o()}};h=requestAnimationFrame(d)})}}const Te=i=>{const e=i.shiftRight(16).bitAnd(255).toFloat().div(255),t=i.shiftRight(8).bitAnd(255).toFloat().div(255),s=i.bitAnd(255).toFloat().div(255);return b.vec3(e,t,s)};class mt extends R.Tween{viewer;constructor(e,t){super(t),this.viewer=e}_update=({time:e})=>{const t=this.update(e);this.viewer.invalidate(),t||this.viewer.removeEventListener("afterControlsUpdate",this._update)};easingByMode(e){const t=Ls[e];return super.easing(t)}start(e,t){return this.viewer.addEventListener("afterControlsUpdate",this._update),super.start(e,t)}stop(){return this.viewer.removeEventListener("afterControlsUpdate",this._update),super.stop()}}function Bs(i,e,t,s={},n,r){return new Promise((a,o)=>{const{duration:l=1e3,delay:h=0,repeat:d=!1,mode:p="Linear.None",yoyo:u=!1}=s,f=new mt(i,e).to(t,l).easingByMode(p).delay(h).onUpdate(M=>{n?.(M,f)}).onComplete(()=>{a()}).onStop(()=>{o("animation stop")}).onStart(()=>{r?.(f)});typeof d=="number"?f.repeat(d):typeof d=="boolean"&&d&&f.repeat(1/0),u&&f.repeatDelay(20),f.yoyo(u),f.start()})}const Ls={"Linear.None":R.Easing.Linear.None,"Quadratic.In":R.Easing.Quadratic.In,"Quadratic.Out":R.Easing.Quadratic.Out,"Quadratic.InOut":R.Easing.Quadratic.InOut,"Cubic.In":R.Easing.Cubic.In,"Cubic.Out":R.Easing.Cubic.Out,"Cubic.InOut":R.Easing.Cubic.InOut,"Quartic.In":R.Easing.Quartic.In,"Quartic.Out":R.Easing.Quartic.Out,"Quartic.InOut":R.Easing.Quartic.InOut,"Quintic.In":R.Easing.Quintic.In,"Quintic.Out":R.Easing.Quintic.Out,"Quintic.InOut":R.Easing.Quintic.InOut,"Sinusoidal.In":R.Easing.Sinusoidal.In,"Sinusoidal.Out":R.Easing.Sinusoidal.Out,"Sinusoidal.InOut":R.Easing.Sinusoidal.InOut,"Exponential.In":R.Easing.Exponential.In,"Exponential.Out":R.Easing.Exponential.Out,"Exponential.InOut":R.Easing.Exponential.InOut,"Circular.In":R.Easing.Circular.In,"Circular.Out":R.Easing.Circular.Out,"Circular.InOut":R.Easing.Circular.InOut,"Elastic.In":R.Easing.Elastic.In,"Elastic.Out":R.Easing.Elastic.Out,"Elastic.InOut":R.Easing.Elastic.InOut,"Back.In":R.Easing.Back.In,"Back.Out":R.Easing.Back.Out,"Back.InOut":R.Easing.Back.InOut,"Bounce.In":R.Easing.Bounce.In,"Bounce.Out":R.Easing.Bounce.Out,"Bounce.InOut":R.Easing.Bounce.InOut};class As{scene;planes=new Map;helpers=new Map;group;constructor(e){this.scene=e,this.group=new c.ClippingGroup,this.group.name="__clippingToolGroup",this.scene.add(this.group)}attach(){const e=[...this.scene.children];for(const t of e)t!==this.group&&this.group.add(t)}detach(){const e=[...this.group.children];for(const t of e)this.helpers.has(t.name)||this.scene.add(t)}enable(){this.group.enabled=!0}disable(){this.group.enabled=!1}addPlane(e,t={}){const{normal:s={x:0,y:-1,z:0},constant:n=0,showHelper:r=!1,helperSize:a=5,helperColor:o=16711680}=t,l=new c.Plane(new c.Vector3(s.x,s.y,s.z),n);return this.planes.set(e,l),this._syncPlanes(),r&&this.showHelper(e,a,o),l}addBox(e,t,s={}){const{showHelpers:n=!1,helperColor:r=16711680}=s,a=t.min,o=t.max,l=[{suffix:"+x",normal:{x:-1,y:0,z:0},constant:o.x},{suffix:"-x",normal:{x:1,y:0,z:0},constant:-a.x},{suffix:"+y",normal:{x:0,y:-1,z:0},constant:o.y},{suffix:"-y",normal:{x:0,y:1,z:0},constant:-a.y},{suffix:"+z",normal:{x:0,y:0,z:-1},constant:o.z},{suffix:"-z",normal:{x:0,y:0,z:1},constant:-a.z}],h=[];for(const d of l){const p=`${e}_${d.suffix}`;this.addPlane(p,{normal:d.normal,constant:d.constant,showHelper:n,helperColor:r}),h.push(p)}return h}addBoxFromObject(e,t,s=0,n={}){const r=new c.Box3().setFromObject(t);return r.expandByScalar(s),this.addBox(e,r,n)}setPlaneConstant(e,t){const s=this.planes.get(e);s&&(s.constant=t)}removePlane(e){this.planes.delete(e),this.hideHelper(e),this._syncPlanes()}removeBox(e){const t=["+x","-x","+y","-y","+z","-z"];for(const s of t)this.removePlane(`${e}_${s}`)}removeAll(){const e=Array.from(this.helpers.keys());for(const t of e)this.hideHelper(t);this.planes.clear(),this._syncPlanes()}showHelper(e,t=5,s=16711680){this.hideHelper(e);const n=this.planes.get(e);if(!n)return;const r=new c.PlaneHelper(n,t,new c.Color(s).getHex());r.name=e,this.helpers.set(e,r),this.scene.add(r)}hideHelper(e){const t=this.helpers.get(e);t&&(this.scene.remove(t),t.dispose(),this.helpers.delete(e))}get(e){return this.planes.get(e)}_syncPlanes(){this.group.clippingPlanes=Array.from(this.planes.values())}dispose(){this.detach(),this.removeAll(),this.scene.remove(this.group)}}class _s{scene;measurements=new Map;_idCounter=0;constructor(e){this.scene=e}measureDistance(e,t,s={}){const{lineColor:n=16776960}=s,r=new c.Vector3(e.x,e.y,e.z),a=new c.Vector3(t.x,t.y,t.z),o=r.distanceTo(a),l=`measure_dist_${this._idCounter++}`,h=new c.Group;h.name=l;const d=new c.BufferGeometry().setFromPoints([r,a]),p=new c.LineBasicMaterial({color:n}),u=new c.Line(d,p);h.add(u),this.scene.add(h);const f={id:l,type:"distance",value:o,unit:"m",points:[r,a],object:h};return this.measurements.set(l,f),f}measureArea(e,t={}){const{lineColor:s=65280}=t;if(e.length<3)throw new Error("MeasureTool.measureArea requires at least 3 points");const n=e.map(f=>new c.Vector3(f.x,f.y,f.z)),r=this._calculatePolygonArea(n),a=`measure_area_${this._idCounter++}`,o=new c.Group;o.name=a;const l=[...n,n[0]],h=new c.BufferGeometry().setFromPoints(l),d=new c.LineBasicMaterial({color:s}),p=new c.Line(h,d);o.add(p),this.scene.add(o);const u={id:a,type:"area",value:r,unit:"m²",points:n,object:o};return this.measurements.set(a,u),u}measureAngle(e,t,s,n={}){const{lineColor:r=16746496}=n,a=new c.Vector3(e.x,e.y,e.z),o=new c.Vector3(t.x,t.y,t.z),l=new c.Vector3(s.x,s.y,s.z),h=a.clone().sub(o).normalize(),d=l.clone().sub(o).normalize(),u=Math.acos(Math.max(-1,Math.min(1,h.dot(d))))*180/Math.PI,f=`measure_angle_${this._idCounter++}`,M=new c.Group;M.name=f;const C=new c.BufferGeometry().setFromPoints([a,o,l]),A=new c.LineBasicMaterial({color:r}),O=new c.Line(C,A);M.add(O),this.scene.add(M);const S={id:f,type:"angle",value:u,unit:"°",points:[a,o,l],object:M};return this.measurements.set(f,S),S}get(e){return this.measurements.get(e)}remove(e){const t=this.measurements.get(e);t&&(this.scene.remove(t.object),t.object.traverse(s=>{s.geometry?.dispose(),s.material?.dispose()}),this.measurements.delete(e))}removeAll(){const e=Array.from(this.measurements.keys());for(const t of e)this.remove(t)}getAll(){return Array.from(this.measurements.values())}_calculatePolygonArea(e){const t=e.length,s=new c.Vector3;for(let r=0;r<t;r++){const a=e[r],o=e[(r+1)%t],l=new c.Vector3().crossVectors(a,o);s.add(l)}const n=new c.Vector3;if(t>=3){const r=e[1].clone().sub(e[0]),a=e[2].clone().sub(e[0]);n.crossVectors(r,a).normalize()}return Math.abs(s.dot(n))/2}dispose(){this.removeAll()}}class Ts{scene;annotations=new Map;_idCounter=0;_createCSSObject=null;constructor(e){this.scene=e}setCSSObjectFactory(e){this._createCSSObject=e}add(e,t){this.annotations.has(e)&&this.remove(e);const s=new c.Group;s.name=`annotation_${e}`;const n=new c.Vector3(t.position.x,t.position.y,t.position.z);s.position.copy(n);const r=document.createElement("div");if(r.innerHTML=t.content,r.style.cssText=`
9
9
  padding: 4px 8px;
10
10
  background: rgba(0, 0, 0, 0.75);
11
11
  color: #fff;
@@ -13,4 +13,4 @@
13
13
  border-radius: 4px;
14
14
  pointer-events: auto;
15
15
  white-space: nowrap;
16
- `,t.labelStyle)for(const h of Object.keys(t.labelStyle)){const d=t.labelStyle[h];d!==void 0&&(r.style[h]=d)}let a=null;const c=t.labelOffset||{x:0,y:2,z:0};if(t.showLeaderLine!==!1){const{lineColor:h=16777215}=t,d=new o.BufferGeometry().setFromPoints([new o.Vector3(0,0,0),new o.Vector3(c.x,c.y,c.z)]),u=new o.LineBasicMaterial({color:h});a=new o.Line(d,u),s.add(a)}if(this._createCSSObject){const h=this._createCSSObject(r);h.position.set(c.x,c.y,c.z),s.add(h)}this.scene.add(s);const l={id:e,options:t,group:s,labelElement:r,line:a};return this.annotations.set(e,l),l}addText(e,t,s={}){const n=`annotation_${this._idCounter++}`;return this.add(n,{position:t,content:e,...s})}updateContent(e,t){const s=this.annotations.get(e);s&&(s.labelElement.innerHTML=t,s.options.content=t)}updatePosition(e,t){const s=this.annotations.get(e);s&&(s.group.position.set(t.x,t.y,t.z),s.options.position=t)}show(e){const t=this.annotations.get(e);t&&(t.group.visible=!0)}hide(e){const t=this.annotations.get(e);t&&(t.group.visible=!1)}get(e){return this.annotations.get(e)}remove(e){const t=this.annotations.get(e);if(t){const s=[...t.group.children];for(const n of s)t.group.remove(n),n.geometry?.dispose(),n.material?.dispose();this.scene.remove(t.group),this.annotations.delete(e)}}removeAll(){const e=Array.from(this.annotations.keys());for(const t of e)this.remove(t)}showAll(){for(const e of this.annotations.values())e.group.visible=!0}hideAll(){for(const e of this.annotations.values())e.group.visible=!1}keys(){return Array.from(this.annotations.keys())}get size(){return this.annotations.size}dispose(){this.removeAll()}}const Te=new o.Matrix4,vs=1e-6,Is=1e-6,De="uSpaceInstanceOriginalMaterialState",ye=0,ae=1,ft=2;function Cs(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Bs(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>vs)return!1;return!0}function mt(i){const e=i.material;return Array.isArray(e)?e:[e]}function gt(i){const e=i.userData,t=e[De];if(t)return t;const s={transparent:i.transparent,opacity:i.opacity};return e[De]=s,s}function Os(i,e){i.traverse(t=>{const s=t;s.isMesh&&mt(s).forEach(n=>{if(!n)return;const r=n,a=gt(r),c=a.opacity*e;r.transparent=a.transparent||c<1,r.opacity=c,r.needsUpdate=!0})})}function As(i){i.traverse(e=>{const t=e;t.isMesh&&mt(t).forEach(s=>{if(!s)return;const n=s,r=gt(n);n.transparent=r.transparent,n.opacity=r.opacity,n.needsUpdate=!0})})}class _s extends q{isInstanceObject=!0;type="InstanceObject";instanceId="";instanceKind="";instanceName="";geometry=new o.BufferGeometry;boundingBox=null;boundingSphere=null;#s={color:null,colorMode:ye,opacity:1};#a=null;#t=null;#e=null;#r=null;#n=new Set;#o=new o.Matrix4;#c=!1;#l=!0;#d=!1;#u;constructor(e={}){super(),this.#u=e.boundsName??"InstanceBounds"}setInstanceIdentity(e){let t=!1;if(e.id!==void 0){const s=e.id??"";this.instanceId!==s&&(this.instanceId=s,t=!0)}if(e.kind!==void 0){const s=e.kind??"";this.instanceKind!==s&&(this.instanceKind=s,t=!0)}if(e.name!==void 0){const s=e.name??"";this.instanceName!==s&&(this.instanceName=s,t=!0)}return t&&this.markInstanceRenderDirty(),this}setInstanceBounds(e){if(e.isEmpty())return this;this.#t&&this.remove(this.#t);const t=new o.BufferGeometry;t.boundingBox=e.clone();const s=new o.Object3D;return s.name=this.#u,s.visible=!1,s.geometry=t,s.raycast=()=>{},this.#t=s,this.add(s),this.#h(),this.markInstanceRenderDirty(),this}setInstanceRenderObject(e){return this.#e&&this.#e!==e&&this.#e.parent===this&&this.remove(this.#e),this.#e=e,e&&e.parent!==this&&this.add(e),this.#f(),this.#h(),this.markInstanceRenderDirty(),this}getInstanceRenderObject(){return this.#e}setInstanceMaterializer(e){return this.#r=e,this}hasInstanceMaterializer(e){return this.#r===e}clearInstanceMaterializer(e){return(e===void 0||this.#r===e)&&(this.#r=null),this}materialize(){return this.#r?.()??this.#e??null}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new o.Box3),this.getInstanceBoundingBox(this.boundingBox,!1)}computeBoundingSphere(){if(this.boundingSphere===null&&(this.boundingSphere=new o.Sphere),this.boundingBox===null&&this.computeBoundingBox(),!this.boundingBox||this.boundingBox.isEmpty()){this.boundingSphere.makeEmpty();return}this.boundingBox.getBoundingSphere(this.boundingSphere)}getInstanceBoundingBox(e=new o.Box3,t=!1){const s=this.#t?.geometry?.boundingBox;return s?(e.copy(s),t&&(this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)),e):this.#e?(e.setFromObject(this.#e),t||(this.updateWorldMatrix(!0,!1),Te.copy(this.matrixWorld).invert(),e.applyMatrix4(Te)),e):e.makeEmpty()}setInstanceVisible(e){return this.visible===e?this:(this.visible=e,this.markInstanceRenderDirty(),this)}setInstanceColor(e){return this.#s.color=new o.Color(e),this.#s.colorMode=ae,this.#f(),this.markInstanceRenderDirty(),this}resetInstanceColor(){return this.#s.color===null?this:(this.#s.color=null,this.#s.colorMode=ye,this.#f(),this.markInstanceRenderDirty(),this)}setInstanceOpacity(e){const t=Math.max(0,Math.min(1,e));return Math.abs(this.#s.opacity-t)<=Is?this:(this.#s.opacity=t,this.#f(),this.markInstanceRenderDirty(),this)}getInstanceColor(e=new o.Color){const t=this.#p();return t.color?e.copy(t.color):e.setRGB(1,1,1)}hasInstanceColor(){return this.#p().color!==null}getInstanceOpacity(){return this.#p().opacity}setInstanceHighlight(e,t,s=!1){return this.#a={color:new o.Color(e),colorMode:s?ae:ft,opacity:Math.max(0,Math.min(1,t))},this.#f(),this.markInstanceRenderDirty(),this}clearInstanceHighlight(){return this.#a===null?this:(this.#a=null,this.#f(),this.markInstanceRenderDirty(),this)}getInstanceColorMode(){return this.#p().colorMode}onInstanceRenderDirty(e){return this.#n.add(e),()=>this.#n.delete(e)}markInstanceRenderDirty(){return this.#n.forEach(e=>e()),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this.#i()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.#i()}#i(){const e=Cs(this);(!this.#c||!Bs(this.matrixWorld,this.#o)||!this.#d||e!==this.#l)&&(this.#c=!0,this.#d=!0,this.#o.copy(this.matrixWorld),this.#l=e,this.markInstanceRenderDirty())}#h(){this.boundingBox=null,this.boundingSphere=null}#p(){return this.#a??this.#s}#f(){if(!this.#e)return;const e=this.#p();if(e.color){As(this.#e),H.highlightColor(this.#e,{color:e.color,opacity:e.opacity,overwrite:e.colorMode===ae,multiplyOpacity:!0});return}H.removeHighlightColor(this.#e),Os(this.#e,e.opacity)}}function Ls(i){return i.isInstanceObject===!0}const Ts=new Set(["MeshBasicMaterial","MeshLambertMaterial","MeshPhongMaterial","MeshStandardMaterial","MeshPhysicalMaterial"]),Ne=new WeakMap;let Ds=1;const Re=new o.Matrix4,Z=new o.Matrix4,Pe=new o.Matrix4;function Ns(i,e,t=1e-6){const s=i.elements,n=e.elements;for(let r=0;r<16;r++)if(Math.abs(s[r]-n[r])>t)return!1;return!0}function yt(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Rs(i){const e=i.source.data;if(!e||typeof e!="object"&&typeof e!="function")return`texture:${i.uuid}`;let t=Ne.get(e);return t===void 0&&(t=Ds++,Ne.set(e,t)),`source:${t}`}function Ps(i){return JSON.stringify([Rs(i),i.mapping,i.channel,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.anisotropy,i.format,i.internalFormat,i.type,i.offset.toArray(),i.repeat.toArray(),i.center.toArray(),i.rotation,i.matrixAutoUpdate,i.matrix.toArray(),i.generateMipmaps,i.premultiplyAlpha,i.flipY,i.unpackAlignment,i.colorSpace,"compareFunction"in i?i.compareFunction:null])}function be(i){if(Array.isArray(i))return i.map(be);if(!i||typeof i!="object")return i;const e=i;return Object.fromEntries(Object.keys(e).sort().map(t=>[t,be(e[t])]))}function we(i,e){if(Array.isArray(i))return i.map(s=>we(s,e));if(!i||typeof i!="object")return typeof i=="string"?e.get(i)??i:i;const t=i;return Object.fromEntries(Object.keys(t).filter(s=>s!=="metadata"&&s!=="uuid"&&s!=="name").sort().map(s=>[s,we(t[s],e)]))}function ks(i){if(!Ts.has(i.type)||i.transparent||i.opacity<.999||i.visible===!1)return null;const e=i;if(Object.keys(e).some(r=>r.endsWith("Node")&&e[r]!=null)||Object.hasOwn(i,"onBeforeCompile"))return null;const t=new Map;Object.values(e).forEach(r=>{r instanceof o.Texture&&t.set(r.uuid,Ps(r))});const s={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n=i.toJSON(s);return JSON.stringify(be(we(n,t)))}function js(i){if(Object.keys(i.morphAttributes).length>0||i.drawRange.start!==0||i.drawRange.count!==1/0)return null;const e=Object.entries(i.attributes).sort(([t],[s])=>t.localeCompare(s)).map(([t,s])=>"isInterleavedBufferAttribute"in s?null:[t,s.itemSize,s.normalized,s.array.constructor.name,s.gpuType]);return e.some(t=>t===null)?null:JSON.stringify([i.index?.array.constructor.name??"non-indexed",e])}function Us(i,e){const t=[],s=new Set,n=new Set,r=!e&&(i.animations.length>0||i.mixer!==null);return r&&n.add("animation"),i.updateWorldMatrix(!0,!0),Re.copy(i.matrixWorld).invert(),i.traverseVisible(a=>{if(!(a instanceof o.Mesh))return;if(r){s.add(a);return}if(a instanceof o.SkinnedMesh){s.add(a),n.add("skinned");return}if(a.morphTargetInfluences){s.add(a),n.add("morph");return}if(Array.isArray(a.material)){s.add(a),n.add("material-array");return}const c=ks(a.material),l=js(a.geometry);if(!c){s.add(a),n.add(a.material.transparent||a.material.opacity<.999?"transparent":`material:${a.material.type}`);return}if(!l){s.add(a),n.add("geometry-layout");return}if(a.matrixWorld.determinant()<=0){s.add(a),n.add("negative-scale");return}t.push({mesh:a,localMatrix:Re.clone().multiply(a.matrixWorld),materialKey:c,geometryKey:l})}),t.length===0&&s.size===0&&n.add("empty"),{meshes:t,fallbackMeshes:s,fallbackReasons:n}}function zs(i,e){const t=Me.clone(i),s=[],n=[];return i.traverse(r=>{r instanceof o.Mesh&&s.push(r)}),t.traverse(r=>{r instanceof o.Mesh&&n.push(r)}),s.forEach((r,a)=>{e.has(r)&&n[a]&&(n[a].visible=!1)}),t}function Fs(i){const e=Me.clone(i),t=new Map,s=n=>{let r=t.get(n);return r||(r=n.clone(),t.set(n,r)),r};return e.traverse(n=>{n instanceof o.Mesh&&(n.material=Array.isArray(n.material)?n.material.map(s):s(n.material))}),e}function Ws(i){return Math.max(1,Math.ceil(Math.sqrt(Math.max(1,i))))}function Gs(i){const e=new o.DataTexture(new Float32Array(i*i*4),i,i,o.RGBAFormat,o.FloatType);return e.magFilter=o.NearestFilter,e.minFilter=o.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e}function Hs(i,e){const t=i.clone(),s=g.attribute("batchObjectIndex","float").toInt(),n=g.int(g.textureSize(g.textureLoad(e),g.int(0)).x).toConst(),r=s.mod(n).toConst(),a=s.div(n).toConst(),c=g.textureLoad(e,g.ivec2(r,a)),l=t.colorNode??g.materialColor,h=g.select(c.a.greaterThan(1.5),l.mul(c.rgb),c.rgb);return t.colorNode=g.select(c.a.greaterThan(.5),h,l),t.maskNode=c.a.greaterThan(-.5),t.needsUpdate=!0,t}function ke(i){let e=0,t=i.parent;for(;t;)e++,t=t.parent;return e}class $s extends F{objectIndices;states;#s;constructor(e,t,s,n){super(e,t),this.objectIndices=s,this.states=n,this.userData.editableGeometryBatch=!0}raycast(e,t){if(this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0)return!1;this.#s===void 0&&(this.#s=j.getGeometryBoundsTree(this.geometry));const s=[];this.#s?this.#s.raycastObject3D(this,e,s):super.raycast(e,s),s.forEach(n=>{const r=n.faceIndex;if(r==null)return;const a=r*3,c=this.geometry.index?.getX(a)??a,l=this.objectIndices[c],h=l===void 0?void 0:this.states[l],d=h?.instance;!h||h.materialized||!d||!yt(d)||d.getInstanceOpacity()<=.001||(n.object=d,n.batchObjectIndex=l,t.push(n))})}}class Vs extends q{isEditableGeometryBatchLayer=!0;type="EditableGeometryBatchLayer";options;stats={instances:0,sourceMeshes:0,batches:0,drawCallsSaved:0,vertices:0,indices:0,unsupportedInstances:0,unsupportedByReason:{}};#s=[];#a=new Set;#t=[];#e=new Map;#r=new Set;#n=null;#o=new o.Matrix4;#c=!1;#l=!1;#d=!1;constructor(e={}){super(),this.name="EditableGeometryBatches",this.options={maxVerticesPerBatch:e.maxVerticesPerBatch??15e5,maxIndicesPerBatch:e.maxIndicesPerBatch??45e5,freezeAnimations:e.freezeAnimations??!1}}addSource(e){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer has already been built.");const{key:t,template:s,instances:n}=e,r=new Set;n.forEach(h=>{if(r.has(h)||this.#a.has(h))throw new Error("EditableGeometryBatchLayer cannot batch the same InstanceObject more than once.");r.add(h)});const{meshes:a,fallbackMeshes:c,fallbackReasons:l}=Us(s,this.options.freezeAnimations);return r.forEach(h=>this.#a.add(h)),this.#s.push({key:t,template:s,instances:[...n],meshes:a,fallbackMeshes:c,fallbackReasons:l,bounds:new o.Box3().setFromObject(s)}),a.length>0}build(){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer.build() can only be called once.");this.#c=!0,this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=[],t=new Map,s=(r,a,c,l)=>{if(c.length===0)return;const h=l.size>0?[...l]:["unknown"];e.push({key:r.key,template:a,instances:c,reasons:h}),h.forEach(d=>{this.stats.unsupportedByReason[d]=(this.stats.unsupportedByReason[d]??0)+c.length})};this.#s.forEach(r=>{const a=[],c=[];r.instances.forEach(h=>{h.updateWorldMatrix(!0,!1),Z.multiplyMatrices(this.#o,h.matrixWorld),Z.determinant()<=0?c.push(h):a.push({instance:h,matrix:Z.clone()})});const l=r.fallbackReasons.size>0?r.fallbackReasons:new Set(["unknown"]);if(r.meshes.length===0){s(r,r.template,a.map(({instance:h})=>h),l),s(r,r.template,c,new Set([...l,"negative-scale"]));return}r.fallbackMeshes.size>0&&s(r,zs(r.template,new Set(r.meshes.map(({mesh:h})=>h))),a.map(({instance:h})=>h),l),s(r,r.template,c,new Set([...r.fallbackReasons,"negative-scale"])),a.forEach(({instance:h,matrix:d})=>{const u=this.#t.length,p=()=>this.materialize(h),f={instance:h,template:r.template,initialMatrix:d,objectIndex:u,materialized:!1,materializer:p,unsubscribe:()=>{}};f.unsubscribe=h.onInstanceRenderDirty(()=>this.#h(f)),this.#t.push(f),this.#e.set(h,f),h.setInstanceBounds(r.bounds),h.setInstanceMaterializer(p),this.#r.add(f),r.meshes.forEach(({mesh:S,localMatrix:C,materialKey:D,geometryKey:O})=>{Pe.multiplyMatrices(d,C);const w=S.geometry.clone().applyMatrix4(Pe),x=w.getAttribute("position");w.setAttribute("batchObjectIndex",new o.Float32BufferAttribute(new Float32Array(x.count).fill(u),1));const b=JSON.stringify([D,O,S.castShadow,S.receiveShadow,S.renderOrder]),y=t.get(b),E={geometry:w,material:S.material,castShadow:S.castShadow,receiveShadow:S.receiveShadow,renderOrder:S.renderOrder,objectIndices:new Array(x.count).fill(u)};y?y.push(E):t.set(b,[E]),this.stats.sourceMeshes++,this.stats.vertices+=x.count,this.stats.indices+=w.index?.count??x.count})})}),this.stats.instances=this.#t.length,this.stats.unsupportedInstances=e.reduce((r,a)=>r+a.instances.length,0);const n=Ws(this.#t.length);return this.#n=Gs(n),this.#i(),t.forEach(r=>this.#u(r)),this.stats.batches=this.children.length,this.stats.drawCallsSaved=Math.max(0,this.stats.sourceMeshes-this.stats.batches),this.children.forEach(r=>{r instanceof o.Mesh&&(r.onBeforeRender=()=>this.#i())}),{stats:{...this.stats},unsupported:e}}materialize(e){const t=this.#e.get(e);if(!t||t.materialized)return e.getInstanceRenderObject();const s=Fs(t.template);return s.position.set(0,0,0),s.quaternion.identity(),s.scale.set(1,1,1),s.matrix.identity(),t.materialized=!0,e.setInstanceRenderObject(s),s.updateWorldMatrix(!0,!0),this.#r.add(t),this.dispatchEvent({type:"materialize",instance:e,object:s}),s}#u(e){const t=[];let s=[],n=0,r=0;e.forEach(a=>{const c=a.geometry.getAttribute("position").count,l=a.geometry.index?.count??c;s.length>0&&(n+c>this.options.maxVerticesPerBatch||r+l>this.options.maxIndicesPerBatch)&&(t.push(s),s=[],n=0,r=0),s.push(a),n+=c,r+=l}),s.length>0&&t.push(s),t.forEach(a=>{const c=Ot.mergeGeometries(a.map(p=>p.geometry),!1);if(a.forEach(p=>p.geometry.dispose()),!c||!this.#n)return;c.computeBoundingBox(),c.computeBoundingSphere();const l=a[0],h=a.flatMap(p=>p.objectIndices),d=Hs(l.material,this.#n),u=new $s(c,d,h,this.#t);u.name=`EditableGeometryBatch:${this.children.length}`,u.castShadow=l.castShadow,u.receiveShadow=l.receiveShadow,u.renderOrder=l.renderOrder,u.matrixAutoUpdate=!1,this.add(u)})}#i(){if(!(!this.#n||this.#r.size===0||this.#d)){this.#d=!0;try{this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=this.#n.image.data;[...this.#r].sort((t,s)=>ke(t.instance)-ke(s.instance)).forEach(t=>{const{instance:s,objectIndex:n}=t;s.updateWorldMatrix(!0,!1),Z.multiplyMatrices(this.#o,s.matrixWorld),!t.materialized&&s.getInstanceRenderObject()!==null&&!s.hasInstanceMaterializer(t.materializer)&&(t.materialized=!0),!t.materialized&&!Ns(Z,t.initialMatrix)&&this.materialize(s),!t.materialized&&s.getInstanceOpacity()<.999&&this.materialize(s);const r=n*4,a=!t.materialized&&yt(s)&&s.getInstanceOpacity()>.001,c=s.getInstanceColor();e[r]=c.r,e[r+1]=c.g,e[r+2]=c.b,e[r+3]=a?s.getInstanceColorMode():-1,this.#r.delete(t)}),this.#n.needsUpdate=!0}finally{this.#d=!1}this.#r.size>0&&this.#i()}}#h(e){this.#r.add(e),this.#i()}dispose(){this.#l||(this.#l=!0,this.#t.forEach(e=>{e.unsubscribe(),e.instance.clearInstanceMaterializer(e.materializer)}),this.#t.length=0,this.#e.clear(),this.#a.clear(),this.#r.clear(),this.#s.length=0,this.#n?.dispose(),this.#n=null,this.traverse(e=>{if(!(e instanceof o.Mesh))return;e.geometry.dispose(),(Array.isArray(e.material)?e.material:[e.material]).forEach(s=>s.dispose())}),this.clear())}}const je=new o.Matrix4,re=new o.Matrix4,Ue=new o.Matrix4,ze=new o.Matrix4,Fe=new o.Box3,We=new o.Sphere,Ge=new o.Sphere,Ks=new o.Frustum,V=new o.Color,He=new o.Vector2,$e=new o.Vector3,Ve=new o.Matrix4,Ke=new o.Matrix4,qe=new o.Sphere,ie=[],bt=1e-6,U=1e-6,wt=.999,qs=0,Xe=1;function Xs(i,e,t){const s=i.elements;for(let n=0;n<16;n++)if(Math.abs(s[n]-e[t+n])>bt)return!1;return!0}function Ys(i,e,t,s){return Math.abs(i.r-t[s])<=U&&Math.abs(i.g-t[s+1])<=U&&Math.abs(i.b-t[s+2])<=U&&Math.abs(e-t[s+3])<=U}function Ye(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>bt)return!1;return!0}function ue(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Qs(i){const e=i.geometry.morphAttributes;return Object.values(e).some(t=>t?.length)}function Js(i){const e=i.material;if(!Array.isArray(e))return!0;if(e.length===0||!e.every(Boolean))return!1;const t=i.geometry.groups;return t.length===0?!1:t.every(s=>{const n=s.materialIndex??0;return Number.isInteger(s.start)&&s.start>=0&&Number.isInteger(s.count)&&s.count>0&&Number.isInteger(n)&&n>=0&&n<e.length})}function Zs(i){return!i.isSkinnedMesh&&!Qs(i)&&Js(i)}function Qe(i){return Array.isArray(i)?i:[i]}function Mt(i){return i.transparent||i.opacity<wt}function Je(i,e,t){const s=i.clone(),n=g.instancedBufferAttribute(e,"vec4",4,0),r=g.instancedBufferAttribute(t,"float",1,0),a=s.colorNode??g.materialColor,c=s.opacityNode?g.float(s.opacityNode):g.materialOpacity,l=g.select(n.a.greaterThan(1.5),a.mul(n.rgb),n.rgb);return s.colorNode=g.select(n.a.greaterThan(.5),l,a),s.opacityNode=c.mul(r),s.transparent=Mt(i),s.needsUpdate=!0,s}function en(i,e,t){return Array.isArray(i)?i.map(s=>Je(s,e,t)):Je(i,e,t)}function tn(i){const e=[],t=new o.Matrix4;let s=!1;return i.updateWorldMatrix(!0,!0),t.copy(i.matrixWorld).invert(),i.traverse(n=>{if(!s&&!(!(n instanceof o.Mesh)||!n.visible)){if(!Zs(n)){s=!0;return}n.updateWorldMatrix(!0,!1),e.push({mesh:n,localMatrix:t.clone().multiply(n.matrixWorld)})}}),s?[]:e}function sn(i){const e=new o.Box3;return i.forEach(({mesh:t,localMatrix:s})=>{const n=t.geometry;n.boundingBox||n.computeBoundingBox(),n.boundingBox&&(Fe.copy(n.boundingBox).applyMatrix4(s),e.union(Fe))}),e}function K(i){const e=i;"needsUpdate"in e&&(e.needsUpdate=!0)}function Ze(i,e=Xe){let t=Math.max(Xe,e);for(;t<i;)t*=2;return t}function nn(i){return i!==null&&typeof i=="object"&&Symbol.iterator in i}class rn extends q{isModelInstancedLayer=!0;type="ModelInstancedLayer";#s=[];#a=new Map;#t=new Map;#e=new Map;#r=!0;#n=!1;#o=!0;#c=qs;#l;#d;constructor(e={}){super(),this.name=e.name??"ModelInstances",this.#l=e.instanceKind??"",this.#d=e.getHitUserData??(()=>({}))}get instanceKind(){return this.#l}getInstances(){const e=[];return this.#i(t=>e.push(t)),e}getInstanceById(e){return this.#w(),this.#e.get(e)}hasInstance(e){return this.#w(),this.#e.has(e)}getInstanceCulling(){return{enabled:this.#n,frustum:this.#o,minScreenRadius:this.#c}}setInstanceCulling(e={}){let t=!1;if(e.enabled!==void 0&&this.#n!==e.enabled&&(this.#n=e.enabled,t=!0),e.frustum!==void 0&&this.#o!==e.frustum&&(this.#o=e.frustum,t=!0),e.minScreenRadius!==void 0){const s=Math.max(0,e.minScreenRadius);Math.abs(this.#c-s)>U&&(this.#c=s,t=!0)}return t&&this.#s.forEach(s=>this.#v(s)),this}setInstanceVisible(e){return this.visible!==e&&(this.visible=e),this.#i(t=>{t.setInstanceVisible(e)}),this}setInstanceColor(e){return this.#i(t=>{t.setInstanceColor(e)}),this}resetInstanceColor(){return this.#i(e=>{e.resetInstanceColor()}),this}setInstanceOpacity(e){return this.#i(t=>{t.setInstanceOpacity(e)}),this}setInstanceHighlight(e,t,s=!1){return this.#i(n=>{n.setInstanceHighlight(e,t,s)}),this}clearInstanceHighlight(){return this.#i(e=>{e.clearInstanceHighlight()}),this}reserveBatch(e,t,s){const n=Math.floor(s);return n<=0?!1:this.#u(e,t,n)!==null}addInstance(e,t,s){return this.addInstances(e,t,[s])}addInstances(e,t,s){if(s.length===0)return!1;const n=this.#a.has(e),r=this.#u(e,t,s.length);if(!r)return!1;const a=[],c=new Set;return s.forEach(l=>{c.has(l)||(c.add(l),this.#t.get(l)===r)||a.push(l)}),a.length===0?!0:this.#C(a)?(a.forEach(l=>{const h=this.#t.get(l);h&&h!==r&&this.#S(h,l)}),this.#x(r,r.instances.length+a.length),a.forEach(l=>{l.setInstanceBounds(r.templateBounds),r.instances.push(l),this.#t.set(l,r),r.unsubscribeByInstance.set(l,l.onInstanceRenderDirty(()=>{this.#g(),this.#y(r)}))}),this.#g(),this.#b(r),this.#y(r),!0):(!n&&r.instances.length===0&&this.#m(r),!1)}removeInstance(e){return this.removeInstances([e])>0}removeInstances(e){const t=new Set,s=new Set,n=typeof e=="string"||!nn(e)?[e]:e;for(const a of n)typeof a=="string"?t.add(a):this.#t.has(a)&&s.add(a);t.size>0&&(this.#w(),t.forEach(a=>{const c=this.#e.get(a);c&&s.add(c)}));let r=0;return s.forEach(a=>{const c=this.#t.get(a);c&&this.#S(c,a)&&r++}),r}removeBatch(e){const t=this.#a.get(e);return t?(this.#m(t),!0):!1}clearBatches(){return[...this.#a.values()].forEach(e=>this.#m(e)),this}#u(e,t,s){const n=this.#a.get(e);if(n)return this.#x(n,s),n;if(t.animations?.length)return null;const r=tn(t);if(r.length===0)return null;const a=sn(r),c=new o.Group;c.name=e,this.add(c);const l={url:e,batch:c,templateMeshes:r,templateBounds:a,records:[],instances:[],unsubscribeByInstance:new Map,capacity:Ze(s)};return r.forEach(({mesh:h,localMatrix:d},u)=>{const p=this.#h(l,h,d,u);l.records.push(p),this.#s.push(p)}),this.#a.set(e,l),this.#b(l),l}#i(e){const t=new Set;this.#a.forEach(s=>{s.instances.forEach(n=>{t.has(n)||(t.add(n),e(n))})})}#h(e,t,s,n){const r=new o.InstancedBufferAttribute(new Float32Array(e.capacity*4),4),a=new o.InstancedBufferAttribute(new Float32Array(e.capacity).fill(1),1);r.setUsage(o.DynamicDrawUsage),a.setUsage(o.DynamicDrawUsage);const c=en(t.material,r,a),l=Qe(c),h=Qe(t.material).some(Mt),d=new o.InstancedMesh(t.geometry,c,e.capacity);d.instanceMatrix=new o.StorageInstancedBufferAttribute(e.capacity,16),d.count=0,d.name=t.name||`${e.url}#${n}`,d.castShadow=t.castShadow,d.receiveShadow=t.receiveShadow,d.frustumCulled=!0,d.matrixAutoUpdate=!1,d.instanceMatrix.setUsage(o.DynamicDrawUsage),d.userData.url=e.url;const u=new o.Mesh(t.geometry,c);u.matrixAutoUpdate=!1;const p={batchRecord:e,mesh:d,boundsTree:void 0,raycastMesh:u,localMatrix:s.clone(),fullBoundingSphere:new o.Sphere,materials:l,hasSourceTransparency:h,colorAttribute:r,opacityAttribute:a,renderedInstances:[],visibleInstances:[],lastCameraMatrixWorldInverse:new o.Matrix4,lastCameraProjectionMatrix:new o.Matrix4,lastViewportHeight:0,hasLastCameraState:!1,dirty:!0};d.userData.getInstanceObjectByRenderIndex=S=>p.renderedInstances[S],d.userData.raycastAcceleration="lazy";const f=d.raycast.bind(d);return d.raycast=(S,C)=>{if(this.#I(p),!this.#p(p,S))return;p.boundsTree===void 0&&(p.boundsTree=j.getGeometryBoundsTree(p.mesh.geometry),p.mesh.userData.raycastAcceleration=p.boundsTree?"three-mesh-bvh":"default");const D=C.length;p.boundsTree?this.#f(p,S,C):f(S,C);for(let O=D;O<C.length;){const w=C[O],x=w.instanceId;if(x===void 0){O++;continue}const b=p.renderedInstances[x];if(!b||!ue(b)){C.splice(O,1);continue}w.object=b,w.instanceObject=b,w.instanceObjectId=b.instanceId,w.instanceKind=b.instanceKind||this.#l,w.instanceName=b.instanceName,w.instanceIndex=x,Object.assign(w,this.#d(b,x)),O++}},d.onBeforeRender=(S,C,D)=>this.#I(p,S,D),e.batch.add(d),p}#p(e,t){const{mesh:s}=e;return s.count===0?!1:(s.boundingSphere===null&&s.computeBoundingSphere(),s.boundingSphere?(qe.copy(s.boundingSphere).applyMatrix4(s.matrixWorld),t.ray.intersectsSphere(qe)):!0)}#f(e,t,s){const{mesh:n,boundsTree:r,raycastMesh:a}=e;if(!(!r||n.count===0)){a.geometry=n.geometry,a.material=n.material;for(let c=0;c<n.count;c++)n.getMatrixAt(c,Ve),Ke.multiplyMatrices(n.matrixWorld,Ve),a.matrixWorld.copy(Ke),ie.length=0,r.raycastObject3D(a,t,ie),ie.forEach(l=>{l.instanceId=c,l.object=n,s.push(l)}),ie.length=0}}#x(e,t){if(t<=e.capacity)return;e.capacity=Ze(t,e.capacity);const s=new Set(e.records);s.forEach(n=>this.#E(n)),this.#s=this.#s.filter(n=>!s.has(n)),e.records=e.templateMeshes.map(({mesh:n,localMatrix:r},a)=>{const c=this.#h(e,n,r,a);return this.#s.push(c),c}),this.#y(e)}#S(e,t){const s=e.instances.indexOf(t);return s===-1?!1:(e.instances.splice(s,1),e.records.forEach(n=>n.visibleInstances.splice(s,1)),this.#t.delete(t),this.#g(),e.unsubscribeByInstance.get(t)?.(),e.unsubscribeByInstance.delete(t),e.instances.length===0?(this.#m(e),!0):(this.#b(e),this.#y(e),!0))}#m(e){e.unsubscribeByInstance.forEach(s=>s()),e.instances.forEach(s=>this.#t.delete(s)),e.unsubscribeByInstance.clear(),e.instances.length=0,this.#g();const t=new Set(e.records);t.forEach(s=>this.#E(s)),this.#s=this.#s.filter(s=>!t.has(s)),e.records.length=0,e.templateMeshes.length=0,this.#a.delete(e.url),this.remove(e.batch)}#E(e){e.batchRecord.batch.remove(e.mesh),e.mesh.dispose(),e.materials.forEach(t=>t.dispose())}#b(e){Object.assign(e.batch.userData,{url:e.url,count:e.instances.length,capacity:e.capacity,instanceKind:this.#l}),delete e.batch.userData.sceneInstances,delete e.batch.userData.facilities,e.records.forEach(t=>{delete t.mesh.userData.instances})}#C(e){const t=new Set(e),s=new Map;for(const r of e){const{instanceId:a}=r;if(!a)continue;const c=s.get(a);if(c&&c!==r)return!1;s.set(a,r)}let n=!0;return s.forEach((r,a)=>{n&&this.#i(c=>{!n||t.has(c)||c.instanceId===a&&(n=!1)})}),n}#w(){if(!this.#r)return;this.#e.clear();const e=new Set;this.#i(t=>{const{instanceId:s}=t;if(!s||e.has(s))return;const n=this.#e.get(s);if(n&&n!==t){this.#e.delete(s),e.add(s);return}this.#e.set(s,t)}),this.#r=!1}#g(){this.#r=!0}#y(e){e.records.forEach(t=>this.#v(t))}#v(e){e.dirty=!0,e.hasLastCameraState=!1,e.mesh.visible=!0,e.mesh.frustumCulled=!1,K(e.batchRecord.batch)}#I(e,t,s){const n=this.#O(t),r=this.#A(e,s,n);!e.dirty&&!this.#B(e)&&!r||this.#D(e,s,n)}#B(e){const{instances:t}=e.batchRecord;for(let s=0;s<t.length;s++)if(e.visibleInstances[s]!==ue(t[s]))return e.dirty=!0,K(e.batchRecord.batch),!0;return!1}#O(e){return e?.getDrawingBufferSize?(e.getDrawingBufferSize(He),He.y):0}#A(e,t,s){return this.#M(t,s)?e.hasLastCameraState?!Ye(e.lastCameraMatrixWorldInverse,t.matrixWorldInverse)||!Ye(e.lastCameraProjectionMatrix,t.projectionMatrix)||Math.abs(e.lastViewportHeight-s)>U:!0:!1}#M(e,t){return this.#n&&e!==void 0&&(this.#o||this.#c>0&&t>0)}#_(e,t){if(!this.#M(e,t))return null;let s=null;return this.#o&&(ze.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),s=Ks.setFromProjectionMatrix(ze)),{camera:e,frustum:s,viewportHeight:t}}#L(e,t){return t?t.frustum&&!t.frustum.intersectsSphere(e)?!1:this.#c<=0||t.viewportHeight<=0?!0:this.#T(e,t.camera,t.viewportHeight)>=this.#c:!0}#T(e,t,s){const n=Math.abs(t.projectionMatrix.elements[5]);if(n<=U)return 1/0;if(t.isOrthographicCamera)return e.radius*n*s*.5;$e.copy(e.center).applyMatrix4(t.matrixWorldInverse);const r=-$e.z;return r<=U?1/0:e.radius*n*s*.5/r}#D(e,t,s=0){this.updateWorldMatrix(!0,!1),je.copy(this.matrixWorld).invert();const n=e.mesh.instanceMatrix.array,r=e.colorAttribute.array,a=e.opacityAttribute.array,c=e.mesh.geometry;let l=!1,h=!1,d=!1,u=0,p=0,f=!1;const S=e.mesh.count,C=this.#_(t,s);c.boundingSphere||c.computeBoundingSphere(),e.fullBoundingSphere.makeEmpty(),e.renderedInstances.length=0,e.batchRecord.instances.forEach((w,x)=>{const b=ue(w);e.visibleInstances[x]=b,w.updateWorldMatrix(!0,!1),re.multiplyMatrices(je,w.matrixWorld).multiply(e.localMatrix);const y=w.getInstanceOpacity();if(!(b&&y>U)||(p++,c.boundingSphere&&(We.copy(c.boundingSphere).applyMatrix4(re),e.fullBoundingSphere.union(We),C&&(Ue.multiplyMatrices(w.matrixWorld,e.localMatrix),Ge.copy(c.boundingSphere).applyMatrix4(Ue),!this.#L(Ge,C)))))return;const M=u,I=M*16;Xs(re,n,I)||(e.mesh.setMatrixAt(M,re),l=!0),V.copy(w.getInstanceColor(V));const A=w.getInstanceColorMode(),v=M*4;Ys(V,A,r,v)||(e.colorAttribute.setXYZW(M,V.r,V.g,V.b,A),h=!0),y<wt&&(f=!0),Math.abs(y-a[M])>U&&(e.opacityAttribute.setX(M,y),d=!0),e.renderedInstances[M]=w,u++}),e.mesh.count=u,S!==u&&(l=!0,h=!0,d=!0,K(e.batchRecord.batch));const D=p>0;e.mesh.visible!==D&&(e.mesh.visible=D,K(e.batchRecord.batch)),e.mesh.frustumCulled!==!0&&(e.mesh.frustumCulled=!0,K(e.batchRecord.batch)),l&&(e.mesh.instanceMatrix.needsUpdate=!0),h&&(e.colorAttribute.needsUpdate=!0),d&&(e.opacityAttribute.needsUpdate=!0),e.mesh.boundingSphere===null&&(e.mesh.boundingSphere=new o.Sphere),e.mesh.boundingSphere.copy(e.fullBoundingSphere);const O=e.hasSourceTransparency||f;e.materials.forEach(w=>{w.transparent!==O&&(w.transparent=O,w.needsUpdate=!0,K(e.batchRecord.batch))}),t&&this.#M(t,s)?(e.lastCameraMatrixWorldInverse.copy(t.matrixWorldInverse),e.lastCameraProjectionMatrix.copy(t.projectionMatrix),e.lastViewportHeight=s,e.hasLastCameraState=!0):e.hasLastCameraState=!1,e.dirty=!1}}const xt="0.0.32";typeof window<"u"&&(window.__USPACE__={version:xt});exports.CSSRenderer=j.CSSRenderer;exports.CameraControls=j.CameraControls;exports.InteractionEvent=j.InteractionEvent;exports.InteractionManager=j.InteractionManager;exports.ObjectManager=j.ObjectManager;exports.RenderPipeline=j.RenderPipeline;exports.RoomEnvironment=j.RoomEnvironment;exports.Viewer=j.Viewer;exports.enableMeshBVHRaycast=j.enableMeshBVHRaycast;exports.getGeometryBoundsTree=j.getGeometryBoundsTree;Object.defineProperty(exports,"CSS2DObject",{enumerable:!0,get:()=>At.CSS2DObject});Object.defineProperty(exports,"CSS3DObject",{enumerable:!0,get:()=>et.CSS3DObject});Object.defineProperty(exports,"CSS3DSprite",{enumerable:!0,get:()=>et.CSS3DSprite});exports.AnnotationManager=Es;exports.BaseGroup=q;exports.BaseMesh=F;exports.BaseSprite=rt;exports.CircleMesh=is;exports.ClippingTool=xs;exports.EditableGeometryBatchLayer=Vs;exports.ExtrudeMesh=Se;exports.INSTANCE_COLOR_MODE_NONE=ye;exports.INSTANCE_COLOR_MODE_OVERRIDE=ae;exports.INSTANCE_COLOR_MODE_TINT=ft;exports.InstanceObject=_s;exports.LightManager=Tt;exports.MaterialEffects=H;exports.MeasureTool=Ss;exports.Model=G;exports.ModelDecodeWorkerClient=nt;exports.ModelDecodeWorkerUnavailableError=te;exports.ModelInstancedLayer=rn;exports.ModelLoaderManager=z;exports.ObjectUtils=W;exports.PlaneMesh=rs;exports.Poi=ns;exports.SBMLoader=me;exports.SBMXLoader=fe;exports.SceneManager=Lt;exports.Selection=_t;exports.ShapeMesh=xe;exports.SphereMesh=it;exports.TSLEffects=ps;exports.TextureLoaderManager=ts;exports.Topology=ss;exports.TubeMesh=ge;exports.Tween=pt;exports.isInstanceObject=Ls;exports.reinterpretType=fs;exports.reuseDecodedImageContent=st;exports.tweenAnimation=ws;exports.version=xt;
16
+ `,t.labelStyle)for(const h of Object.keys(t.labelStyle)){const d=t.labelStyle[h];d!==void 0&&(r.style[h]=d)}let a=null;const o=t.labelOffset||{x:0,y:2,z:0};if(t.showLeaderLine!==!1){const{lineColor:h=16777215}=t,d=new c.BufferGeometry().setFromPoints([new c.Vector3(0,0,0),new c.Vector3(o.x,o.y,o.z)]),p=new c.LineBasicMaterial({color:h});a=new c.Line(d,p),s.add(a)}if(this._createCSSObject){const h=this._createCSSObject(r);h.position.set(o.x,o.y,o.z),s.add(h)}this.scene.add(s);const l={id:e,options:t,group:s,labelElement:r,line:a};return this.annotations.set(e,l),l}addText(e,t,s={}){const n=`annotation_${this._idCounter++}`;return this.add(n,{position:t,content:e,...s})}updateContent(e,t){const s=this.annotations.get(e);s&&(s.labelElement.innerHTML=t,s.options.content=t)}updatePosition(e,t){const s=this.annotations.get(e);s&&(s.group.position.set(t.x,t.y,t.z),s.options.position=t)}show(e){const t=this.annotations.get(e);t&&(t.group.visible=!0)}hide(e){const t=this.annotations.get(e);t&&(t.group.visible=!1)}get(e){return this.annotations.get(e)}remove(e){const t=this.annotations.get(e);if(t){const s=[...t.group.children];for(const n of s)t.group.remove(n),n.geometry?.dispose(),n.material?.dispose();this.scene.remove(t.group),this.annotations.delete(e)}}removeAll(){const e=Array.from(this.annotations.keys());for(const t of e)this.remove(t)}showAll(){for(const e of this.annotations.values())e.group.visible=!0}hideAll(){for(const e of this.annotations.values())e.group.visible=!1}keys(){return Array.from(this.annotations.keys())}get size(){return this.annotations.size}dispose(){this.removeAll()}}const Re=new c.Matrix4,Rs=1e-6,Ds=1e-6,De="uSpaceInstanceOriginalMaterialState",be=0,oe=1,gt=2;function Ns(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Ps(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>Rs)return!1;return!0}function yt(i){const e=i.material;return Array.isArray(e)?e:[e]}function bt(i){const e=i.userData,t=e[De];if(t)return t;const s={transparent:i.transparent,opacity:i.opacity};return e[De]=s,s}function Us(i,e){i.traverse(t=>{const s=t;s.isMesh&&yt(s).forEach(n=>{if(!n)return;const r=n,a=bt(r),o=a.opacity*e;r.transparent=a.transparent||o<1,r.opacity=o,r.needsUpdate=!0})})}function ks(i){i.traverse(e=>{const t=e;t.isMesh&&yt(t).forEach(s=>{if(!s)return;const n=s,r=bt(n);n.transparent=r.transparent,n.opacity=r.opacity,n.needsUpdate=!0})})}class js extends Y{isInstanceObject=!0;type="InstanceObject";instanceId="";instanceKind="";instanceName="";geometry=new c.BufferGeometry;boundingBox=null;boundingSphere=null;#s={color:null,colorMode:be,opacity:1};#a=null;#t=null;#e=null;#r=null;#n=new Set;#o=new c.Matrix4;#c=!1;#l=!0;#d=!1;#u;constructor(e={}){super(),this.#u=e.boundsName??"InstanceBounds"}setInstanceIdentity(e){let t=!1;if(e.id!==void 0){const s=e.id??"";this.instanceId!==s&&(this.instanceId=s,t=!0)}if(e.kind!==void 0){const s=e.kind??"";this.instanceKind!==s&&(this.instanceKind=s,t=!0)}if(e.name!==void 0){const s=e.name??"";this.instanceName!==s&&(this.instanceName=s,t=!0)}return t&&this.markInstanceRenderDirty(),this}setInstanceBounds(e){if(e.isEmpty())return this;this.#t&&this.remove(this.#t);const t=new c.BufferGeometry;t.boundingBox=e.clone();const s=new c.Object3D;return s.name=this.#u,s.visible=!1,s.geometry=t,s.raycast=()=>{},this.#t=s,this.add(s),this.#h(),this.markInstanceRenderDirty(),this}setInstanceRenderObject(e){return this.#e&&this.#e!==e&&this.#e.parent===this&&this.remove(this.#e),this.#e=e,e&&e.parent!==this&&this.add(e),this.#f(),this.#h(),this.markInstanceRenderDirty(),this}getInstanceRenderObject(){return this.#e}setInstanceMaterializer(e){return this.#r=e,this}hasInstanceMaterializer(e){return this.#r===e}clearInstanceMaterializer(e){return(e===void 0||this.#r===e)&&(this.#r=null),this}materialize(){return this.#r?.()??this.#e??null}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new c.Box3),this.getInstanceBoundingBox(this.boundingBox,!1)}computeBoundingSphere(){if(this.boundingSphere===null&&(this.boundingSphere=new c.Sphere),this.boundingBox===null&&this.computeBoundingBox(),!this.boundingBox||this.boundingBox.isEmpty()){this.boundingSphere.makeEmpty();return}this.boundingBox.getBoundingSphere(this.boundingSphere)}getInstanceBoundingBox(e=new c.Box3,t=!1){const s=this.#t?.geometry?.boundingBox;return s?(e.copy(s),t&&(this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)),e):this.#e?(e.setFromObject(this.#e),t||(this.updateWorldMatrix(!0,!1),Re.copy(this.matrixWorld).invert(),e.applyMatrix4(Re)),e):e.makeEmpty()}setInstanceVisible(e){return this.visible===e?this:(this.visible=e,this.markInstanceRenderDirty(),this)}setInstanceColor(e){return this.#s.color=new c.Color(e),this.#s.colorMode=oe,this.#f(),this.markInstanceRenderDirty(),this}resetInstanceColor(){return this.#s.color===null?this:(this.#s.color=null,this.#s.colorMode=be,this.#f(),this.markInstanceRenderDirty(),this)}setInstanceOpacity(e){const t=Math.max(0,Math.min(1,e));return Math.abs(this.#s.opacity-t)<=Ds?this:(this.#s.opacity=t,this.#f(),this.markInstanceRenderDirty(),this)}getInstanceColor(e=new c.Color){const t=this.#p();return t.color?e.copy(t.color):e.setRGB(1,1,1)}hasInstanceColor(){return this.#p().color!==null}getInstanceOpacity(){return this.#p().opacity}setInstanceHighlight(e,t,s=!1){return this.#a={color:new c.Color(e),colorMode:s?oe:gt,opacity:Math.max(0,Math.min(1,t))},this.#f(),this.markInstanceRenderDirty(),this}clearInstanceHighlight(){return this.#a===null?this:(this.#a=null,this.#f(),this.markInstanceRenderDirty(),this)}getInstanceColorMode(){return this.#p().colorMode}onInstanceRenderDirty(e){return this.#n.add(e),()=>this.#n.delete(e)}markInstanceRenderDirty(){return this.#n.forEach(e=>e()),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this.#i()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.#i()}#i(){const e=Ns(this);(!this.#c||!Ps(this.matrixWorld,this.#o)||!this.#d||e!==this.#l)&&(this.#c=!0,this.#d=!0,this.#o.copy(this.matrixWorld),this.#l=e,this.markInstanceRenderDirty())}#h(){this.boundingBox=null,this.boundingSphere=null}#p(){return this.#a??this.#s}#f(){if(!this.#e)return;const e=this.#p();if(e.color){ks(this.#e),$.highlightColor(this.#e,{color:e.color,opacity:e.opacity,overwrite:e.colorMode===oe,multiplyOpacity:!0});return}$.removeHighlightColor(this.#e),Us(this.#e,e.opacity)}}function zs(i){return i.isInstanceObject===!0}const Fs=new Set(["MeshBasicMaterial","MeshLambertMaterial","MeshPhongMaterial","MeshStandardMaterial","MeshPhysicalMaterial"]),Ne=new WeakMap;let Ws=1;const Pe=new c.Matrix4,te=new c.Matrix4,Ue=new c.Matrix4;function Gs(i,e,t=1e-6){const s=i.elements,n=e.elements;for(let r=0;r<16;r++)if(Math.abs(s[r]-n[r])>t)return!1;return!0}function wt(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function Hs(i){const e=i.source.data;if(!e||typeof e!="object"&&typeof e!="function")return`texture:${i.uuid}`;let t=Ne.get(e);return t===void 0&&(t=Ws++,Ne.set(e,t)),`source:${t}`}function $s(i){return JSON.stringify([Hs(i),i.mapping,i.channel,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.anisotropy,i.format,i.internalFormat,i.type,i.offset.toArray(),i.repeat.toArray(),i.center.toArray(),i.rotation,i.matrixAutoUpdate,i.matrix.toArray(),i.generateMipmaps,i.premultiplyAlpha,i.flipY,i.unpackAlignment,i.colorSpace,"compareFunction"in i?i.compareFunction:null])}function we(i){if(Array.isArray(i))return i.map(we);if(!i||typeof i!="object")return i;const e=i;return Object.fromEntries(Object.keys(e).sort().map(t=>[t,we(e[t])]))}function Me(i,e){if(Array.isArray(i))return i.map(s=>Me(s,e));if(!i||typeof i!="object")return typeof i=="string"?e.get(i)??i:i;const t=i;return Object.fromEntries(Object.keys(t).filter(s=>s!=="metadata"&&s!=="uuid"&&s!=="name").sort().map(s=>[s,Me(t[s],e)]))}function Vs(i){if(!Fs.has(i.type)||i.transparent||i.opacity<.999||i.visible===!1)return null;const e=i;if(Object.keys(e).some(r=>r.endsWith("Node")&&e[r]!=null)||Object.hasOwn(i,"onBeforeCompile"))return null;const t=new Map;Object.values(e).forEach(r=>{r instanceof c.Texture&&t.set(r.uuid,$s(r))});const s={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n=i.toJSON(s);return JSON.stringify(we(Me(n,t)))}function Ks(i){if(Object.keys(i.morphAttributes).length>0||i.drawRange.start!==0||i.drawRange.count!==1/0)return null;const e=Object.entries(i.attributes).sort(([t],[s])=>t.localeCompare(s)).map(([t,s])=>"isInterleavedBufferAttribute"in s?null:[t,s.itemSize,s.normalized,s.array.constructor.name,s.gpuType]);return e.some(t=>t===null)?null:JSON.stringify([i.index?.array.constructor.name??"non-indexed",e])}function qs(i,e){const t=[],s=new Set,n=new Set,r=!e&&(i.animations.length>0||i.mixer!==null);return r&&n.add("animation"),i.updateWorldMatrix(!0,!0),Pe.copy(i.matrixWorld).invert(),i.traverseVisible(a=>{if(!(a instanceof c.Mesh))return;if(r){s.add(a);return}if(a instanceof c.SkinnedMesh){s.add(a),n.add("skinned");return}if(a.morphTargetInfluences){s.add(a),n.add("morph");return}if(Array.isArray(a.material)){s.add(a),n.add("material-array");return}const o=Vs(a.material),l=Ks(a.geometry);if(!o){s.add(a),n.add(a.material.transparent||a.material.opacity<.999?"transparent":`material:${a.material.type}`);return}if(!l){s.add(a),n.add("geometry-layout");return}if(a.matrixWorld.determinant()<=0){s.add(a),n.add("negative-scale");return}t.push({mesh:a,localMatrix:Pe.clone().multiply(a.matrixWorld),materialKey:o,geometryKey:l})}),t.length===0&&s.size===0&&n.add("empty"),{meshes:t,fallbackMeshes:s,fallbackReasons:n}}function Xs(i,e){const t=xe.clone(i),s=[],n=[];return i.traverse(r=>{r instanceof c.Mesh&&s.push(r)}),t.traverse(r=>{r instanceof c.Mesh&&n.push(r)}),s.forEach((r,a)=>{e.has(r)&&n[a]&&(n[a].visible=!1)}),t}function Ys(i){const e=xe.clone(i),t=new Map,s=n=>{let r=t.get(n);return r||(r=n.clone(),t.set(n,r)),r};return e.traverse(n=>{n instanceof c.Mesh&&(n.material=Array.isArray(n.material)?n.material.map(s):s(n.material))}),e}function Qs(i){return Math.max(1,Math.ceil(Math.sqrt(Math.max(1,i))))}function Js(i){const e=new c.DataTexture(new Float32Array(i*i*4),i,i,c.RGBAFormat,c.FloatType);return e.magFilter=c.NearestFilter,e.minFilter=c.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e}function Zs(i,e){const t=i.clone(),s=b.attribute("batchObjectIndex","float").toInt(),n=b.int(b.textureSize(b.textureLoad(e),b.int(0)).x).toConst(),r=s.mod(n).toConst(),a=s.div(n).toConst(),o=b.textureLoad(e,b.ivec2(r,a)),l=t.colorNode??b.materialColor,h=b.select(o.a.greaterThan(1.5),l.mul(o.rgb),o.rgb);return t.colorNode=b.select(o.a.greaterThan(.5),h,l),t.maskNode=o.a.greaterThan(-.5),t.needsUpdate=!0,t}function ke(i){let e=0,t=i.parent;for(;t;)e++,t=t.parent;return e}class en extends G{objectIndices;states;#s;constructor(e,t,s,n){super(e,t),this.objectIndices=s,this.states=n,this.userData.editableGeometryBatch=!0}raycast(e,t){if(this.visible===!1&&this.ignoreInvisibleWhenRaycast===!0)return!1;this.#s===void 0&&(this.#s=z.getGeometryBoundsTree(this.geometry));const s=[];this.#s?this.#s.raycastObject3D(this,e,s):super.raycast(e,s),s.forEach(n=>{const r=n.faceIndex;if(r==null)return;const a=r*3,o=this.geometry.index?.getX(a)??a,l=this.objectIndices[o],h=l===void 0?void 0:this.states[l],d=h?.instance;!h||h.materialized||!d||!wt(d)||d.getInstanceOpacity()<=.001||(n.object=d,n.batchObjectIndex=l,t.push(n))})}}class tn extends Y{isEditableGeometryBatchLayer=!0;type="EditableGeometryBatchLayer";options;stats={instances:0,sourceMeshes:0,batches:0,drawCallsSaved:0,vertices:0,indices:0,unsupportedInstances:0,unsupportedByReason:{}};#s=[];#a=new Set;#t=[];#e=new Map;#r=new Set;#n=null;#o=new c.Matrix4;#c=!1;#l=!1;#d=!1;constructor(e={}){super(),this.name="EditableGeometryBatches",this.options={maxVerticesPerBatch:e.maxVerticesPerBatch??15e5,maxIndicesPerBatch:e.maxIndicesPerBatch??45e5,freezeAnimations:e.freezeAnimations??!1}}addSource(e){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer has already been built.");const{key:t,template:s,instances:n}=e,r=new Set;n.forEach(h=>{if(r.has(h)||this.#a.has(h))throw new Error("EditableGeometryBatchLayer cannot batch the same InstanceObject more than once.");r.add(h)});const{meshes:a,fallbackMeshes:o,fallbackReasons:l}=qs(s,this.options.freezeAnimations);return r.forEach(h=>this.#a.add(h)),this.#s.push({key:t,template:s,instances:[...n],meshes:a,fallbackMeshes:o,fallbackReasons:l,bounds:new c.Box3().setFromObject(s)}),a.length>0}build(){if(this.#l)throw new Error("EditableGeometryBatchLayer has been disposed.");if(this.#c)throw new Error("EditableGeometryBatchLayer.build() can only be called once.");this.#c=!0,this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=[],t=new Map,s=(r,a,o,l)=>{if(o.length===0)return;const h=l.size>0?[...l]:["unknown"];e.push({key:r.key,template:a,instances:o,reasons:h}),h.forEach(d=>{this.stats.unsupportedByReason[d]=(this.stats.unsupportedByReason[d]??0)+o.length})};this.#s.forEach(r=>{const a=[],o=[];r.instances.forEach(h=>{h.updateWorldMatrix(!0,!1),te.multiplyMatrices(this.#o,h.matrixWorld),te.determinant()<=0?o.push(h):a.push({instance:h,matrix:te.clone()})});const l=r.fallbackReasons.size>0?r.fallbackReasons:new Set(["unknown"]);if(r.meshes.length===0){s(r,r.template,a.map(({instance:h})=>h),l),s(r,r.template,o,new Set([...l,"negative-scale"]));return}r.fallbackMeshes.size>0&&s(r,Xs(r.template,new Set(r.meshes.map(({mesh:h})=>h))),a.map(({instance:h})=>h),l),s(r,r.template,o,new Set([...r.fallbackReasons,"negative-scale"])),a.forEach(({instance:h,matrix:d})=>{const p=this.#t.length,u=()=>this.materialize(h),f={instance:h,template:r.template,initialMatrix:d,objectIndex:p,materialized:!1,materializer:u,unsubscribe:()=>{}};f.unsubscribe=h.onInstanceRenderDirty(()=>this.#h(f)),this.#t.push(f),this.#e.set(h,f),h.setInstanceBounds(r.bounds),h.setInstanceMaterializer(u),this.#r.add(f),r.meshes.forEach(({mesh:M,localMatrix:C,materialKey:A,geometryKey:O})=>{Ue.multiplyMatrices(d,C);const S=M.geometry.clone().applyMatrix4(Ue),y=S.getAttribute("position");S.setAttribute("batchObjectIndex",new c.Float32BufferAttribute(new Float32Array(y.count).fill(p),1));const x=JSON.stringify([A,O,M.castShadow,M.receiveShadow,M.renderOrder]),m=t.get(x),E={geometry:S,material:M.material,castShadow:M.castShadow,receiveShadow:M.receiveShadow,renderOrder:M.renderOrder,objectIndices:new Array(y.count).fill(p)};m?m.push(E):t.set(x,[E]),this.stats.sourceMeshes++,this.stats.vertices+=y.count,this.stats.indices+=S.index?.count??y.count})})}),this.stats.instances=this.#t.length,this.stats.unsupportedInstances=e.reduce((r,a)=>r+a.instances.length,0);const n=Qs(this.#t.length);return this.#n=Js(n),this.#i(),t.forEach(r=>this.#u(r)),this.stats.batches=this.children.length,this.stats.drawCallsSaved=Math.max(0,this.stats.sourceMeshes-this.stats.batches),this.children.forEach(r=>{r instanceof c.Mesh&&(r.onBeforeRender=()=>this.#i())}),{stats:{...this.stats},unsupported:e}}materialize(e){const t=this.#e.get(e);if(!t||t.materialized)return e.getInstanceRenderObject();const s=Ys(t.template);return s.position.set(0,0,0),s.quaternion.identity(),s.scale.set(1,1,1),s.matrix.identity(),t.materialized=!0,e.setInstanceRenderObject(s),s.updateWorldMatrix(!0,!0),this.#r.add(t),this.dispatchEvent({type:"materialize",instance:e,object:s}),s}#u(e){const t=[];let s=[],n=0,r=0;e.forEach(a=>{const o=a.geometry.getAttribute("position").count,l=a.geometry.index?.count??o;s.length>0&&(n+o>this.options.maxVerticesPerBatch||r+l>this.options.maxIndicesPerBatch)&&(t.push(s),s=[],n=0,r=0),s.push(a),n+=o,r+=l}),s.length>0&&t.push(s),t.forEach(a=>{const o=At.mergeGeometries(a.map(u=>u.geometry),!1);if(a.forEach(u=>u.geometry.dispose()),!o||!this.#n)return;o.computeBoundingBox(),o.computeBoundingSphere();const l=a[0],h=a.flatMap(u=>u.objectIndices),d=Zs(l.material,this.#n),p=new en(o,d,h,this.#t);p.name=`EditableGeometryBatch:${this.children.length}`,p.castShadow=l.castShadow,p.receiveShadow=l.receiveShadow,p.renderOrder=l.renderOrder,p.matrixAutoUpdate=!1,this.add(p)})}#i(){if(!(!this.#n||this.#r.size===0||this.#d)){this.#d=!0;try{this.updateWorldMatrix(!0,!1),this.#o.copy(this.matrixWorld).invert();const e=this.#n.image.data;[...this.#r].sort((t,s)=>ke(t.instance)-ke(s.instance)).forEach(t=>{const{instance:s,objectIndex:n}=t;s.updateWorldMatrix(!0,!1),te.multiplyMatrices(this.#o,s.matrixWorld),!t.materialized&&s.getInstanceRenderObject()!==null&&!s.hasInstanceMaterializer(t.materializer)&&(t.materialized=!0),!t.materialized&&!Gs(te,t.initialMatrix)&&this.materialize(s),!t.materialized&&s.getInstanceOpacity()<.999&&this.materialize(s);const r=n*4,a=!t.materialized&&wt(s)&&s.getInstanceOpacity()>.001,o=s.getInstanceColor();e[r]=o.r,e[r+1]=o.g,e[r+2]=o.b,e[r+3]=a?s.getInstanceColorMode():-1,this.#r.delete(t)}),this.#n.needsUpdate=!0}finally{this.#d=!1}this.#r.size>0&&this.#i()}}#h(e){this.#r.add(e),this.#i()}dispose(){this.#l||(this.#l=!0,this.#t.forEach(e=>{e.unsubscribe(),e.instance.clearInstanceMaterializer(e.materializer)}),this.#t.length=0,this.#e.clear(),this.#a.clear(),this.#r.clear(),this.#s.length=0,this.#n?.dispose(),this.#n=null,this.traverse(e=>{if(!(e instanceof c.Mesh))return;e.geometry.dispose(),(Array.isArray(e.material)?e.material:[e.material]).forEach(s=>s.dispose())}),this.clear())}}const je=new c.Matrix4,ie=new c.Matrix4,ze=new c.Matrix4,Fe=new c.Matrix4,We=new c.Box3,Ge=new c.Sphere,He=new c.Sphere,sn=new c.Frustum,q=new c.Color,$e=new c.Vector2,Ve=new c.Vector3,Ke=new c.Matrix4,qe=new c.Matrix4,Xe=new c.Sphere,ae=[],Mt=1e-6,F=1e-6,xt=.999,nn=0,Ye=1;function rn(i,e,t){const s=i.elements;for(let n=0;n<16;n++)if(Math.abs(s[n]-e[t+n])>Mt)return!1;return!0}function an(i,e,t,s){return Math.abs(i.r-t[s])<=F&&Math.abs(i.g-t[s+1])<=F&&Math.abs(i.b-t[s+2])<=F&&Math.abs(e-t[s+3])<=F}function Qe(i,e){const t=i.elements,s=e.elements;for(let n=0;n<16;n++)if(Math.abs(t[n]-s[n])>Mt)return!1;return!0}function pe(i){let e=i;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function on(i){const e=i.geometry.morphAttributes;return Object.values(e).some(t=>t?.length)}function cn(i){const e=i.material;if(!Array.isArray(e))return!0;if(e.length===0||!e.every(Boolean))return!1;const t=i.geometry.groups;return t.length===0?!1:t.every(s=>{const n=s.materialIndex??0;return Number.isInteger(s.start)&&s.start>=0&&Number.isInteger(s.count)&&s.count>0&&Number.isInteger(n)&&n>=0&&n<e.length})}function ln(i){return!i.isSkinnedMesh&&!on(i)&&cn(i)}function Je(i){return Array.isArray(i)?i:[i]}function St(i){return i.transparent||i.opacity<xt}function Ze(i,e,t){const s=i.clone(),n=b.instancedBufferAttribute(e,"vec4",4,0),r=b.instancedBufferAttribute(t,"float",1,0),a=s.colorNode??b.materialColor,o=s.opacityNode?b.float(s.opacityNode):b.materialOpacity,l=b.select(n.a.greaterThan(1.5),a.mul(n.rgb),n.rgb);return s.colorNode=b.select(n.a.greaterThan(.5),l,a),s.opacityNode=o.mul(r),s.transparent=St(i),s.needsUpdate=!0,s}function hn(i,e,t){return Array.isArray(i)?i.map(s=>Ze(s,e,t)):Ze(i,e,t)}function dn(i){const e=[],t=new c.Matrix4;let s=!1;return i.updateWorldMatrix(!0,!0),t.copy(i.matrixWorld).invert(),i.traverse(n=>{if(!s&&!(!(n instanceof c.Mesh)||!n.visible)){if(!ln(n)){s=!0;return}n.updateWorldMatrix(!0,!1),e.push({mesh:n,localMatrix:t.clone().multiply(n.matrixWorld)})}}),s?[]:e}function un(i){const e=new c.Box3;return i.forEach(({mesh:t,localMatrix:s})=>{const n=t.geometry;n.boundingBox||n.computeBoundingBox(),n.boundingBox&&(We.copy(n.boundingBox).applyMatrix4(s),e.union(We))}),e}function X(i){const e=i;"needsUpdate"in e&&(e.needsUpdate=!0)}function et(i,e=Ye){let t=Math.max(Ye,e);for(;t<i;)t*=2;return t}function pn(i){return i!==null&&typeof i=="object"&&Symbol.iterator in i}class fn extends Y{isModelInstancedLayer=!0;type="ModelInstancedLayer";#s=[];#a=new Map;#t=new Map;#e=new Map;#r=!0;#n=!1;#o=!0;#c=nn;#l;#d;constructor(e={}){super(),this.name=e.name??"ModelInstances",this.#l=e.instanceKind??"",this.#d=e.getHitUserData??(()=>({}))}get instanceKind(){return this.#l}getInstances(){const e=[];return this.#i(t=>e.push(t)),e}getInstanceById(e){return this.#w(),this.#e.get(e)}hasInstance(e){return this.#w(),this.#e.has(e)}getInstanceCulling(){return{enabled:this.#n,frustum:this.#o,minScreenRadius:this.#c}}setInstanceCulling(e={}){let t=!1;if(e.enabled!==void 0&&this.#n!==e.enabled&&(this.#n=e.enabled,t=!0),e.frustum!==void 0&&this.#o!==e.frustum&&(this.#o=e.frustum,t=!0),e.minScreenRadius!==void 0){const s=Math.max(0,e.minScreenRadius);Math.abs(this.#c-s)>F&&(this.#c=s,t=!0)}return t&&this.#s.forEach(s=>this.#v(s)),this}setInstanceVisible(e){return this.visible!==e&&(this.visible=e),this.#i(t=>{t.setInstanceVisible(e)}),this}setInstanceColor(e){return this.#i(t=>{t.setInstanceColor(e)}),this}resetInstanceColor(){return this.#i(e=>{e.resetInstanceColor()}),this}setInstanceOpacity(e){return this.#i(t=>{t.setInstanceOpacity(e)}),this}setInstanceHighlight(e,t,s=!1){return this.#i(n=>{n.setInstanceHighlight(e,t,s)}),this}clearInstanceHighlight(){return this.#i(e=>{e.clearInstanceHighlight()}),this}reserveBatch(e,t,s){const n=Math.floor(s);return n<=0?!1:this.#u(e,t,n)!==null}addInstance(e,t,s){return this.addInstances(e,t,[s])}addInstances(e,t,s){if(s.length===0)return!1;const n=this.#a.has(e),r=this.#u(e,t,s.length);if(!r)return!1;const a=[],o=new Set;return s.forEach(l=>{o.has(l)||(o.add(l),this.#t.get(l)===r)||a.push(l)}),a.length===0?!0:this.#I(a)?(a.forEach(l=>{const h=this.#t.get(l);h&&h!==r&&this.#S(h,l)}),this.#x(r,r.instances.length+a.length),a.forEach(l=>{l.setInstanceBounds(r.templateBounds),r.instances.push(l),this.#t.set(l,r),r.unsubscribeByInstance.set(l,l.onInstanceRenderDirty(()=>{this.#g(),this.#y(r)}))}),this.#g(),this.#b(r),this.#y(r),!0):(!n&&r.instances.length===0&&this.#m(r),!1)}removeInstance(e){return this.removeInstances([e])>0}removeInstances(e){const t=new Set,s=new Set,n=typeof e=="string"||!pn(e)?[e]:e;for(const a of n)typeof a=="string"?t.add(a):this.#t.has(a)&&s.add(a);t.size>0&&(this.#w(),t.forEach(a=>{const o=this.#e.get(a);o&&s.add(o)}));let r=0;return s.forEach(a=>{const o=this.#t.get(a);o&&this.#S(o,a)&&r++}),r}removeBatch(e){const t=this.#a.get(e);return t?(this.#m(t),!0):!1}clearBatches(){return[...this.#a.values()].forEach(e=>this.#m(e)),this}#u(e,t,s){const n=this.#a.get(e);if(n)return this.#x(n,s),n;if(t.animations?.length)return null;const r=dn(t);if(r.length===0)return null;const a=un(r),o=new c.Group;o.name=e,this.add(o);const l={url:e,batch:o,templateMeshes:r,templateBounds:a,records:[],instances:[],unsubscribeByInstance:new Map,capacity:et(s)};return r.forEach(({mesh:h,localMatrix:d},p)=>{const u=this.#h(l,h,d,p);l.records.push(u),this.#s.push(u)}),this.#a.set(e,l),this.#b(l),l}#i(e){const t=new Set;this.#a.forEach(s=>{s.instances.forEach(n=>{t.has(n)||(t.add(n),e(n))})})}#h(e,t,s,n){const r=new c.InstancedBufferAttribute(new Float32Array(e.capacity*4),4),a=new c.InstancedBufferAttribute(new Float32Array(e.capacity).fill(1),1);r.setUsage(c.DynamicDrawUsage),a.setUsage(c.DynamicDrawUsage);const o=hn(t.material,r,a),l=Je(o),h=Je(t.material).some(St),d=new c.InstancedMesh(t.geometry,o,e.capacity);d.instanceMatrix=new c.StorageInstancedBufferAttribute(e.capacity,16),d.count=0,d.name=t.name||`${e.url}#${n}`,d.castShadow=t.castShadow,d.receiveShadow=t.receiveShadow,d.frustumCulled=!0,d.matrixAutoUpdate=!1,d.instanceMatrix.setUsage(c.DynamicDrawUsage),d.userData.url=e.url;const p=new c.Mesh(t.geometry,o);p.matrixAutoUpdate=!1;const u={batchRecord:e,mesh:d,boundsTree:void 0,raycastMesh:p,localMatrix:s.clone(),fullBoundingSphere:new c.Sphere,materials:l,hasSourceTransparency:h,colorAttribute:r,opacityAttribute:a,renderedInstances:[],visibleInstances:[],lastCameraMatrixWorldInverse:new c.Matrix4,lastCameraProjectionMatrix:new c.Matrix4,lastViewportHeight:0,hasLastCameraState:!1,dirty:!0};d.userData.getInstanceObjectByRenderIndex=M=>u.renderedInstances[M],d.userData.raycastAcceleration="lazy";const f=d.raycast.bind(d);return d.raycast=(M,C)=>{if(this.#C(u),!this.#p(u,M))return;u.boundsTree===void 0&&(u.boundsTree=z.getGeometryBoundsTree(u.mesh.geometry),u.mesh.userData.raycastAcceleration=u.boundsTree?"three-mesh-bvh":"default");const A=C.length;u.boundsTree?this.#f(u,M,C):f(M,C);for(let O=A;O<C.length;){const S=C[O],y=S.instanceId;if(y===void 0){O++;continue}const x=u.renderedInstances[y];if(!x||!pe(x)){C.splice(O,1);continue}S.object=x,S.instanceObject=x,S.instanceObjectId=x.instanceId,S.instanceKind=x.instanceKind||this.#l,S.instanceName=x.instanceName,S.instanceIndex=y,Object.assign(S,this.#d(x,y)),O++}},d.onBeforeRender=(M,C,A)=>this.#C(u,M,A),e.batch.add(d),u}#p(e,t){const{mesh:s}=e;return s.count===0?!1:(s.boundingSphere===null&&s.computeBoundingSphere(),s.boundingSphere?(Xe.copy(s.boundingSphere).applyMatrix4(s.matrixWorld),t.ray.intersectsSphere(Xe)):!0)}#f(e,t,s){const{mesh:n,boundsTree:r,raycastMesh:a}=e;if(!(!r||n.count===0)){a.geometry=n.geometry,a.material=n.material;for(let o=0;o<n.count;o++)n.getMatrixAt(o,Ke),qe.multiplyMatrices(n.matrixWorld,Ke),a.matrixWorld.copy(qe),ae.length=0,r.raycastObject3D(a,t,ae),ae.forEach(l=>{l.instanceId=o,l.object=n,s.push(l)}),ae.length=0}}#x(e,t){if(t<=e.capacity)return;e.capacity=et(t,e.capacity);const s=new Set(e.records);s.forEach(n=>this.#E(n)),this.#s=this.#s.filter(n=>!s.has(n)),e.records=e.templateMeshes.map(({mesh:n,localMatrix:r},a)=>{const o=this.#h(e,n,r,a);return this.#s.push(o),o}),this.#y(e)}#S(e,t){const s=e.instances.indexOf(t);return s===-1?!1:(e.instances.splice(s,1),e.records.forEach(n=>n.visibleInstances.splice(s,1)),this.#t.delete(t),this.#g(),e.unsubscribeByInstance.get(t)?.(),e.unsubscribeByInstance.delete(t),e.instances.length===0?(this.#m(e),!0):(this.#b(e),this.#y(e),!0))}#m(e){e.unsubscribeByInstance.forEach(s=>s()),e.instances.forEach(s=>this.#t.delete(s)),e.unsubscribeByInstance.clear(),e.instances.length=0,this.#g();const t=new Set(e.records);t.forEach(s=>this.#E(s)),this.#s=this.#s.filter(s=>!t.has(s)),e.records.length=0,e.templateMeshes.length=0,this.#a.delete(e.url),this.remove(e.batch)}#E(e){e.batchRecord.batch.remove(e.mesh),e.mesh.dispose(),e.materials.forEach(t=>t.dispose())}#b(e){Object.assign(e.batch.userData,{url:e.url,count:e.instances.length,capacity:e.capacity,instanceKind:this.#l}),delete e.batch.userData.sceneInstances,delete e.batch.userData.facilities,e.records.forEach(t=>{delete t.mesh.userData.instances})}#I(e){const t=new Set(e),s=new Map;for(const r of e){const{instanceId:a}=r;if(!a)continue;const o=s.get(a);if(o&&o!==r)return!1;s.set(a,r)}let n=!0;return s.forEach((r,a)=>{n&&this.#i(o=>{!n||t.has(o)||o.instanceId===a&&(n=!1)})}),n}#w(){if(!this.#r)return;this.#e.clear();const e=new Set;this.#i(t=>{const{instanceId:s}=t;if(!s||e.has(s))return;const n=this.#e.get(s);if(n&&n!==t){this.#e.delete(s),e.add(s);return}this.#e.set(s,t)}),this.#r=!1}#g(){this.#r=!0}#y(e){e.records.forEach(t=>this.#v(t))}#v(e){e.dirty=!0,e.hasLastCameraState=!1,e.mesh.visible=!0,e.mesh.frustumCulled=!1,X(e.batchRecord.batch)}#C(e,t,s){const n=this.#B(t),r=this.#L(e,s,n);!e.dirty&&!this.#O(e)&&!r||this.#R(e,s,n)}#O(e){const{instances:t}=e.batchRecord;for(let s=0;s<t.length;s++)if(e.visibleInstances[s]!==pe(t[s]))return e.dirty=!0,X(e.batchRecord.batch),!0;return!1}#B(e){return e?.getDrawingBufferSize?(e.getDrawingBufferSize($e),$e.y):0}#L(e,t,s){return this.#M(t,s)?e.hasLastCameraState?!Qe(e.lastCameraMatrixWorldInverse,t.matrixWorldInverse)||!Qe(e.lastCameraProjectionMatrix,t.projectionMatrix)||Math.abs(e.lastViewportHeight-s)>F:!0:!1}#M(e,t){return this.#n&&e!==void 0&&(this.#o||this.#c>0&&t>0)}#A(e,t){if(!this.#M(e,t))return null;let s=null;return this.#o&&(Fe.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),s=sn.setFromProjectionMatrix(Fe)),{camera:e,frustum:s,viewportHeight:t}}#_(e,t){return t?t.frustum&&!t.frustum.intersectsSphere(e)?!1:this.#c<=0||t.viewportHeight<=0?!0:this.#T(e,t.camera,t.viewportHeight)>=this.#c:!0}#T(e,t,s){const n=Math.abs(t.projectionMatrix.elements[5]);if(n<=F)return 1/0;if(t.isOrthographicCamera)return e.radius*n*s*.5;Ve.copy(e.center).applyMatrix4(t.matrixWorldInverse);const r=-Ve.z;return r<=F?1/0:e.radius*n*s*.5/r}#R(e,t,s=0){this.updateWorldMatrix(!0,!1),je.copy(this.matrixWorld).invert();const n=e.mesh.instanceMatrix.array,r=e.colorAttribute.array,a=e.opacityAttribute.array,o=e.mesh.geometry;let l=!1,h=!1,d=!1,p=0,u=0,f=!1;const M=e.mesh.count,C=this.#A(t,s);o.boundingSphere||o.computeBoundingSphere(),e.fullBoundingSphere.makeEmpty(),e.renderedInstances.length=0,e.batchRecord.instances.forEach((S,y)=>{const x=pe(S);e.visibleInstances[y]=x,S.updateWorldMatrix(!0,!1),ie.multiplyMatrices(je,S.matrixWorld).multiply(e.localMatrix);const m=S.getInstanceOpacity();if(!(x&&m>F)||(u++,o.boundingSphere&&(Ge.copy(o.boundingSphere).applyMatrix4(ie),e.fullBoundingSphere.union(Ge),C&&(ze.multiplyMatrices(S.matrixWorld,e.localMatrix),He.copy(o.boundingSphere).applyMatrix4(ze),!this.#_(He,C)))))return;const w=p,v=w*16;rn(ie,n,v)||(e.mesh.setMatrixAt(w,ie),l=!0),q.copy(S.getInstanceColor(q));const B=S.getInstanceColorMode(),I=w*4;an(q,B,r,I)||(e.colorAttribute.setXYZW(w,q.r,q.g,q.b,B),h=!0),m<xt&&(f=!0),Math.abs(m-a[w])>F&&(e.opacityAttribute.setX(w,m),d=!0),e.renderedInstances[w]=S,p++}),e.mesh.count=p,M!==p&&(l=!0,h=!0,d=!0,X(e.batchRecord.batch));const A=u>0;e.mesh.visible!==A&&(e.mesh.visible=A,X(e.batchRecord.batch)),e.mesh.frustumCulled!==!0&&(e.mesh.frustumCulled=!0,X(e.batchRecord.batch)),l&&(e.mesh.instanceMatrix.needsUpdate=!0),h&&(e.colorAttribute.needsUpdate=!0),d&&(e.opacityAttribute.needsUpdate=!0),e.mesh.boundingSphere===null&&(e.mesh.boundingSphere=new c.Sphere),e.mesh.boundingSphere.copy(e.fullBoundingSphere);const O=e.hasSourceTransparency||f;e.materials.forEach(S=>{S.transparent!==O&&(S.transparent=O,S.needsUpdate=!0,X(e.batchRecord.batch))}),t&&this.#M(t,s)?(e.lastCameraMatrixWorldInverse.copy(t.matrixWorldInverse),e.lastCameraProjectionMatrix.copy(t.projectionMatrix),e.lastViewportHeight=s,e.hasLastCameraState=!0):e.hasLastCameraState=!1,e.dirty=!1}}const Et="0.0.33";typeof window<"u"&&(window.__USPACE__={version:Et});exports.CSSRenderer=z.CSSRenderer;exports.CameraControls=z.CameraControls;exports.InteractionEvent=z.InteractionEvent;exports.InteractionManager=z.InteractionManager;exports.ObjectManager=z.ObjectManager;exports.RenderPipeline=z.RenderPipeline;exports.RoomEnvironment=z.RoomEnvironment;exports.Viewer=z.Viewer;exports.enableMeshBVHRaycast=z.enableMeshBVHRaycast;exports.getGeometryBoundsTree=z.getGeometryBoundsTree;Object.defineProperty(exports,"CSS2DObject",{enumerable:!0,get:()=>_t.CSS2DObject});Object.defineProperty(exports,"CSS3DObject",{enumerable:!0,get:()=>tt.CSS3DObject});Object.defineProperty(exports,"CSS3DSprite",{enumerable:!0,get:()=>tt.CSS3DSprite});exports.AnnotationManager=Ts;exports.BaseGroup=Y;exports.BaseMesh=G;exports.BaseSprite=at;exports.CircleMesh=fs;exports.ClippingTool=As;exports.EditableGeometryBatchLayer=tn;exports.ExtrudeMesh=Ee;exports.INSTANCE_COLOR_MODE_NONE=be;exports.INSTANCE_COLOR_MODE_OVERRIDE=oe;exports.INSTANCE_COLOR_MODE_TINT=gt;exports.InstanceObject=js;exports.LightManager=Dt;exports.MaterialEffects=$;exports.MeasureTool=_s;exports.Model=k;exports.ModelDecodeWorkerClient=rt;exports.ModelDecodeWorkerUnavailableError=se;exports.ModelInstancedLayer=fn;exports.ModelLoaderManager=W;exports.ObjectUtils=H;exports.PlaneMesh=ps;exports.Poi=us;exports.SBMLoader=ge;exports.SBMXLoader=me;exports.SceneManager=Rt;exports.Selection=Tt;exports.ShapeMesh=Se;exports.SphereMesh=ot;exports.TSLEffects=Ss;exports.TextureLoaderManager=hs;exports.Topology=ds;exports.TubeMesh=ye;exports.Tween=mt;exports.isInstanceObject=zs;exports.reinterpretType=Es;exports.reuseDecodedImageContent=nt;exports.tweenAnimation=Bs;exports.version=Et;