@selvajs/compute 1.5.2-beta.7 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-GZYSQSLH.cjs +2 -0
- package/dist/{chunk-TDXM32RV.cjs.map → chunk-GZYSQSLH.cjs.map} +1 -1
- package/dist/chunk-JZYEMZZ5.js +2 -0
- package/dist/{chunk-J3UKLYH5.js.map → chunk-JZYEMZZ5.js.map} +1 -1
- package/dist/{chunk-HO6NH6HB.js → chunk-OEDLGVIQ.js} +2 -2
- package/dist/{chunk-XLHA5YPH.js → chunk-OW6HV6QP.js} +2 -2
- package/dist/{chunk-VWOEUM7C.cjs → chunk-RBNF6MNH.cjs} +3 -3
- package/dist/chunk-RBNF6MNH.cjs.map +1 -0
- package/dist/{chunk-TRLKUOOF.cjs → chunk-SVEXPGHW.cjs} +2 -2
- package/dist/{chunk-TRLKUOOF.cjs.map → chunk-SVEXPGHW.cjs.map} +1 -1
- package/dist/{chunk-RHULSS7S.js → chunk-XBIEAJBK.js} +3 -3
- package/dist/chunk-XBIEAJBK.js.map +1 -0
- package/dist/{chunk-MZGKJZVP.cjs → chunk-ZRQRYG6F.cjs} +2 -2
- package/dist/{chunk-MZGKJZVP.cjs.map → chunk-ZRQRYG6F.cjs.map} +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{visualization-T5QNA4RB.js → visualization-ENMBHWIN.js} +2 -2
- package/dist/visualization-TBPFFBFU.cjs +2 -0
- package/dist/{visualization-NJLK5746.cjs.map → visualization-TBPFFBFU.cjs.map} +1 -1
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-J3UKLYH5.js +0 -2
- package/dist/chunk-RHULSS7S.js.map +0 -1
- package/dist/chunk-TDXM32RV.cjs +0 -2
- package/dist/chunk-VWOEUM7C.cjs.map +0 -1
- package/dist/visualization-NJLK5746.cjs +0 -2
- /package/dist/{chunk-HO6NH6HB.js.map → chunk-OEDLGVIQ.js.map} +0 -0
- /package/dist/{chunk-XLHA5YPH.js.map → chunk-OW6HV6QP.js.map} +0 -0
- /package/dist/{visualization-T5QNA4RB.js.map → visualization-ENMBHWIN.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as _}from"./chunk-XLHA5YPH.js";import{a as te,c as D,d as F,e as y}from"./chunk-RHULSS7S.js";import*as s from"three";import{OrbitControls as ne}from"three/addons/controls/OrbitControls.js";import{HDRLoader as re}from"three/addons/loaders/HDRLoader.js";var V=new s.Vector3(0,0,1),P=(e,r,n,t)=>{switch(e){case"mm":return r;case"cm":return n;default:return t}},Ze=function(e,r){let n=oe(r||{}),t=ae(n),o=de(n,e),a=me(e,n),i=he(o,e,n);le(t,n),ce(t,n),n.floor?.enabled&&ue(t,n);let c=n.events.enableEventHandlers!==!1?fe(e,t,o,i,n):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},l=e.parentElement,h=()=>l?{width:l.clientWidth,height:l.clientHeight}:{width:window.innerWidth,height:window.innerHeight},{animate:m,dispose:u}=se(a,t,o,i,h,n.events.onFrame);m();let E=n.environment?.sceneUp||V;return t.up.set(E.x,E.y,E.z),{scene:t,camera:o,controls:i,renderer:a,dispose:()=>{u(),c.dispose(),i.dispose(),a.dispose(),t.traverse(d=>{d instanceof s.Mesh&&(d.geometry?.dispose(),Array.isArray(d.material)?d.material.forEach(H=>H.dispose()):d.material?.dispose())})},fitToView:c.fitToView,clearSelection:c.clearSelection}};function oe(e){let r=e.sceneScale||"m",t={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:e.camera?.position||new s.Vector3(-t.cameraDistance,t.cameraDistance,t.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||t.near,far:e.camera?.far||t.far,target:e.camera?.target||new s.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new s.Vector3(t.lightDistance,t.lightHeight,t.lightDistance),ambientLightColor:e.lighting?.ambientLightColor||new s.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new s.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||V,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||t.floorSize,color:e.floor?.color||new s.Color(8421504),roughness:e.floor?.roughness||.7,metalness:e.floor?.metalness||0,receiveShadow:e.floor?.receiveShadow??!0},render:{enableShadows:e.render?.enableShadows??!0,shadowMapSize:e.render?.shadowMapSize||2048,antialias:e.render?.antialias??!0,pixelRatio:e.render?.pixelRatio||Math.min(window.devicePixelRatio,2),toneMapping:e.render?.toneMapping||s.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure||1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1},controls:{enableDamping:e.controls?.enableDamping??!1,dampingFactor:e.controls?.dampingFactor||.05,autoRotate:e.controls?.autoRotate??!1,autoRotateSpeed:e.controls?.autoRotateSpeed||.5,enableZoom:e.controls?.enableZoom??!0,enablePan:e.controls?.enablePan??!0,minDistance:e.controls?.minDistance||t.minDistance,maxDistance:e.controls?.maxDistance||1/0},events:{onBackgroundClicked:e.events?.onBackgroundClicked,onObjectSelected:e.events?.onObjectSelected,onMeshMetadataClicked:e.events?.onMeshMetadataClicked,onMeshDoubleClicked:e.events?.onMeshDoubleClicked,selectionColor:e.events?.selectionColor||"#ff0000",enableEventHandlers:e.events?.enableEventHandlers??!0,enableKeyboardControls:e.events?.enableKeyboardControls??!0,enableClickToFocus:e.events?.enableClickToFocus??!0,enableDoubleClickZoom:e.events?.enableDoubleClickZoom??!0,onReady:e.events?.onReady,onFrame:e.events?.onFrame}}}function ae(e){let r=new s.Scene,n=typeof e.environment.backgroundColor=="string"?new s.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=n||null,r}function ie(e,r,n,t,o=200){let a=e.position.clone(),i=r.target.clone(),c=performance.now(),l=m=>1-Math.pow(1-m,3),h=()=>{let m=performance.now()-c,u=l(Math.min(m/o,1));e.position.lerpVectors(a,n,u),r.target.lerpVectors(i,t,u),r.update(),u<1&&requestAnimationFrame(h)};requestAnimationFrame(h)}function se(e,r,n,t,o,a){let i=null,c=performance.now(),l=()=>{let{width:u,height:E}=o();if(u===0||E===0)return;let g=Math.min(window.devicePixelRatio,2),d=Math.round(u*g),H=Math.round(E*g);(e.domElement.width!==d||e.domElement.height!==H)&&(e.setPixelRatio(g),e.setSize(u,E,!1),n.aspect=u/E,n.updateProjectionMatrix())},h=function(){i=requestAnimationFrame(h);let u=performance.now(),E=(u-c)/1e3;c=u,l(),(t.enableDamping||t.autoRotate)&&t.update(),a?.(E),e.render(r,n)};return{animate:h,dispose:()=>{i!==null&&(cancelAnimationFrame(i),i=null)}}}function le(e,r){r.environment.enableEnvironmentLighting?new re().load(r.environment.hdrPath||"/baseHDR.hdr",function(n){n.mapping=s.EquirectangularReflectionMapping,e.environment=n,r.environment.showEnvironment&&(e.background=n),r.events.onReady?.()},void 0,function(n){y().warn("HDR texture could not be loaded, falling back to basic lighting:",n),r.events.onReady?.()}):r.events.onReady?.()}function ce(e,r){let n=new s.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(n),r.lighting.enableSunlight){let t=new s.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&t.position.set(o.x,o.y,o.z),r.render.enableShadows){t.castShadow=!0;let a=P(r.sceneScale,.1,10,100);t.shadow.camera.left=-a,t.shadow.camera.right=a,t.shadow.camera.top=a,t.shadow.camera.bottom=-a;let i=P(r.sceneScale,.001,.1,.5),c=P(r.sceneScale,1,100,500);t.shadow.camera.near=i,t.shadow.camera.far=c,t.shadow.mapSize.width=r.render.shadowMapSize||2048,t.shadow.mapSize.height=r.render.shadowMapSize||2048,t.shadow.bias=-1e-4,t.shadow.normalBias=.02}e.add(t)}}function ue(e,r){let n=r.floor.size,t=new s.PlaneGeometry(n,n),o=typeof r.floor.color=="string"?new s.Color(r.floor.color):r.floor.color,a=new s.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:s.DoubleSide}),i=new s.Mesh(t,a);i.userData.id="floor",i.name="floor",i.rotation.x=-Math.PI/2,i.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function de(e,r){let n=r.parentElement,t=n?n.clientWidth:window.innerWidth,o=n?n.clientHeight:window.innerHeight,a=new s.PerspectiveCamera(e.camera.fov,t/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function me(e,r){let n=new s.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),t=e.parentElement,o=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight;return t&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),n.setSize(o,a,!1),n.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(n.shadowMap.enabled=!0,n.shadowMap.type=s.VSMShadowMap),n.toneMapping=r.render.toneMapping,n.toneMappingExposure=r.render.toneMappingExposure||1,n.outputColorSpace=s.SRGBColorSpace,n.sortObjects=!0,n}function fe(e,r,n,t,o){let a=new Set,i=new Map,c=new s.Raycaster,l=new s.Vector2,h=new s.Vector2,m=f=>{let p=f;for(;p;){if(!p.visible)return!1;p=p.parent}return!0},u=()=>{let f=new s.Box3;if(r.traverse(A=>{A.visible&&A.userData.id!=="floor"&&A instanceof s.Mesh&&f.expandByObject(A)}),f.isEmpty()){y().warn("No objects to fit to view");return}let p=f.getCenter(new s.Vector3),T=f.getSize(new s.Vector3),v=Math.max(T.x,T.y,T.z),R=n.fov*(Math.PI/180),S=v/(2*Math.tan(R/2));S*=1.5;let O=n.position.clone().sub(t.target).normalize();n.position.copy(p.clone().add(O.multiplyScalar(S))),t.target.copy(p),t.update()},E=typeof o.events.selectionColor=="string"?new s.Color(o.events.selectionColor):o.events.selectionColor instanceof s.Color?o.events.selectionColor:new s.Color("#ff0000"),g=()=>{a.forEach(f=>{f instanceof s.Mesh&&i.has(f)&&(f.material=i.get(f),i.delete(f))}),a.clear()},d=f=>{h.set(f.clientX,f.clientY)},H=f=>{let p=new s.Vector2(f.clientX,f.clientY);if(h.distanceTo(p)>5)return;let T=e.getBoundingClientRect();l.x=(f.clientX-T.left)/T.width*2-1,l.y=-((f.clientY-T.top)/T.height)*2+1,c.setFromCamera(l,n);let v=c.intersectObjects(r.children,!0).filter(R=>m(R.object));if(v.length>0){let R=v[0].object;if(!a.has(R)){if(g(),a.add(R),R instanceof s.Mesh&&R.material instanceof s.Material){i.set(R,R.material);let S=R.material.clone();S.emissive=E.clone(),R.material=S}o.events?.onObjectSelected?.(R),R instanceof s.Mesh&&Object.keys(R.userData).length>0&&o.events?.onMeshMetadataClicked?.(R.userData)}}else g(),o.events?.onBackgroundClicked?.({x:l.x,y:l.y})},L=f=>{let p=e.getBoundingClientRect();l.x=(f.clientX-p.left)/p.width*2-1,l.y=-((f.clientY-p.top)/p.height)*2+1,c.setFromCamera(l,n);let T=c.intersectObjects(r.children,!0).filter(ee=>m(ee.object));if(T.length===0)return;let v=T[0].object;if(o.events?.onMeshDoubleClicked?.(v),!o.events?.enableDoubleClickZoom)return;let R=new s.Box3().setFromObject(v);if(R.isEmpty())return;let S=R.getCenter(new s.Vector3),O=R.getSize(new s.Vector3),A=Math.max(O.x,O.y,O.z),K=n.fov*(Math.PI/180),X=A/(2*Math.tan(K/2))*1.5,J=n.position.clone().sub(t.target).normalize(),Q=S.clone().add(J.multiplyScalar(X));ie(n,t,Q,S)},x=f=>{if(o.events?.enableKeyboardControls)switch(f.key.toLowerCase()){case"f":f.preventDefault(),u();break;case"escape":f.preventDefault(),g();break;case" ":f.preventDefault(),u();break}};return o.events?.enableClickToFocus&&(e.addEventListener("mousedown",d),e.addEventListener("click",H),e.addEventListener("dblclick",L)),o.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",d),e.removeEventListener("click",H),e.removeEventListener("dblclick",L),e.removeEventListener("keydown",x),g()},fitToView:u,clearSelection:g}}function he(e,r,n){let t=new ne(e,r),o=n.camera.target;return o&&t.target.set(o.x,o.y,o.z),t.enableDamping=n.controls.enableDamping||!1,t.dampingFactor=n.controls.dampingFactor||.05,t.autoRotate=n.controls.autoRotate||!1,t.autoRotateSpeed=n.controls.autoRotateSpeed||.5,t.enableZoom=n.controls.enableZoom??!0,t.enablePan=n.controls.enablePan??!0,t.minDistance=n.controls.minDistance||.001,t.maxDistance=n.controls.maxDistance||1/0,t.screenSpacePanning=!1,t.maxPolarAngle=Math.PI,t.update(),t}import*as w from"three";var B={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Xe(e,r,n,t,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let a=z(r),i=a.getCenter(new w.Vector3),c=a.getSize(new w.Vector3),l=Math.max(c.x,c.y,c.z);if(l/Math.min(c.x||1,c.y||1,c.z||1)>B.SCALE_RATIO_THRESHOLD||l>B.HUGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.TINY,n.far=l*B.FAR_PLANE_FACTOR.HUGE):l>B.LARGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.SMALL,n.far=l*B.FAR_PLANE_FACTOR.LARGE):(n.near=Math.max(.01,l*B.NEAR_PLANE_FACTOR.NORMAL),n.far=Math.max(2e3,l*B.FAR_PLANE_FACTOR.NORMAL)),n.updateProjectionMatrix(),o)t.minDistance=n.near*2,t.maxDistance=n.far*.9;else{let m=l*B.INITIAL_DISTANCE_MULTIPLIER;n.position.set(i.x+m*.8,i.y+m,i.z+m*1.2),t.target.copy(i),t.minDistance=n.near*2,t.maxDistance=n.far*.9,t.update()}}function N(e){if(!e||typeof e!="string")return y().warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let n=r.startsWith("#")?r:`#${r}`;return new w.Color(n)}catch{return y().warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let n=r.split(",").map(t=>parseInt(t.trim(),10));if(n.length===3&&n.every(t=>!isNaN(t)&&t>=0&&t<=255))return new w.Color(n[0]/255,n[1]/255,n[2]/255)}try{return new w.Color(r.toLowerCase())}catch{return y().warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function G(e,r){e.forEach(n=>{n.position.y-=r})}function z(e){let r=new w.Box3;return e.length===0||e.forEach(n=>{n.updateMatrixWorld(!0);let t=new w.Box3().setFromObject(n);r.union(t)}),r}function Ee(e){[...e.children].forEach(n=>{n.userData.id!=="floor"&&(n.traverse(t=>{if(!(t instanceof w.Mesh))return;t.geometry?.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(a=>{for(let i of Object.values(a))i instanceof w.Texture&&i.dispose();a.dispose()})}),n.removeFromParent())})}var Me={};te(Me,{CONCRETE_MATERIAL:()=>ye,EMISSIVE_MATERIAL:()=>pe,GLASS_MATERIAL:()=>Re,METAL_MATERIAL:()=>ge,PLASTIC_MATERIAL:()=>be,RUBBER_MATERIAL:()=>Te,WOOD_MATERIAL:()=>we});import*as b from"three";var pe=new b.MeshPhysicalMaterial({color:0,emissive:new b.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ge=new b.MeshPhysicalMaterial({color:new b.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ye=new b.MeshPhysicalMaterial({color:new b.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),be=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Re=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new b.MeshPhysicalMaterial({color:new b.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new b.MeshPhysicalMaterial({color:new b.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var $=1096174675,W=1,k=1,Y=12,j=56;function U(e){let r=He(e),n=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Y)throw I("Blob too small to contain SLVA header.",{expectedBytes:Y,availableBytes:r.byteLength});let t=0,o=n.getUint32(t,!0);if(t+=4,o!==$)throw I(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${$.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=n.getUint32(t,!0);if(t+=4,a!==W)throw I(`Unsupported SLVA version: ${a}`,{expectedVersion:W,actualVersion:a});let i=n.getUint32(t,!0);if(t+=4,t+i>r.byteLength)throw I("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-t,offset:t});let c=r.subarray(t,t+i);t+=i;let l;try{l=JSON.parse(xe(c))}catch(A){throw I(`Failed to parse metadata JSON: ${A instanceof Error?A.message:String(A)}`,{metadataLen:i})}if(t+j>r.byteLength)throw I("Insufficient data to read geometry header.",{expectedBytes:j,availableBytes:r.byteLength-t,offset:t});let h=n.getUint32(t,!0);t+=4;let m=n.getFloat64(t,!0);t+=8;let u=n.getFloat64(t,!0);t+=8;let E=n.getFloat64(t,!0);t+=8;let g=n.getFloat64(t,!0);t+=8;let d=n.getFloat64(t,!0);t+=8;let H=n.getFloat64(t,!0);t+=8;let L=n.getUint32(t,!0);t+=4;let x=(h&k)!==0,C=L*3,p=C*(x?4:2);if(t+p>r.byteLength)throw I("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:r.byteLength-t,offset:t,useFloat32:x,vertexCount:L});let T=r.byteOffset+t,v=x?ve(r.buffer,T,C):Ce(r.buffer,T,C);if(t+=p,t+4>r.byteLength)throw I("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-t,offset:t});let R=n.getUint32(t,!0);t+=4;let S=R*4;if(t+S>r.byteLength)throw I("Insufficient data to read indices.",{expectedBytes:S,availableBytes:r.byteLength-t,offset:t,indexCount:R});let O=Se(r.buffer,r.byteOffset+t,R);return{metadata:l,flags:h,vertices:v,indices:O,origin:[m,u,E],scale:[g,d,H]}}function He(e){return typeof e=="string"?_(e):e instanceof Uint8Array?e:new Uint8Array(e)}function xe(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new F("No UTF-8 decoder available in this environment.",D.INVALID_STATE)}function Ce(e,r,n){if(n===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,n);let t=new Uint8Array(n*2);return t.set(new Uint8Array(e,r,n*2)),new Int16Array(t.buffer)}function ve(e,r,n){if(n===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Float32Array(t.buffer)}function Se(e,r,n){if(n===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Uint32Array(t.buffer)}function I(e,r){return new F(e,D.VALIDATION_ERROR,{context:r})}import*as M from"three";async function Z(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,debug:o=!1}=r??{},a=o?performance.now():0,i=0;try{let c=performance.now(),l=JSON.parse(e);return i=performance.now()-c,await Ae(l,{mergeByMaterial:n,applyTransforms:t,debug:o,parseTime:i,perfStart:a})}catch(c){return y().error("Error parsing mesh batch:",c),[]}}async function Ae(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1,parseTime:i=0,perfStart:c=a?performance.now():0}=r??{};try{let l=performance.now(),h=U(e.compressedData),m=performance.now()-l,u=a?Fe(e.compressedData):0;return q(h,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:m,perfStart:c,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return y().error("Error parsing mesh batch object:",l),[]}}async function at(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1}=r??{},i=a?performance.now():0;try{let c=performance.now(),l=U(e),h=performance.now()-c,m=(e instanceof Uint8Array,e.byteLength);return q(l,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:0,decodeTime:h,perfStart:i,blobBytes:m})}catch(c){return y().error("Error parsing mesh batch blob:",c),[]}}function q(e,r){let{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:c,perfStart:l,blobBytes:h,fallback:m}=r,u=e.metadata.materials??m?.materials??[],E=e.metadata.groups??m?.groups??[],g=e.metadata.sourceComponentId??m?.sourceComponentId,d=(e.flags&k)!==0,H=d?Le(e.vertices,t):Be(e.vertices,e.origin,e.scale,t);if(a){let p=e.vertices.byteLength+e.indices.byteLength;y().debug("Mesh Batch Stats:"),y().debug(` Materials: ${u.length} | Groups: ${E.length}`),y().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),y().debug(` Format: ${d?"float32":"int16 quantized"}`),y().debug(` Blob: ${(h/1024/1024).toFixed(2)} MB | Geometry on wire: ${(p/1024/1024).toFixed(2)} MB`)}let L=performance.now(),x=u.map(Ie),C=[];for(let p of E)if(n&&p.meshes.length>1){let T=Oe(p,H,e.indices,x);T.userData.sourceComponentId=g??null,C.push(T)}else{let T=De(p,H,e.indices,x);for(let v of T)v.userData.sourceComponentId=g??null;C.push(...T)}if(o!==1)for(let p of C)p.scale.set(o,o,o);let f=performance.now()-L;if(a){let p=performance.now()-l;y().debug("Performance:"),i>0&&y().debug(` Parse JSON: ${i.toFixed(2)}ms`),y().debug(` Decode binary: ${c.toFixed(2)}ms`),y().debug(` Create Meshes: ${f.toFixed(2)}ms`),y().debug(` Total: ${p.toFixed(2)}ms`)}return Promise.resolve(C)}function Be(e,r,n,t){let o=new Float32Array(e.length),a=r[0],i=r[1],c=r[2],l=n[0],h=n[1],m=n[2];if(t)for(let u=0;u<e.length;u+=3){let E=a+(e[u]+32767)*l,g=i+(e[u+1]+32767)*h,d=c+(e[u+2]+32767)*m;o[u]=E,o[u+1]=d,o[u+2]=-g}else for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*l,o[u+1]=i+(e[u+1]+32767)*h,o[u+2]=c+(e[u+2]+32767)*m;return o}function Le(e,r){if(!r)return e;let n=new Float32Array(e.length);for(let t=0;t<e.length;t+=3){let o=e[t],a=e[t+1],i=e[t+2];n[t]=o,n[t+1]=i,n[t+2]=-a}return n}function Ie(e){let r=N(e.color);return new M.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:M.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Oe(e,r,n,t){let o=0,a=0;for(let d of e.meshes)o+=d.vertexCount,a+=d.indexCount;let i=new Float32Array(o*3),c=new Uint32Array(a),l=0,h=0;for(let d of e.meshes){let H=d.vertexStart*3,L=d.vertexCount*3;i.set(r.subarray(H,H+L),l*3);let x=n.subarray(d.indexStart,d.indexStart+d.indexCount),C=l-d.vertexStart;if(C===0)c.set(x,h);else for(let f=0;f<x.length;f++)c[h+f]=x[f]+C;l+=d.vertexCount,h+=d.indexCount}let m=new M.BufferGeometry;m.setAttribute("position",new M.BufferAttribute(i,3)),m.setIndex(new M.BufferAttribute(c,1)),m.computeVertexNormals();let u=new M.Mesh(m,t[e.materialId]),E=e.meshes[0],g=e.meshes.map(d=>d.name).filter(d=>d&&d.length>0);return u.name=g.length>0?g[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={name:u.name,layer:E?.layer??"",originalIndex:E?.originalIndex??0,metadata:E?.metadata??{},mergedFrom:e.meshes.slice(1).map(d=>({name:d.name,layer:d.layer,originalIndex:d.originalIndex}))},u}function De(e,r,n,t){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,c=a.vertexCount*3,l=r.slice(i,i+c),h=n.subarray(a.indexStart,a.indexStart+a.indexCount),m=new Uint32Array(h.length),u=a.vertexStart;for(let d=0;d<h.length;d++)m[d]=h[d]-u;let E=new M.BufferGeometry;E.setAttribute("position",new M.BufferAttribute(l,3)),E.setIndex(new M.BufferAttribute(m,1)),E.computeVertexNormals();let g=new M.Mesh(E,t[e.materialId]);g.name=a.name,g.userData={name:a.name,layer:a.layer??"",originalIndex:a.originalIndex,metadata:a.metadata??{}},g.castShadow=!0,g.receiveShadow=!0,o.push(g)}return o}function Fe(e){return Math.floor(e.length*3/4)}var Pe={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ze="Display";async function ut(e,r){let n=performance.now(),t=[],{allowScaling:o=!0,allowAutoPosition:a=!0,debug:i=!1,parsing:c={}}=r??{};try{let l=o?ke(e.modelunits):1;return await Ue(e,t,l,c,i),a&&Ve(t),t}catch(l){throw Ne(l,t),l}finally{i&&$e(n)}}function ke(e){return Pe[e]??1}async function Ue(e,r,n,t,o){for(let a of e.values){let i=a.InnerTree;for(let c in i){let l=i[c];l&&await _e(l,r,n,t,o)}}}async function _e(e,r,n,t,o){for(let a of e)if(a.type.includes(ze)){let i={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...t},c=await Z(a.data,i);if(n!==1)for(let l of c)l.scale.set(n,n,n);r.push(...c),o&&y().debug(`Extracted ${c.length} meshes from batch`)}}function Ve(e){if(e.length===0)return;let n=z(e).min.y;G(e,n)}function Ne(e,r){y().error("An unexpected error occurred:",e),Ge(r)}function Ge(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(n=>n.dispose()):r.material.dispose())}function $e(e){let r=performance.now()-e;y().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{Ze as a,Xe as b,N as c,G as d,z as e,Me as f,$ as g,W as h,k as i,U as j,Z as k,Ae as l,at as m,Pe as n,ut as o};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as _}from"./chunk-OW6HV6QP.js";import{a as te,c as D,d as F,e as y}from"./chunk-XBIEAJBK.js";import*as s from"three";import{OrbitControls as ne}from"three/addons/controls/OrbitControls.js";import{HDRLoader as re}from"three/addons/loaders/HDRLoader.js";var V=new s.Vector3(0,0,1),P=(e,r,n,t)=>{switch(e){case"mm":return r;case"cm":return n;default:return t}},Ze=function(e,r){let n=oe(r||{}),t=ae(n),o=de(n,e),a=me(e,n),i=he(o,e,n);le(t,n),ce(t,n),n.floor?.enabled&&ue(t,n);let c=n.events.enableEventHandlers!==!1?fe(e,t,o,i,n):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},l=e.parentElement,h=()=>l?{width:l.clientWidth,height:l.clientHeight}:{width:window.innerWidth,height:window.innerHeight},{animate:m,dispose:u}=se(a,t,o,i,h,n.events.onFrame);m();let E=n.environment?.sceneUp||V;return t.up.set(E.x,E.y,E.z),{scene:t,camera:o,controls:i,renderer:a,dispose:()=>{u(),c.dispose(),i.dispose(),a.dispose(),t.traverse(d=>{d instanceof s.Mesh&&(d.geometry?.dispose(),Array.isArray(d.material)?d.material.forEach(H=>H.dispose()):d.material?.dispose())})},fitToView:c.fitToView,clearSelection:c.clearSelection}};function oe(e){let r=e.sceneScale||"m",t={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:e.camera?.position||new s.Vector3(-t.cameraDistance,t.cameraDistance,t.cameraDistance),fov:e.camera?.fov||20,near:e.camera?.near||t.near,far:e.camera?.far||t.far,target:e.camera?.target||new s.Vector3(0,0,0)},lighting:{enableSunlight:e.lighting?.enableSunlight??!0,sunlightIntensity:e.lighting?.sunlightIntensity||1,sunlightPosition:e.lighting?.sunlightPosition||new s.Vector3(t.lightDistance,t.lightHeight,t.lightDistance),ambientLightColor:e.lighting?.ambientLightColor||new s.Color(4210752),ambientLightIntensity:e.lighting?.ambientLightIntensity||1,sunlightColor:e.lighting?.sunlightColor||16777215},environment:{hdrPath:e.environment?.hdrPath||"/baseHDR.hdr",backgroundColor:e.environment?.backgroundColor||new s.Color(15790320),enableEnvironmentLighting:e.environment?.enableEnvironmentLighting??!0,sceneUp:e.environment?.sceneUp||V,showEnvironment:e.environment?.showEnvironment??!1},floor:{enabled:e.floor?.enabled??!1,size:e.floor?.size||t.floorSize,color:e.floor?.color||new s.Color(8421504),roughness:e.floor?.roughness||.7,metalness:e.floor?.metalness||0,receiveShadow:e.floor?.receiveShadow??!0},render:{enableShadows:e.render?.enableShadows??!0,shadowMapSize:e.render?.shadowMapSize||2048,antialias:e.render?.antialias??!0,pixelRatio:e.render?.pixelRatio||Math.min(window.devicePixelRatio,2),toneMapping:e.render?.toneMapping||s.NeutralToneMapping,toneMappingExposure:e.render?.toneMappingExposure||1,preserveDrawingBuffer:e.render?.preserveDrawingBuffer??!1},controls:{enableDamping:e.controls?.enableDamping??!1,dampingFactor:e.controls?.dampingFactor||.05,autoRotate:e.controls?.autoRotate??!1,autoRotateSpeed:e.controls?.autoRotateSpeed||.5,enableZoom:e.controls?.enableZoom??!0,enablePan:e.controls?.enablePan??!0,minDistance:e.controls?.minDistance||t.minDistance,maxDistance:e.controls?.maxDistance||1/0},events:{onBackgroundClicked:e.events?.onBackgroundClicked,onObjectSelected:e.events?.onObjectSelected,onMeshMetadataClicked:e.events?.onMeshMetadataClicked,onMeshDoubleClicked:e.events?.onMeshDoubleClicked,selectionColor:e.events?.selectionColor||"#ff0000",enableEventHandlers:e.events?.enableEventHandlers??!0,enableKeyboardControls:e.events?.enableKeyboardControls??!0,enableClickToFocus:e.events?.enableClickToFocus??!0,enableDoubleClickZoom:e.events?.enableDoubleClickZoom??!0,onReady:e.events?.onReady,onFrame:e.events?.onFrame}}}function ae(e){let r=new s.Scene,n=typeof e.environment.backgroundColor=="string"?new s.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=n||null,r}function ie(e,r,n,t,o=200){let a=e.position.clone(),i=r.target.clone(),c=performance.now(),l=m=>1-Math.pow(1-m,3),h=()=>{let m=performance.now()-c,u=l(Math.min(m/o,1));e.position.lerpVectors(a,n,u),r.target.lerpVectors(i,t,u),r.update(),u<1&&requestAnimationFrame(h)};requestAnimationFrame(h)}function se(e,r,n,t,o,a){let i=null,c=performance.now(),l=()=>{let{width:u,height:E}=o();if(u===0||E===0)return;let g=Math.min(window.devicePixelRatio,2),d=Math.round(u*g),H=Math.round(E*g);(e.domElement.width!==d||e.domElement.height!==H)&&(e.setPixelRatio(g),e.setSize(u,E,!1),n.aspect=u/E,n.updateProjectionMatrix())},h=function(){i=requestAnimationFrame(h);let u=performance.now(),E=(u-c)/1e3;c=u,l(),(t.enableDamping||t.autoRotate)&&t.update(),a?.(E),e.render(r,n)};return{animate:h,dispose:()=>{i!==null&&(cancelAnimationFrame(i),i=null)}}}function le(e,r){r.environment.enableEnvironmentLighting?new re().load(r.environment.hdrPath||"/baseHDR.hdr",function(n){n.mapping=s.EquirectangularReflectionMapping,e.environment=n,r.environment.showEnvironment&&(e.background=n),r.events.onReady?.()},void 0,function(n){y().warn("HDR texture could not be loaded, falling back to basic lighting:",n),r.events.onReady?.()}):r.events.onReady?.()}function ce(e,r){let n=new s.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(n),r.lighting.enableSunlight){let t=new s.DirectionalLight(r.lighting.sunlightColor??16777215,r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&t.position.set(o.x,o.y,o.z),r.render.enableShadows){t.castShadow=!0;let a=P(r.sceneScale,.1,10,100);t.shadow.camera.left=-a,t.shadow.camera.right=a,t.shadow.camera.top=a,t.shadow.camera.bottom=-a;let i=P(r.sceneScale,.001,.1,.5),c=P(r.sceneScale,1,100,500);t.shadow.camera.near=i,t.shadow.camera.far=c,t.shadow.mapSize.width=r.render.shadowMapSize||2048,t.shadow.mapSize.height=r.render.shadowMapSize||2048,t.shadow.bias=-1e-4,t.shadow.normalBias=.02}e.add(t)}}function ue(e,r){let n=r.floor.size,t=new s.PlaneGeometry(n,n),o=typeof r.floor.color=="string"?new s.Color(r.floor.color):r.floor.color,a=new s.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:s.DoubleSide}),i=new s.Mesh(t,a);i.userData.id="floor",i.name="floor",i.rotation.x=-Math.PI/2,i.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function de(e,r){let n=r.parentElement,t=n?n.clientWidth:window.innerWidth,o=n?n.clientHeight:window.innerHeight,a=new s.PerspectiveCamera(e.camera.fov,t/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function me(e,r){let n=new s.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),t=e.parentElement,o=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight;return t&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),n.setSize(o,a,!1),n.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(n.shadowMap.enabled=!0,n.shadowMap.type=s.VSMShadowMap),n.toneMapping=r.render.toneMapping,n.toneMappingExposure=r.render.toneMappingExposure||1,n.outputColorSpace=s.SRGBColorSpace,n.sortObjects=!0,n}function fe(e,r,n,t,o){let a=new Set,i=new Map,c=new s.Raycaster,l=new s.Vector2,h=new s.Vector2,m=f=>{let p=f;for(;p;){if(!p.visible)return!1;p=p.parent}return!0},u=()=>{let f=new s.Box3;if(r.traverse(A=>{A.visible&&A.userData.id!=="floor"&&A instanceof s.Mesh&&f.expandByObject(A)}),f.isEmpty()){y().warn("No objects to fit to view");return}let p=f.getCenter(new s.Vector3),T=f.getSize(new s.Vector3),v=Math.max(T.x,T.y,T.z),R=n.fov*(Math.PI/180),S=v/(2*Math.tan(R/2));S*=1.5;let O=n.position.clone().sub(t.target).normalize();n.position.copy(p.clone().add(O.multiplyScalar(S))),t.target.copy(p),t.update()},E=typeof o.events.selectionColor=="string"?new s.Color(o.events.selectionColor):o.events.selectionColor instanceof s.Color?o.events.selectionColor:new s.Color("#ff0000"),g=()=>{a.forEach(f=>{f instanceof s.Mesh&&i.has(f)&&(f.material=i.get(f),i.delete(f))}),a.clear()},d=f=>{h.set(f.clientX,f.clientY)},H=f=>{let p=new s.Vector2(f.clientX,f.clientY);if(h.distanceTo(p)>5)return;let T=e.getBoundingClientRect();l.x=(f.clientX-T.left)/T.width*2-1,l.y=-((f.clientY-T.top)/T.height)*2+1,c.setFromCamera(l,n);let v=c.intersectObjects(r.children,!0).filter(R=>m(R.object));if(v.length>0){let R=v[0].object;if(!a.has(R)){if(g(),a.add(R),R instanceof s.Mesh&&R.material instanceof s.Material){i.set(R,R.material);let S=R.material.clone();S.emissive=E.clone(),R.material=S}o.events?.onObjectSelected?.(R),R instanceof s.Mesh&&Object.keys(R.userData).length>0&&o.events?.onMeshMetadataClicked?.(R.userData)}}else g(),o.events?.onBackgroundClicked?.({x:l.x,y:l.y})},L=f=>{let p=e.getBoundingClientRect();l.x=(f.clientX-p.left)/p.width*2-1,l.y=-((f.clientY-p.top)/p.height)*2+1,c.setFromCamera(l,n);let T=c.intersectObjects(r.children,!0).filter(ee=>m(ee.object));if(T.length===0)return;let v=T[0].object;if(o.events?.onMeshDoubleClicked?.(v),!o.events?.enableDoubleClickZoom)return;let R=new s.Box3().setFromObject(v);if(R.isEmpty())return;let S=R.getCenter(new s.Vector3),O=R.getSize(new s.Vector3),A=Math.max(O.x,O.y,O.z),K=n.fov*(Math.PI/180),X=A/(2*Math.tan(K/2))*1.5,J=n.position.clone().sub(t.target).normalize(),Q=S.clone().add(J.multiplyScalar(X));ie(n,t,Q,S)},x=f=>{if(o.events?.enableKeyboardControls)switch(f.key.toLowerCase()){case"f":f.preventDefault(),u();break;case"escape":f.preventDefault(),g();break;case" ":f.preventDefault(),u();break}};return o.events?.enableClickToFocus&&(e.addEventListener("mousedown",d),e.addEventListener("click",H),e.addEventListener("dblclick",L)),o.events?.enableKeyboardControls&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",d),e.removeEventListener("click",H),e.removeEventListener("dblclick",L),e.removeEventListener("keydown",x),g()},fitToView:u,clearSelection:g}}function he(e,r,n){let t=new ne(e,r),o=n.camera.target;return o&&t.target.set(o.x,o.y,o.z),t.enableDamping=n.controls.enableDamping||!1,t.dampingFactor=n.controls.dampingFactor||.05,t.autoRotate=n.controls.autoRotate||!1,t.autoRotateSpeed=n.controls.autoRotateSpeed||.5,t.enableZoom=n.controls.enableZoom??!0,t.enablePan=n.controls.enablePan??!0,t.minDistance=n.controls.minDistance||.001,t.maxDistance=n.controls.maxDistance||1/0,t.screenSpacePanning=!1,t.maxPolarAngle=Math.PI,t.update(),t}import*as w from"three";var B={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Xe(e,r,n,t,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let a=z(r),i=a.getCenter(new w.Vector3),c=a.getSize(new w.Vector3),l=Math.max(c.x,c.y,c.z);if(l/Math.min(c.x||1,c.y||1,c.z||1)>B.SCALE_RATIO_THRESHOLD||l>B.HUGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.TINY,n.far=l*B.FAR_PLANE_FACTOR.HUGE):l>B.LARGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.SMALL,n.far=l*B.FAR_PLANE_FACTOR.LARGE):(n.near=Math.max(.01,l*B.NEAR_PLANE_FACTOR.NORMAL),n.far=Math.max(2e3,l*B.FAR_PLANE_FACTOR.NORMAL)),n.updateProjectionMatrix(),o)t.minDistance=n.near*2,t.maxDistance=n.far*.9;else{let m=l*B.INITIAL_DISTANCE_MULTIPLIER;n.position.set(i.x+m*.8,i.y+m,i.z+m*1.2),t.target.copy(i),t.minDistance=n.near*2,t.maxDistance=n.far*.9,t.update()}}function N(e){if(!e||typeof e!="string")return y().warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let n=r.startsWith("#")?r:`#${r}`;return new w.Color(n)}catch{return y().warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let n=r.split(",").map(t=>parseInt(t.trim(),10));if(n.length===3&&n.every(t=>!isNaN(t)&&t>=0&&t<=255))return new w.Color(n[0]/255,n[1]/255,n[2]/255)}try{return new w.Color(r.toLowerCase())}catch{return y().warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function G(e,r){e.forEach(n=>{n.position.y-=r})}function z(e){let r=new w.Box3;return e.length===0||e.forEach(n=>{n.updateMatrixWorld(!0);let t=new w.Box3().setFromObject(n);r.union(t)}),r}function Ee(e){[...e.children].forEach(n=>{n.userData.id!=="floor"&&(n.traverse(t=>{if(!(t instanceof w.Mesh))return;t.geometry?.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(a=>{for(let i of Object.values(a))i instanceof w.Texture&&i.dispose();a.dispose()})}),n.removeFromParent())})}var Me={};te(Me,{CONCRETE_MATERIAL:()=>ye,EMISSIVE_MATERIAL:()=>pe,GLASS_MATERIAL:()=>Re,METAL_MATERIAL:()=>ge,PLASTIC_MATERIAL:()=>be,RUBBER_MATERIAL:()=>Te,WOOD_MATERIAL:()=>we});import*as b from"three";var pe=new b.MeshPhysicalMaterial({color:0,emissive:new b.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ge=new b.MeshPhysicalMaterial({color:new b.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ye=new b.MeshPhysicalMaterial({color:new b.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),be=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Re=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new b.MeshPhysicalMaterial({color:new b.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new b.MeshPhysicalMaterial({color:new b.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var $=1096174675,W=1,k=1,Y=12,j=56;function U(e){let r=He(e),n=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Y)throw I("Blob too small to contain SLVA header.",{expectedBytes:Y,availableBytes:r.byteLength});let t=0,o=n.getUint32(t,!0);if(t+=4,o!==$)throw I(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${$.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=n.getUint32(t,!0);if(t+=4,a!==W)throw I(`Unsupported SLVA version: ${a}`,{expectedVersion:W,actualVersion:a});let i=n.getUint32(t,!0);if(t+=4,t+i>r.byteLength)throw I("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-t,offset:t});let c=r.subarray(t,t+i);t+=i;let l;try{l=JSON.parse(xe(c))}catch(A){throw I(`Failed to parse metadata JSON: ${A instanceof Error?A.message:String(A)}`,{metadataLen:i})}if(t+j>r.byteLength)throw I("Insufficient data to read geometry header.",{expectedBytes:j,availableBytes:r.byteLength-t,offset:t});let h=n.getUint32(t,!0);t+=4;let m=n.getFloat64(t,!0);t+=8;let u=n.getFloat64(t,!0);t+=8;let E=n.getFloat64(t,!0);t+=8;let g=n.getFloat64(t,!0);t+=8;let d=n.getFloat64(t,!0);t+=8;let H=n.getFloat64(t,!0);t+=8;let L=n.getUint32(t,!0);t+=4;let x=(h&k)!==0,C=L*3,p=C*(x?4:2);if(t+p>r.byteLength)throw I("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:r.byteLength-t,offset:t,useFloat32:x,vertexCount:L});let T=r.byteOffset+t,v=x?ve(r.buffer,T,C):Ce(r.buffer,T,C);if(t+=p,t+4>r.byteLength)throw I("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-t,offset:t});let R=n.getUint32(t,!0);t+=4;let S=R*4;if(t+S>r.byteLength)throw I("Insufficient data to read indices.",{expectedBytes:S,availableBytes:r.byteLength-t,offset:t,indexCount:R});let O=Se(r.buffer,r.byteOffset+t,R);return{metadata:l,flags:h,vertices:v,indices:O,origin:[m,u,E],scale:[g,d,H]}}function He(e){return typeof e=="string"?_(e):e instanceof Uint8Array?e:new Uint8Array(e)}function xe(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new F("No UTF-8 decoder available in this environment.",D.INVALID_STATE)}function Ce(e,r,n){if(n===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,n);let t=new Uint8Array(n*2);return t.set(new Uint8Array(e,r,n*2)),new Int16Array(t.buffer)}function ve(e,r,n){if(n===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Float32Array(t.buffer)}function Se(e,r,n){if(n===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Uint32Array(t.buffer)}function I(e,r){return new F(e,D.VALIDATION_ERROR,{context:r})}import*as M from"three";async function Z(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,debug:o=!1}=r??{},a=o?performance.now():0,i=0;try{let c=performance.now(),l=JSON.parse(e);return i=performance.now()-c,await Ae(l,{mergeByMaterial:n,applyTransforms:t,debug:o,parseTime:i,perfStart:a})}catch(c){return y().error("Error parsing mesh batch:",c),[]}}async function Ae(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1,parseTime:i=0,perfStart:c=a?performance.now():0}=r??{};try{let l=performance.now(),h=U(e.compressedData),m=performance.now()-l,u=a?Fe(e.compressedData):0;return q(h,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:m,perfStart:c,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return y().error("Error parsing mesh batch object:",l),[]}}async function at(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1}=r??{},i=a?performance.now():0;try{let c=performance.now(),l=U(e),h=performance.now()-c,m=(e instanceof Uint8Array,e.byteLength);return q(l,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:0,decodeTime:h,perfStart:i,blobBytes:m})}catch(c){return y().error("Error parsing mesh batch blob:",c),[]}}function q(e,r){let{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:c,perfStart:l,blobBytes:h,fallback:m}=r,u=e.metadata.materials??m?.materials??[],E=e.metadata.groups??m?.groups??[],g=e.metadata.sourceComponentId??m?.sourceComponentId,d=(e.flags&k)!==0,H=d?Le(e.vertices,t):Be(e.vertices,e.origin,e.scale,t);if(a){let p=e.vertices.byteLength+e.indices.byteLength;y().debug("Mesh Batch Stats:"),y().debug(` Materials: ${u.length} | Groups: ${E.length}`),y().debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),y().debug(` Format: ${d?"float32":"int16 quantized"}`),y().debug(` Blob: ${(h/1024/1024).toFixed(2)} MB | Geometry on wire: ${(p/1024/1024).toFixed(2)} MB`)}let L=performance.now(),x=u.map(Ie),C=[];for(let p of E)if(n&&p.meshes.length>1){let T=Oe(p,H,e.indices,x);T.userData.sourceComponentId=g??null,C.push(T)}else{let T=De(p,H,e.indices,x);for(let v of T)v.userData.sourceComponentId=g??null;C.push(...T)}if(o!==1)for(let p of C)p.scale.set(o,o,o);let f=performance.now()-L;if(a){let p=performance.now()-l;y().debug("Performance:"),i>0&&y().debug(` Parse JSON: ${i.toFixed(2)}ms`),y().debug(` Decode binary: ${c.toFixed(2)}ms`),y().debug(` Create Meshes: ${f.toFixed(2)}ms`),y().debug(` Total: ${p.toFixed(2)}ms`)}return Promise.resolve(C)}function Be(e,r,n,t){let o=new Float32Array(e.length),a=r[0],i=r[1],c=r[2],l=n[0],h=n[1],m=n[2];if(t)for(let u=0;u<e.length;u+=3){let E=a+(e[u]+32767)*l,g=i+(e[u+1]+32767)*h,d=c+(e[u+2]+32767)*m;o[u]=E,o[u+1]=d,o[u+2]=-g}else for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*l,o[u+1]=i+(e[u+1]+32767)*h,o[u+2]=c+(e[u+2]+32767)*m;return o}function Le(e,r){if(!r)return e;let n=new Float32Array(e.length);for(let t=0;t<e.length;t+=3){let o=e[t],a=e[t+1],i=e[t+2];n[t]=o,n[t+1]=i,n[t+2]=-a}return n}function Ie(e){let r=N(e.color);return new M.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:M.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Oe(e,r,n,t){let o=0,a=0;for(let d of e.meshes)o+=d.vertexCount,a+=d.indexCount;let i=new Float32Array(o*3),c=new Uint32Array(a),l=0,h=0;for(let d of e.meshes){let H=d.vertexStart*3,L=d.vertexCount*3;i.set(r.subarray(H,H+L),l*3);let x=n.subarray(d.indexStart,d.indexStart+d.indexCount),C=l-d.vertexStart;if(C===0)c.set(x,h);else for(let f=0;f<x.length;f++)c[h+f]=x[f]+C;l+=d.vertexCount,h+=d.indexCount}let m=new M.BufferGeometry;m.setAttribute("position",new M.BufferAttribute(i,3)),m.setIndex(new M.BufferAttribute(c,1)),m.computeVertexNormals();let u=new M.Mesh(m,t[e.materialId]),E=e.meshes[0],g=e.meshes.map(d=>d.name).filter(d=>d&&d.length>0);return u.name=g.length>0?g[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={name:u.name,layer:E?.layer??"",originalIndex:E?.originalIndex??0,metadata:E?.metadata??{},mergedFrom:e.meshes.slice(1).map(d=>({name:d.name,layer:d.layer,originalIndex:d.originalIndex}))},u}function De(e,r,n,t){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,c=a.vertexCount*3,l=r.slice(i,i+c),h=n.subarray(a.indexStart,a.indexStart+a.indexCount),m=new Uint32Array(h.length),u=a.vertexStart;for(let d=0;d<h.length;d++)m[d]=h[d]-u;let E=new M.BufferGeometry;E.setAttribute("position",new M.BufferAttribute(l,3)),E.setIndex(new M.BufferAttribute(m,1)),E.computeVertexNormals();let g=new M.Mesh(E,t[e.materialId]);g.name=a.name,g.userData={name:a.name,layer:a.layer??"",originalIndex:a.originalIndex,metadata:a.metadata??{}},g.castShadow=!0,g.receiveShadow=!0,o.push(g)}return o}function Fe(e){return Math.floor(e.length*3/4)}var Pe={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ze="Display";async function ut(e,r){let n=performance.now(),t=[],{allowScaling:o=!0,allowAutoPosition:a=!0,debug:i=!1,parsing:c={}}=r??{};try{let l=o?ke(e.modelunits):1;return await Ue(e,t,l,c,i),a&&Ve(t),t}catch(l){throw Ne(l,t),l}finally{i&&$e(n)}}function ke(e){return Pe[e]??1}async function Ue(e,r,n,t,o){for(let a of e.values){let i=a.InnerTree;for(let c in i){let l=i[c];l&&await _e(l,r,n,t,o)}}}async function _e(e,r,n,t,o){for(let a of e)if(a.type.includes(ze)){let i={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...t},c=await Z(a.data,i);if(n!==1)for(let l of c)l.scale.set(n,n,n);r.push(...c),o&&y().debug(`Extracted ${c.length} meshes from batch`)}}function Ve(e){if(e.length===0)return;let n=z(e).min.y;G(e,n)}function Ne(e,r){y().error("An unexpected error occurred:",e),Ge(r)}function Ge(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(n=>n.dispose()):r.material.dispose())}function $e(e){let r=performance.now()-e;y().info("Time to process meshes:",`${r.toFixed(2)}ms`)}export{Ze as a,Xe as b,N as c,G as d,z as e,Me as f,$ as g,W as h,k as i,U as j,Z as k,Ae as l,at as m,Pe as n,ut as o};
|
|
2
|
+
//# sourceMappingURL=chunk-OEDLGVIQ.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as n,d as a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as n,d as a}from"./chunk-XBIEAJBK.js";function f(e){return Buffer.from(e,"utf-8").toString("base64")}function s(e){return!e||e.length<2||e.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(e)}function l(e){if(typeof globalThis.Buffer=="function"){let t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof globalThis.atob=="function"){let t=globalThis.atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r++)o[r]=t.charCodeAt(r)&255;return o}throw new a("Base64 decoding not supported in this environment.",n.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function c(e){if(typeof globalThis.Buffer=="function")return globalThis.Buffer.from(e).toString("base64");if(typeof globalThis.btoa=="function"){let o="";for(let r=0;r<e.length;r+=32768)o+=String.fromCharCode.apply(null,Array.from(e.subarray(r,r+32768)));return globalThis.btoa(o)}throw new a("Base64 encoding not supported in this environment.",n.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}export{f as a,s as b,l as c,c as d};
|
|
2
|
+
//# sourceMappingURL=chunk-OW6HV6QP.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var T=Object.defineProperty;var
|
|
2
|
-
${i.StackTrace||""}`:_optionalChain([i, 'optionalAccess', _17 => _17.error])&&(a=typeof i.error=="string"?i.error:JSON.stringify(i.error,null,2))}catch(i){c&&
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var T=Object.defineProperty;var M=(t,e,r)=>e in t?T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var z=(t,e)=>{for(var r in e)T(t,r,{get:e[r],enumerable:!0})};var f=(t,e,r)=>M(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED"},d= exports.d =class t extends Error{constructor(r,n="UNKNOWN_ERROR",o){super(r);f(this,"code");f(this,"statusCode");f(this,"context");f(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,u.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,u.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var b=class{debug(){}info(){}warn(){}error(){}},w=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},N=new b;function p(){return N}function C(t){N=t===null?new b:t}function k(){C(new w)}var E={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},A=new Set([502,503,504]);function D(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (E.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (E.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (E.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (E.retryOn429))}:E}function x(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function v(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function L(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",l)]),r()},t),l=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",l,{once:!0})])})}function U(t,e,r,n,o,l){let{status:c,statusText:s}=t,a={};t.headers.forEach(($,_)=>{a[_]=$});let i=l.trim(),R=i?` \u2014 ${i.slice(0,200)}${i.length>200?"\u2026":""}`:"",h={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:l||void 0,responseHeaders:a},g={401:{message:`HTTP ${c}: ${s}${R}`,code:u.AUTH_ERROR},403:{message:`HTTP ${c}: ${s}${R}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NETWORK_ERROR},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${R}`,code:u.NETWORK_ERROR},500:{message:`Server error: ${s}${R}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${s}${R}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${s}${R}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${s}${R}`,code:u.NETWORK_ERROR}}[c]||{message:`HTTP ${c}: ${s}${R}`,code:u.UNKNOWN_ERROR};throw new d(g.message,g.code,{statusCode:c,context:h})}function q(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function K(t){try{let e=new URL(t).host;return/^(localhost|127\.0\.0\.1|::1)(:\d+)?$/i.test(e)}catch (e2){return/(localhost|127\.0\.0\.1)/i.test(t)}}function P(t,e){let r={"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!K(e.serverUrl)&&p().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key is configured. Requests may fail or be rate-limited.`),r}function F(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function m(t,e){e&&p().debug(t)}function H(t,e){let r=[],n=()=>{};if(t&&r.push(t),e&&e>0)if(typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function")r.push(AbortSignal.timeout(e));else{let s=new AbortController,a=setTimeout(()=>s.abort(),e);n=()=>clearTimeout(a),r.push(s.signal)}if(r.length===0)return{signal:void 0,cleanup:n};if(r.length===1)return{signal:r[0],cleanup:n};if(typeof AbortSignal<"u"&&typeof AbortSignal.any=="function")return{signal:AbortSignal.any(r),cleanup:n};let o=new AbortController,l=()=>o.abort();for(let s of r){if(s.aborted){o.abort();break}s.addEventListener("abort",l,{once:!0})}let c=n;return n=()=>{c();for(let s of r)s.removeEventListener("abort",l)},{signal:o.signal,cleanup:n}}async function W(t,e,r,n,o,l,c){let s=Math.round(performance.now()-l);if(!t.ok){let a=await t.text();if(c&&(m(`\u274C Request [${r}] failed with HTTP ${t.status} in ${s}ms`,!0),m(` URL: ${e}`,!0),m(` Status: ${t.status} ${t.statusText}`,!0),a&&m(` Response body: ${a.substring(0,500)}${a.length>500?"...":""}`,!0)),t.status===500)try{let i=JSON.parse(a);if(_optionalChain([i, 'optionalAccess', _11 => _11.values])&&(i.errors||i.warnings))return c&&(m(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${s}ms`,!0),_optionalChain([i, 'access', _12 => _12.errors, 'optionalAccess', _13 => _13.length])>0&&m(` Errors: ${JSON.stringify(i.errors,null,2)}`,!0),_optionalChain([i, 'access', _14 => _14.warnings, 'optionalAccess', _15 => _15.length])>0&&m(` Warnings: ${JSON.stringify(i.warnings,null,2)}`,!0)),i;_optionalChain([i, 'optionalAccess', _16 => _16.Message])?a=`${i.ExceptionType?i.ExceptionType+": ":""}${i.Message}
|
|
2
|
+
${i.StackTrace||""}`:_optionalChain([i, 'optionalAccess', _17 => _17.error])&&(a=typeof i.error=="string"?i.error:JSON.stringify(i.error,null,2))}catch(i){c&&m(` Failed to parse error body as JSON: ${i}`,!0)}U(t,e,r,n,o,a)}m(`\u2705 Request [${r}] completed in ${s}ms`,c);try{return await t.json()}catch(a){throw new d("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:a instanceof Error?a:new Error(String(a))})}}async function V(t,e,r,n){let{signal:o,cleanup:l}=H(t.config.signal,t.config.timeoutMs),c=performance.now();try{let s=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((A.has(s.status)||e.retryOn429&&s.status===429)&&r<n-1){let h=_nullishCoalesce(x(s.headers.get("Retry-After")), () => (v(r,e)));return await s.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:h,cause:new d(`HTTP ${s.status} ${s.statusText} (will retry)`,u.NETWORK_ERROR,{statusCode:s.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await W(s,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,c,t.config.debug)}}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")){if(_optionalChain([t, 'access', _18 => _18.config, 'access', _19 => _19.signal, 'optionalAccess', _20 => _20.aborted])===!0)return{ok:!1,retry:!1,cause:new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:s})};let i=new d(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize}});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}if(s instanceof TypeError){let a=new d(`Network error: ${s.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:s});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:a}:{ok:!1,retry:!1,cause:a}}if(s instanceof d){let a=s.statusCode;return a!==void 0&&(A.has(a)||e.retryOn429&&a===429)&&r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:s}:{ok:!1,retry:!1,cause:s}}return{ok:!1,retry:!1,cause:new d(s instanceof Error?s.message:String(s),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:s instanceof Error?s:new Error(String(s))})}}finally{l()}}async function G(t,e,r){let n=F(),o=JSON.stringify(e),l=o.length,c=q(t,r.serverUrl),s=P(n,r),a=D(r.retry),i=a.attempts+1;if(r.debug){let y=(l/1024).toFixed(2),g=l>1e5?"\u26A0\uFE0F":"\u{1F680}";m(`${g} Starting compute request [${n}]: ${t} (${y}KB)`,!0)}let R={endpoint:t,body:o,requestSize:l,fullUrl:c,requestId:n,headers:s,config:r},h=null;for(let y=0;y<i;y++){let g=await V(R,a,y,i);if(g.ok)return g.value;if(!g.retry)throw g.cause;h=g.cause,r.debug&&m(`\u{1F501} Request [${n}] retrying after ${g.delayMs}ms (attempt ${y+2}/${i}): ${g.cause.message}`,!0);try{await L(g.delayMs,r.signal)}catch (e3){throw new d("Request aborted by caller",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:l},originalError:h})}}throw _nullishCoalesce(h, () => (new d("Unknown error after retries",u.UNKNOWN_ERROR,{context:{endpoint:t,requestId:n,requestSize:l}})))}var O=class{constructor(e,r){f(this,"serverUrl");f(this,"apiKey");f(this,"disposed",!1);f(this,"activeMonitors",new Set);f(this,"activeTimeouts",new Set);if(!_optionalChain([e, 'optionalAccess', _21 => _21.trim, 'call', _22 => _22()]))throw new d("serverUrl is required",u.INVALID_CONFIG,{context:{serverUrl:e}});if(!e.match(/^https?:\/\//))throw new d(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{serverUrl:e}});try{new URL(e)}catch(n){throw new d(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${n instanceof Error?n.message:String(n)}`,u.INVALID_CONFIG,{context:{serverUrl:e},originalError:n instanceof Error?n:void 0})}this.apiKey=r,this.serverUrl=e.replace(/\/+$/,"")}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}async isServerOnline(){this.ensureNotDisposed();let e=`${this.serverUrl}/healthcheck`,r={headers:this.buildHeaders(),method:"GET"};try{return(await fetch(e,r)).ok}catch(n){return p().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(){this.ensureNotDisposed();try{let e=await fetch(`${this.serverUrl}/activechildren`,{headers:this.buildHeaders()});if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch active children:",e.status),null;let r=await e.text(),n=parseInt(r.trim(),10);return isNaN(n)?(p().warn("[ComputeServerStats] Invalid active children response:",r),null):n}catch(e){return p().warn("[ComputeServerStats] Error fetching active children:",e),null}}async getVersion(){this.ensureNotDisposed();try{let e=await fetch(`${this.serverUrl}/version`,{headers:this.buildHeaders()});if(!e.ok)return p().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e4){return{rhino:r,compute:"",git_sha:null}}}catch(e){return p().warn("[ComputeServerStats] Error fetching version:",e),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren()]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}monitor(e,r=5e3){this.ensureNotDisposed();let n=!0,o=null;p().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let l=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let s=await this.getServerStats();if(!n||this.disposed)return;try{e(s)}catch(a){p().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(s){p().error("[ComputeServerStats] Failed to fetch stats during monitor:",s)}n&&!this.disposed&&(o=setTimeout(()=>{l()},r),this.activeTimeouts.add(o))}},c=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(c)};return this.activeMonitors.add(c),l(),c}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new d("ComputeServerStats has been disposed and cannot be used",u.INVALID_STATE,{context:{disposed:this.disposed}})}};function I(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s-_]+(.)?/g,o=t.trim();return o.charAt(0).toLowerCase()+o.slice(1).replace(n,(l,c)=>c?c.toUpperCase():"")}function S(t,e={}){return!t||typeof t!="object"?t:Array.isArray(t)?e.deep?t.map(r=>S(r,e)):t:Object.keys(t).reduce((r,n)=>{let o=I(n,{preserveSpaces:e.preserveSpaces}),l=t[n];return r[o]=e.deep?S(l,e):l,r},{})}exports.a = z; exports.b = f; exports.c = u; exports.d = d; exports.e = p; exports.f = C; exports.g = k; exports.h = G; exports.i = O; exports.j = I; exports.k = S;
|
|
3
|
+
//# sourceMappingURL=chunk-RBNF6MNH.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-RBNF6MNH.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,qrBAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CCI1N,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SACV,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAe,eAAA,CACfC,CAAAA,CACC,CACD,KAAA,CAAMF,CAAO,CAAA,CAVdG,CAAAA,CAAA,IAAA,CAAgB,MAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,YAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,SAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,eAAA,CAAA,CAQf,IAAA,CAAK,IAAA,CAAO,mBAAA,CACZ,IAAA,CAAK,IAAA,CAAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CASA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;AC+VlB","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-RBNF6MNH.cjs","sourcesContent":[null,"/**\n * Error types and codes for `@selvajs/compute`.\n */\n\nexport const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: string;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: string = 'UNKNOWN_ERROR',\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Validation Error Helpers\n\t// ============================================================================\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { ComputeConfig, RetryPolicy } from '../types';\nimport type {\n\tGrasshopperComputeConfig,\n\tGrasshopperComputeResponse,\n\tIoResponseSchema\n} from '@/features/grasshopper/types';\n\n/**\n * Valid endpoints for Rhino Compute (improved response type handling).\n */\nexport type Endpoint = 'grasshopper' | 'io' | string;\n\nexport type EndpointResponseMap = {\n\tgrasshopper: GrasshopperComputeResponse;\n\tio: IoResponseSchema;\n};\n\nexport type ComputeResponseFor<E extends string> = E extends keyof EndpointResponseMap\n\t? EndpointResponseMap[E]\n\t: unknown;\n\n// ============================================================================\n// Retry Policy\n// ============================================================================\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed\n\t\t? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}`\n\t\t: '';\n\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: errorBody || undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: string }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: { message: `Service unavailable: ${statusText}${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t503: { message: `Service unavailable: ${statusText}${bodyHint}`, code: ErrorCodes.NETWORK_ERROR },\n\t\t504: { message: `Service unavailable: ${statusText}${bodyHint}`, code: ErrorCodes.NETWORK_ERROR }\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\tthrow new RhinoComputeError(error.message, error.code, { statusCode: status, context });\n}\n\n// ============================================================================\n// Request Helpers\n// ============================================================================\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\tconst host = new URL(serverUrl).host;\n\t\treturn /^(localhost|127\\.0\\.0\\.1|::1)(:\\d+)?$/i.test(host);\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1)/i.test(serverUrl);\n\t}\n}\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (!config.apiKey && !isLocalhost(config.serverUrl)) {\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key is configured. Requests may fail or be rate-limited.`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst signals: AbortSignal[] = [];\n\tlet cleanup = () => {};\n\n\tif (callerSignal) signals.push(callerSignal);\n\n\tif (timeoutMs && timeoutMs > 0) {\n\t\tif (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {\n\t\t\tsignals.push(AbortSignal.timeout(timeoutMs));\n\t\t} else {\n\t\t\t// Fallback for runtimes without AbortSignal.timeout\n\t\t\tconst ctrl = new AbortController();\n\t\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\t\tcleanup = () => clearTimeout(id);\n\t\t\tsignals.push(ctrl.signal);\n\t\t}\n\t}\n\n\tif (signals.length === 0) return { signal: undefined, cleanup };\n\tif (signals.length === 1) return { signal: signals[0], cleanup };\n\n\tif (typeof AbortSignal !== 'undefined' && typeof (AbortSignal as any).any === 'function') {\n\t\treturn { signal: (AbortSignal as any).any(signals) as AbortSignal, cleanup };\n\t}\n\n\t// Manual composition fallback\n\tconst ctrl = new AbortController();\n\tconst onAbort = () => ctrl.abort();\n\tfor (const s of signals) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort();\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\tconst prevCleanup = cleanup;\n\tcleanup = () => {\n\t\tprevCleanup();\n\t\tfor (const s of signals) s.removeEventListener('abort', onAbort);\n\t};\n\treturn { signal: ctrl.signal, cleanup };\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse\n\t\tlet errorBody = await response.text();\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// If it's a raw exception from the server (like ArgumentException), include it in the error message\n\t\t\t\tif (parsed?.Message) {\n\t\t\t\t\terrorBody = `${parsed.ExceptionType ? parsed.ExceptionType + ': ' : ''}${parsed.Message}\\n${parsed.StackTrace || ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(response, fullUrl, requestId, requestSize, serverUrl, errorBody);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\n// ============================================================================\n// Single attempt\n// ============================================================================\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig | GrasshopperComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\tconst delayMs = retryAfterMs ?? backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Timeout — retryable up to attempts limit\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable\n\t\tif (error instanceof TypeError) {\n\t\t\tconst fatal = new RhinoComputeError(\n\t\t\t\t`Network error: ${error.message}`,\n\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t},\n\t\t\t\t\toriginalError: error\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\tconst retryable =\n\t\t\t\tstatus !== undefined &&\n\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * @typeParam E - The endpoint name (e.g., 'grasshopper', 'io'). Determines the response type for better type safety.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed according to the endpoint.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<E extends Endpoint>(\n\tendpoint: E,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig | GrasshopperComputeConfig\n): Promise<ComputeResponseFor<E>> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\tconst requestSize = body.length;\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\tlet lastError: RhinoComputeError | null = null;\n\n\tfor (let attempt = 0; attempt < totalAttempts; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as ComputeResponseFor<E>;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tlastError = result.cause;\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: lastError\n\t\t\t});\n\t\t}\n\t}\n\n\t// Exhausted retries — throw the last seen error\n\tthrow (\n\t\tlastError ??\n\t\tnew RhinoComputeError('Unknown error after retries', ErrorCodes.UNKNOWN_ERROR, {\n\t\t\tcontext: { endpoint, requestId, requestSize }\n\t\t})\n\t);\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkMZGKJZVPcjs = require('./chunk-MZGKJZVP.cjs');var _chunkVWOEUM7Ccjs = require('./chunk-VWOEUM7C.cjs');var _three = require('three'); var s = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var b = _interopRequireWildcard(_three); var M = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var V=new s.Vector3(0,0,1),P=(e,r,n,t)=>{switch(e){case"mm":return r;case"cm":return n;default:return t}},Ze= exports.a =function(e,r){let n=oe(r||{}),t=ae(n),o=de(n,e),a=me(e,n),i=he(o,e,n);le(t,n),ce(t,n),_optionalChain([n, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&ue(t,n);let c=n.events.enableEventHandlers!==!1?fe(e,t,o,i,n):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},l=e.parentElement,h=()=>l?{width:l.clientWidth,height:l.clientHeight}:{width:window.innerWidth,height:window.innerHeight},{animate:m,dispose:u}=se(a,t,o,i,h,n.events.onFrame);m();let E=_optionalChain([n, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||V;return t.up.set(E.x,E.y,E.z),{scene:t,camera:o,controls:i,renderer:a,dispose:()=>{u(),c.dispose(),i.dispose(),a.dispose(),t.traverse(d=>{d instanceof s.Mesh&&(_optionalChain([d, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(d.material)?d.material.forEach(H=>H.dispose()):_optionalChain([d, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},fitToView:c.fitToView,clearSelection:c.clearSelection}};function oe(e){let r=e.sceneScale||"m",t={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new s.Vector3(-t.cameraDistance,t.cameraDistance,t.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||t.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||t.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new s.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new s.Vector3(t.lightDistance,t.lightHeight,t.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new s.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new s.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||V,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||t.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new s.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||s.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||t.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.events, 'optionalAccess', _101 => _101.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.events, 'optionalAccess', _103 => _103.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _104 => _104.events, 'optionalAccess', _105 => _105.onReady]),onFrame:_optionalChain([e, 'access', _106 => _106.events, 'optionalAccess', _107 => _107.onFrame])}}}function ae(e){let r=new s.Scene,n=typeof e.environment.backgroundColor=="string"?new s.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=n||null,r}function ie(e,r,n,t,o=200){let a=e.position.clone(),i=r.target.clone(),c=performance.now(),l=m=>1-Math.pow(1-m,3),h=()=>{let m=performance.now()-c,u=l(Math.min(m/o,1));e.position.lerpVectors(a,n,u),r.target.lerpVectors(i,t,u),r.update(),u<1&&requestAnimationFrame(h)};requestAnimationFrame(h)}function se(e,r,n,t,o,a){let i=null,c=performance.now(),l=()=>{let{width:u,height:E}=o();if(u===0||E===0)return;let g=Math.min(window.devicePixelRatio,2),d=Math.round(u*g),H=Math.round(E*g);(e.domElement.width!==d||e.domElement.height!==H)&&(e.setPixelRatio(g),e.setSize(u,E,!1),n.aspect=u/E,n.updateProjectionMatrix())},h=function(){i=requestAnimationFrame(h);let u=performance.now(),E=(u-c)/1e3;c=u,l(),(t.enableDamping||t.autoRotate)&&t.update(),_optionalChain([a, 'optionalCall', _108 => _108(E)]),e.render(r,n)};return{animate:h,dispose:()=>{i!==null&&(cancelAnimationFrame(i),i=null)}}}function le(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(n){n.mapping=s.EquirectangularReflectionMapping,e.environment=n,r.environment.showEnvironment&&(e.background=n),_optionalChain([r, 'access', _109 => _109.events, 'access', _110 => _110.onReady, 'optionalCall', _111 => _111()])},void 0,function(n){_chunkVWOEUM7Ccjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",n),_optionalChain([r, 'access', _112 => _112.events, 'access', _113 => _113.onReady, 'optionalCall', _114 => _114()])}):_optionalChain([r, 'access', _115 => _115.events, 'access', _116 => _116.onReady, 'optionalCall', _117 => _117()])}function ce(e,r){let n=new s.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(n),r.lighting.enableSunlight){let t=new s.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&t.position.set(o.x,o.y,o.z),r.render.enableShadows){t.castShadow=!0;let a=P(r.sceneScale,.1,10,100);t.shadow.camera.left=-a,t.shadow.camera.right=a,t.shadow.camera.top=a,t.shadow.camera.bottom=-a;let i=P(r.sceneScale,.001,.1,.5),c=P(r.sceneScale,1,100,500);t.shadow.camera.near=i,t.shadow.camera.far=c,t.shadow.mapSize.width=r.render.shadowMapSize||2048,t.shadow.mapSize.height=r.render.shadowMapSize||2048,t.shadow.bias=-1e-4,t.shadow.normalBias=.02}e.add(t)}}function ue(e,r){let n=r.floor.size,t=new s.PlaneGeometry(n,n),o=typeof r.floor.color=="string"?new s.Color(r.floor.color):r.floor.color,a=new s.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:s.DoubleSide}),i=new s.Mesh(t,a);i.userData.id="floor",i.name="floor",i.rotation.x=-Math.PI/2,i.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function de(e,r){let n=r.parentElement,t=n?n.clientWidth:window.innerWidth,o=n?n.clientHeight:window.innerHeight,a=new s.PerspectiveCamera(e.camera.fov,t/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function me(e,r){let n=new s.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),t=e.parentElement,o=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight;return t&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),n.setSize(o,a,!1),n.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(n.shadowMap.enabled=!0,n.shadowMap.type=s.VSMShadowMap),n.toneMapping=r.render.toneMapping,n.toneMappingExposure=r.render.toneMappingExposure||1,n.outputColorSpace=s.SRGBColorSpace,n.sortObjects=!0,n}function fe(e,r,n,t,o){let a=new Set,i=new Map,c=new s.Raycaster,l=new s.Vector2,h=new s.Vector2,m=f=>{let p=f;for(;p;){if(!p.visible)return!1;p=p.parent}return!0},u=()=>{let f=new s.Box3;if(r.traverse(A=>{A.visible&&A.userData.id!=="floor"&&A instanceof s.Mesh&&f.expandByObject(A)}),f.isEmpty()){_chunkVWOEUM7Ccjs.e.call(void 0, ).warn("No objects to fit to view");return}let p=f.getCenter(new s.Vector3),T=f.getSize(new s.Vector3),v=Math.max(T.x,T.y,T.z),R=n.fov*(Math.PI/180),S=v/(2*Math.tan(R/2));S*=1.5;let O=n.position.clone().sub(t.target).normalize();n.position.copy(p.clone().add(O.multiplyScalar(S))),t.target.copy(p),t.update()},E=typeof o.events.selectionColor=="string"?new s.Color(o.events.selectionColor):o.events.selectionColor instanceof s.Color?o.events.selectionColor:new s.Color("#ff0000"),g=()=>{a.forEach(f=>{f instanceof s.Mesh&&i.has(f)&&(f.material=i.get(f),i.delete(f))}),a.clear()},d=f=>{h.set(f.clientX,f.clientY)},H=f=>{let p=new s.Vector2(f.clientX,f.clientY);if(h.distanceTo(p)>5)return;let T=e.getBoundingClientRect();l.x=(f.clientX-T.left)/T.width*2-1,l.y=-((f.clientY-T.top)/T.height)*2+1,c.setFromCamera(l,n);let v=c.intersectObjects(r.children,!0).filter(R=>m(R.object));if(v.length>0){let R=v[0].object;if(!a.has(R)){if(g(),a.add(R),R instanceof s.Mesh&&R.material instanceof s.Material){i.set(R,R.material);let S=R.material.clone();S.emissive=E.clone(),R.material=S}_optionalChain([o, 'access', _118 => _118.events, 'optionalAccess', _119 => _119.onObjectSelected, 'optionalCall', _120 => _120(R)]),R instanceof s.Mesh&&Object.keys(R.userData).length>0&&_optionalChain([o, 'access', _121 => _121.events, 'optionalAccess', _122 => _122.onMeshMetadataClicked, 'optionalCall', _123 => _123(R.userData)])}}else g(),_optionalChain([o, 'access', _124 => _124.events, 'optionalAccess', _125 => _125.onBackgroundClicked, 'optionalCall', _126 => _126({x:l.x,y:l.y})])},L=f=>{let p=e.getBoundingClientRect();l.x=(f.clientX-p.left)/p.width*2-1,l.y=-((f.clientY-p.top)/p.height)*2+1,c.setFromCamera(l,n);let T=c.intersectObjects(r.children,!0).filter(ee=>m(ee.object));if(T.length===0)return;let v=T[0].object;if(_optionalChain([o, 'access', _127 => _127.events, 'optionalAccess', _128 => _128.onMeshDoubleClicked, 'optionalCall', _129 => _129(v)]),!_optionalChain([o, 'access', _130 => _130.events, 'optionalAccess', _131 => _131.enableDoubleClickZoom]))return;let R=new s.Box3().setFromObject(v);if(R.isEmpty())return;let S=R.getCenter(new s.Vector3),O=R.getSize(new s.Vector3),A=Math.max(O.x,O.y,O.z),K=n.fov*(Math.PI/180),X=A/(2*Math.tan(K/2))*1.5,J=n.position.clone().sub(t.target).normalize(),Q=S.clone().add(J.multiplyScalar(X));ie(n,t,Q,S)},x=f=>{if(_optionalChain([o, 'access', _132 => _132.events, 'optionalAccess', _133 => _133.enableKeyboardControls]))switch(f.key.toLowerCase()){case"f":f.preventDefault(),u();break;case"escape":f.preventDefault(),g();break;case" ":f.preventDefault(),u();break}};return _optionalChain([o, 'access', _134 => _134.events, 'optionalAccess', _135 => _135.enableClickToFocus])&&(e.addEventListener("mousedown",d),e.addEventListener("click",H),e.addEventListener("dblclick",L)),_optionalChain([o, 'access', _136 => _136.events, 'optionalAccess', _137 => _137.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",d),e.removeEventListener("click",H),e.removeEventListener("dblclick",L),e.removeEventListener("keydown",x),g()},fitToView:u,clearSelection:g}}function he(e,r,n){let t=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=n.camera.target;return o&&t.target.set(o.x,o.y,o.z),t.enableDamping=n.controls.enableDamping||!1,t.dampingFactor=n.controls.dampingFactor||.05,t.autoRotate=n.controls.autoRotate||!1,t.autoRotateSpeed=n.controls.autoRotateSpeed||.5,t.enableZoom=_nullishCoalesce(n.controls.enableZoom, () => (!0)),t.enablePan=_nullishCoalesce(n.controls.enablePan, () => (!0)),t.minDistance=n.controls.minDistance||.001,t.maxDistance=n.controls.maxDistance||1/0,t.screenSpacePanning=!1,t.maxPolarAngle=Math.PI,t.update(),t}var B={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Xe(e,r,n,t,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let a=z(r),i=a.getCenter(new w.Vector3),c=a.getSize(new w.Vector3),l=Math.max(c.x,c.y,c.z);if(l/Math.min(c.x||1,c.y||1,c.z||1)>B.SCALE_RATIO_THRESHOLD||l>B.HUGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.TINY,n.far=l*B.FAR_PLANE_FACTOR.HUGE):l>B.LARGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.SMALL,n.far=l*B.FAR_PLANE_FACTOR.LARGE):(n.near=Math.max(.01,l*B.NEAR_PLANE_FACTOR.NORMAL),n.far=Math.max(2e3,l*B.FAR_PLANE_FACTOR.NORMAL)),n.updateProjectionMatrix(),o)t.minDistance=n.near*2,t.maxDistance=n.far*.9;else{let m=l*B.INITIAL_DISTANCE_MULTIPLIER;n.position.set(i.x+m*.8,i.y+m,i.z+m*1.2),t.target.copy(i),t.minDistance=n.near*2,t.maxDistance=n.far*.9,t.update()}}function N(e){if(!e||typeof e!="string")return _chunkVWOEUM7Ccjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let n=r.startsWith("#")?r:`#${r}`;return new w.Color(n)}catch (e2){return _chunkVWOEUM7Ccjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let n=r.split(",").map(t=>parseInt(t.trim(),10));if(n.length===3&&n.every(t=>!isNaN(t)&&t>=0&&t<=255))return new w.Color(n[0]/255,n[1]/255,n[2]/255)}try{return new w.Color(r.toLowerCase())}catch (e3){return _chunkVWOEUM7Ccjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function G(e,r){e.forEach(n=>{n.position.y-=r})}function z(e){let r=new w.Box3;return e.length===0||e.forEach(n=>{n.updateMatrixWorld(!0);let t=new w.Box3().setFromObject(n);r.union(t)}),r}function Ee(e){[...e.children].forEach(n=>{n.userData.id!=="floor"&&(n.traverse(t=>{if(!(t instanceof w.Mesh))return;_optionalChain([t, 'access', _138 => _138.geometry, 'optionalAccess', _139 => _139.dispose, 'call', _140 => _140()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(a=>{for(let i of Object.values(a))i instanceof w.Texture&&i.dispose();a.dispose()})}),n.removeFromParent())})}var Me={};_chunkVWOEUM7Ccjs.a.call(void 0, Me,{CONCRETE_MATERIAL:()=>ye,EMISSIVE_MATERIAL:()=>pe,GLASS_MATERIAL:()=>Re,METAL_MATERIAL:()=>ge,PLASTIC_MATERIAL:()=>be,RUBBER_MATERIAL:()=>Te,WOOD_MATERIAL:()=>we});var pe=new b.MeshPhysicalMaterial({color:0,emissive:new b.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ge=new b.MeshPhysicalMaterial({color:new b.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ye=new b.MeshPhysicalMaterial({color:new b.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),be=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Re=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new b.MeshPhysicalMaterial({color:new b.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new b.MeshPhysicalMaterial({color:new b.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var $=1096174675,W= exports.h =1,k= exports.i =1,Y=12,j=56;function U(e){let r=He(e),n=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Y)throw I("Blob too small to contain SLVA header.",{expectedBytes:Y,availableBytes:r.byteLength});let t=0,o=n.getUint32(t,!0);if(t+=4,o!==$)throw I(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${$.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=n.getUint32(t,!0);if(t+=4,a!==W)throw I(`Unsupported SLVA version: ${a}`,{expectedVersion:W,actualVersion:a});let i=n.getUint32(t,!0);if(t+=4,t+i>r.byteLength)throw I("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-t,offset:t});let c=r.subarray(t,t+i);t+=i;let l;try{l=JSON.parse(xe(c))}catch(A){throw I(`Failed to parse metadata JSON: ${A instanceof Error?A.message:String(A)}`,{metadataLen:i})}if(t+j>r.byteLength)throw I("Insufficient data to read geometry header.",{expectedBytes:j,availableBytes:r.byteLength-t,offset:t});let h=n.getUint32(t,!0);t+=4;let m=n.getFloat64(t,!0);t+=8;let u=n.getFloat64(t,!0);t+=8;let E=n.getFloat64(t,!0);t+=8;let g=n.getFloat64(t,!0);t+=8;let d=n.getFloat64(t,!0);t+=8;let H=n.getFloat64(t,!0);t+=8;let L=n.getUint32(t,!0);t+=4;let x=(h&k)!==0,C=L*3,p=C*(x?4:2);if(t+p>r.byteLength)throw I("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:r.byteLength-t,offset:t,useFloat32:x,vertexCount:L});let T=r.byteOffset+t,v=x?ve(r.buffer,T,C):Ce(r.buffer,T,C);if(t+=p,t+4>r.byteLength)throw I("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-t,offset:t});let R=n.getUint32(t,!0);t+=4;let S=R*4;if(t+S>r.byteLength)throw I("Insufficient data to read indices.",{expectedBytes:S,availableBytes:r.byteLength-t,offset:t,indexCount:R});let O=Se(r.buffer,r.byteOffset+t,R);return{metadata:l,flags:h,vertices:v,indices:O,origin:[m,u,E],scale:[g,d,H]}}function He(e){return typeof e=="string"?_chunkMZGKJZVPcjs.c.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function xe(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunkVWOEUM7Ccjs.d)("No UTF-8 decoder available in this environment.",_chunkVWOEUM7Ccjs.c.INVALID_STATE)}function Ce(e,r,n){if(n===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,n);let t=new Uint8Array(n*2);return t.set(new Uint8Array(e,r,n*2)),new Int16Array(t.buffer)}function ve(e,r,n){if(n===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Float32Array(t.buffer)}function Se(e,r,n){if(n===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Uint32Array(t.buffer)}function I(e,r){return new (0, _chunkVWOEUM7Ccjs.d)(e,_chunkVWOEUM7Ccjs.c.VALIDATION_ERROR,{context:r})}async function Z(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),a=o?performance.now():0,i=0;try{let c=performance.now(),l=JSON.parse(e);return i=performance.now()-c,await Ae(l,{mergeByMaterial:n,applyTransforms:t,debug:o,parseTime:i,perfStart:a})}catch(c){return _chunkVWOEUM7Ccjs.e.call(void 0, ).error("Error parsing mesh batch:",c),[]}}async function Ae(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1,parseTime:i=0,perfStart:c=a?performance.now():0}=_nullishCoalesce(r, () => ({}));try{let l=performance.now(),h=U(e.compressedData),m=performance.now()-l,u=a?Fe(e.compressedData):0;return q(h,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:m,perfStart:c,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return _chunkVWOEUM7Ccjs.e.call(void 0, ).error("Error parsing mesh batch object:",l),[]}}async function at(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1}=_nullishCoalesce(r, () => ({})),i=a?performance.now():0;try{let c=performance.now(),l=U(e),h=performance.now()-c,m=(e instanceof Uint8Array,e.byteLength);return q(l,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:0,decodeTime:h,perfStart:i,blobBytes:m})}catch(c){return _chunkVWOEUM7Ccjs.e.call(void 0, ).error("Error parsing mesh batch blob:",c),[]}}function q(e,r){let{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:c,perfStart:l,blobBytes:h,fallback:m}=r,u=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([m, 'optionalAccess', _141 => _141.materials]))), () => ([])),E=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([m, 'optionalAccess', _142 => _142.groups]))), () => ([])),g=_nullishCoalesce(e.metadata.sourceComponentId, () => (_optionalChain([m, 'optionalAccess', _143 => _143.sourceComponentId]))),d=(e.flags&k)!==0,H=d?Le(e.vertices,t):Be(e.vertices,e.origin,e.scale,t);if(a){let p=e.vertices.byteLength+e.indices.byteLength;_chunkVWOEUM7Ccjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Materials: ${u.length} | Groups: ${E.length}`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Format: ${d?"float32":"int16 quantized"}`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Blob: ${(h/1024/1024).toFixed(2)} MB | Geometry on wire: ${(p/1024/1024).toFixed(2)} MB`)}let L=performance.now(),x=u.map(Ie),C=[];for(let p of E)if(n&&p.meshes.length>1){let T=Oe(p,H,e.indices,x);T.userData.sourceComponentId=_nullishCoalesce(g, () => (null)),C.push(T)}else{let T=De(p,H,e.indices,x);for(let v of T)v.userData.sourceComponentId=_nullishCoalesce(g, () => (null));C.push(...T)}if(o!==1)for(let p of C)p.scale.set(o,o,o);let f=performance.now()-L;if(a){let p=performance.now()-l;_chunkVWOEUM7Ccjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Decode binary: ${c.toFixed(2)}ms`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Create Meshes: ${f.toFixed(2)}ms`),_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(` Total: ${p.toFixed(2)}ms`)}return Promise.resolve(C)}function Be(e,r,n,t){let o=new Float32Array(e.length),a=r[0],i=r[1],c=r[2],l=n[0],h=n[1],m=n[2];if(t)for(let u=0;u<e.length;u+=3){let E=a+(e[u]+32767)*l,g=i+(e[u+1]+32767)*h,d=c+(e[u+2]+32767)*m;o[u]=E,o[u+1]=d,o[u+2]=-g}else for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*l,o[u+1]=i+(e[u+1]+32767)*h,o[u+2]=c+(e[u+2]+32767)*m;return o}function Le(e,r){if(!r)return e;let n=new Float32Array(e.length);for(let t=0;t<e.length;t+=3){let o=e[t],a=e[t+1],i=e[t+2];n[t]=o,n[t+1]=i,n[t+2]=-a}return n}function Ie(e){let r=N(e.color);return new M.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:M.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Oe(e,r,n,t){let o=0,a=0;for(let d of e.meshes)o+=d.vertexCount,a+=d.indexCount;let i=new Float32Array(o*3),c=new Uint32Array(a),l=0,h=0;for(let d of e.meshes){let H=d.vertexStart*3,L=d.vertexCount*3;i.set(r.subarray(H,H+L),l*3);let x=n.subarray(d.indexStart,d.indexStart+d.indexCount),C=l-d.vertexStart;if(C===0)c.set(x,h);else for(let f=0;f<x.length;f++)c[h+f]=x[f]+C;l+=d.vertexCount,h+=d.indexCount}let m=new M.BufferGeometry;m.setAttribute("position",new M.BufferAttribute(i,3)),m.setIndex(new M.BufferAttribute(c,1)),m.computeVertexNormals();let u=new M.Mesh(m,t[e.materialId]),E=e.meshes[0],g=e.meshes.map(d=>d.name).filter(d=>d&&d.length>0);return u.name=g.length>0?g[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={name:u.name,layer:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _144 => _144.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _145 => _145.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _146 => _146.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(d=>({name:d.name,layer:d.layer,originalIndex:d.originalIndex}))},u}function De(e,r,n,t){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,c=a.vertexCount*3,l=r.slice(i,i+c),h=n.subarray(a.indexStart,a.indexStart+a.indexCount),m=new Uint32Array(h.length),u=a.vertexStart;for(let d=0;d<h.length;d++)m[d]=h[d]-u;let E=new M.BufferGeometry;E.setAttribute("position",new M.BufferAttribute(l,3)),E.setIndex(new M.BufferAttribute(m,1)),E.computeVertexNormals();let g=new M.Mesh(E,t[e.materialId]);g.name=a.name,g.userData={name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},g.castShadow=!0,g.receiveShadow=!0,o.push(g)}return o}function Fe(e){return Math.floor(e.length*3/4)}var Pe={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ze="Display";async function ut(e,r){let n=performance.now(),t=[],{allowScaling:o=!0,allowAutoPosition:a=!0,debug:i=!1,parsing:c={}}=_nullishCoalesce(r, () => ({}));try{let l=o?ke(e.modelunits):1;return await Ue(e,t,l,c,i),a&&Ve(t),t}catch(l){throw Ne(l,t),l}finally{i&&$e(n)}}function ke(e){return _nullishCoalesce(Pe[e], () => (1))}async function Ue(e,r,n,t,o){for(let a of e.values){let i=a.InnerTree;for(let c in i){let l=i[c];l&&await _e(l,r,n,t,o)}}}async function _e(e,r,n,t,o){for(let a of e)if(a.type.includes(ze)){let i={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...t},c=await Z(a.data,i);if(n!==1)for(let l of c)l.scale.set(n,n,n);r.push(...c),o&&_chunkVWOEUM7Ccjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes from batch`)}}function Ve(e){if(e.length===0)return;let n=z(e).min.y;G(e,n)}function Ne(e,r){_chunkVWOEUM7Ccjs.e.call(void 0, ).error("An unexpected error occurred:",e),Ge(r)}function Ge(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(n=>n.dispose()):r.material.dispose())}function $e(e){let r=performance.now()-e;_chunkVWOEUM7Ccjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = Ze; exports.b = Xe; exports.c = N; exports.d = G; exports.e = z; exports.f = Me; exports.g = $; exports.h = W; exports.i = k; exports.j = U; exports.k = Z; exports.l = Ae; exports.m = at; exports.n = Pe; exports.o = ut;
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkZRQRYG6Fcjs = require('./chunk-ZRQRYG6F.cjs');var _chunkRBNF6MNHcjs = require('./chunk-RBNF6MNH.cjs');var _three = require('three'); var s = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var b = _interopRequireWildcard(_three); var M = _interopRequireWildcard(_three);var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var V=new s.Vector3(0,0,1),P=(e,r,n,t)=>{switch(e){case"mm":return r;case"cm":return n;default:return t}},Ze= exports.a =function(e,r){let n=oe(r||{}),t=ae(n),o=de(n,e),a=me(e,n),i=he(o,e,n);le(t,n),ce(t,n),_optionalChain([n, 'access', _2 => _2.floor, 'optionalAccess', _3 => _3.enabled])&&ue(t,n);let c=n.events.enableEventHandlers!==!1?fe(e,t,o,i,n):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},l=e.parentElement,h=()=>l?{width:l.clientWidth,height:l.clientHeight}:{width:window.innerWidth,height:window.innerHeight},{animate:m,dispose:u}=se(a,t,o,i,h,n.events.onFrame);m();let E=_optionalChain([n, 'access', _4 => _4.environment, 'optionalAccess', _5 => _5.sceneUp])||V;return t.up.set(E.x,E.y,E.z),{scene:t,camera:o,controls:i,renderer:a,dispose:()=>{u(),c.dispose(),i.dispose(),a.dispose(),t.traverse(d=>{d instanceof s.Mesh&&(_optionalChain([d, 'access', _6 => _6.geometry, 'optionalAccess', _7 => _7.dispose, 'call', _8 => _8()]),Array.isArray(d.material)?d.material.forEach(H=>H.dispose()):_optionalChain([d, 'access', _9 => _9.material, 'optionalAccess', _10 => _10.dispose, 'call', _11 => _11()]))})},fitToView:c.fitToView,clearSelection:c.clearSelection}};function oe(e){let r=e.sceneScale||"m",t={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[r];return{sceneScale:r,camera:{position:_optionalChain([e, 'access', _12 => _12.camera, 'optionalAccess', _13 => _13.position])||new s.Vector3(-t.cameraDistance,t.cameraDistance,t.cameraDistance),fov:_optionalChain([e, 'access', _14 => _14.camera, 'optionalAccess', _15 => _15.fov])||20,near:_optionalChain([e, 'access', _16 => _16.camera, 'optionalAccess', _17 => _17.near])||t.near,far:_optionalChain([e, 'access', _18 => _18.camera, 'optionalAccess', _19 => _19.far])||t.far,target:_optionalChain([e, 'access', _20 => _20.camera, 'optionalAccess', _21 => _21.target])||new s.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.lighting, 'optionalAccess', _23 => _23.enableSunlight]), () => (!0)),sunlightIntensity:_optionalChain([e, 'access', _24 => _24.lighting, 'optionalAccess', _25 => _25.sunlightIntensity])||1,sunlightPosition:_optionalChain([e, 'access', _26 => _26.lighting, 'optionalAccess', _27 => _27.sunlightPosition])||new s.Vector3(t.lightDistance,t.lightHeight,t.lightDistance),ambientLightColor:_optionalChain([e, 'access', _28 => _28.lighting, 'optionalAccess', _29 => _29.ambientLightColor])||new s.Color(4210752),ambientLightIntensity:_optionalChain([e, 'access', _30 => _30.lighting, 'optionalAccess', _31 => _31.ambientLightIntensity])||1,sunlightColor:_optionalChain([e, 'access', _32 => _32.lighting, 'optionalAccess', _33 => _33.sunlightColor])||16777215},environment:{hdrPath:_optionalChain([e, 'access', _34 => _34.environment, 'optionalAccess', _35 => _35.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _36 => _36.environment, 'optionalAccess', _37 => _37.backgroundColor])||new s.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _38 => _38.environment, 'optionalAccess', _39 => _39.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _40 => _40.environment, 'optionalAccess', _41 => _41.sceneUp])||V,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _42 => _42.environment, 'optionalAccess', _43 => _43.showEnvironment]), () => (!1))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _44 => _44.floor, 'optionalAccess', _45 => _45.enabled]), () => (!1)),size:_optionalChain([e, 'access', _46 => _46.floor, 'optionalAccess', _47 => _47.size])||t.floorSize,color:_optionalChain([e, 'access', _48 => _48.floor, 'optionalAccess', _49 => _49.color])||new s.Color(8421504),roughness:_optionalChain([e, 'access', _50 => _50.floor, 'optionalAccess', _51 => _51.roughness])||.7,metalness:_optionalChain([e, 'access', _52 => _52.floor, 'optionalAccess', _53 => _53.metalness])||0,receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _54 => _54.floor, 'optionalAccess', _55 => _55.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _56 => _56.render, 'optionalAccess', _57 => _57.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _58 => _58.render, 'optionalAccess', _59 => _59.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.render, 'optionalAccess', _61 => _61.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _62 => _62.render, 'optionalAccess', _63 => _63.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_optionalChain([e, 'access', _64 => _64.render, 'optionalAccess', _65 => _65.toneMapping])||s.NeutralToneMapping,toneMappingExposure:_optionalChain([e, 'access', _66 => _66.render, 'optionalAccess', _67 => _67.toneMappingExposure])||1,preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _68 => _68.render, 'optionalAccess', _69 => _69.preserveDrawingBuffer]), () => (!1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.controls, 'optionalAccess', _71 => _71.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _72 => _72.controls, 'optionalAccess', _73 => _73.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.controls, 'optionalAccess', _75 => _75.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _76 => _76.controls, 'optionalAccess', _77 => _77.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _78 => _78.controls, 'optionalAccess', _79 => _79.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _80 => _80.controls, 'optionalAccess', _81 => _81.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _82 => _82.controls, 'optionalAccess', _83 => _83.minDistance])||t.minDistance,maxDistance:_optionalChain([e, 'access', _84 => _84.controls, 'optionalAccess', _85 => _85.maxDistance])||1/0},events:{onBackgroundClicked:_optionalChain([e, 'access', _86 => _86.events, 'optionalAccess', _87 => _87.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _88 => _88.events, 'optionalAccess', _89 => _89.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _90 => _90.events, 'optionalAccess', _91 => _91.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _92 => _92.events, 'optionalAccess', _93 => _93.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _94 => _94.events, 'optionalAccess', _95 => _95.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.events, 'optionalAccess', _97 => _97.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.events, 'optionalAccess', _99 => _99.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.events, 'optionalAccess', _101 => _101.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.events, 'optionalAccess', _103 => _103.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _104 => _104.events, 'optionalAccess', _105 => _105.onReady]),onFrame:_optionalChain([e, 'access', _106 => _106.events, 'optionalAccess', _107 => _107.onFrame])}}}function ae(e){let r=new s.Scene,n=typeof e.environment.backgroundColor=="string"?new s.Color(e.environment.backgroundColor):e.environment.backgroundColor;return r.background=n||null,r}function ie(e,r,n,t,o=200){let a=e.position.clone(),i=r.target.clone(),c=performance.now(),l=m=>1-Math.pow(1-m,3),h=()=>{let m=performance.now()-c,u=l(Math.min(m/o,1));e.position.lerpVectors(a,n,u),r.target.lerpVectors(i,t,u),r.update(),u<1&&requestAnimationFrame(h)};requestAnimationFrame(h)}function se(e,r,n,t,o,a){let i=null,c=performance.now(),l=()=>{let{width:u,height:E}=o();if(u===0||E===0)return;let g=Math.min(window.devicePixelRatio,2),d=Math.round(u*g),H=Math.round(E*g);(e.domElement.width!==d||e.domElement.height!==H)&&(e.setPixelRatio(g),e.setSize(u,E,!1),n.aspect=u/E,n.updateProjectionMatrix())},h=function(){i=requestAnimationFrame(h);let u=performance.now(),E=(u-c)/1e3;c=u,l(),(t.enableDamping||t.autoRotate)&&t.update(),_optionalChain([a, 'optionalCall', _108 => _108(E)]),e.render(r,n)};return{animate:h,dispose:()=>{i!==null&&(cancelAnimationFrame(i),i=null)}}}function le(e,r){r.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(r.environment.hdrPath||"/baseHDR.hdr",function(n){n.mapping=s.EquirectangularReflectionMapping,e.environment=n,r.environment.showEnvironment&&(e.background=n),_optionalChain([r, 'access', _109 => _109.events, 'access', _110 => _110.onReady, 'optionalCall', _111 => _111()])},void 0,function(n){_chunkRBNF6MNHcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",n),_optionalChain([r, 'access', _112 => _112.events, 'access', _113 => _113.onReady, 'optionalCall', _114 => _114()])}):_optionalChain([r, 'access', _115 => _115.events, 'access', _116 => _116.onReady, 'optionalCall', _117 => _117()])}function ce(e,r){let n=new s.AmbientLight(r.lighting.ambientLightColor,r.lighting.ambientLightIntensity);if(e.add(n),r.lighting.enableSunlight){let t=new s.DirectionalLight(_nullishCoalesce(r.lighting.sunlightColor, () => (16777215)),r.lighting.sunlightIntensity),o=r.lighting.sunlightPosition;if(o&&t.position.set(o.x,o.y,o.z),r.render.enableShadows){t.castShadow=!0;let a=P(r.sceneScale,.1,10,100);t.shadow.camera.left=-a,t.shadow.camera.right=a,t.shadow.camera.top=a,t.shadow.camera.bottom=-a;let i=P(r.sceneScale,.001,.1,.5),c=P(r.sceneScale,1,100,500);t.shadow.camera.near=i,t.shadow.camera.far=c,t.shadow.mapSize.width=r.render.shadowMapSize||2048,t.shadow.mapSize.height=r.render.shadowMapSize||2048,t.shadow.bias=-1e-4,t.shadow.normalBias=.02}e.add(t)}}function ue(e,r){let n=r.floor.size,t=new s.PlaneGeometry(n,n),o=typeof r.floor.color=="string"?new s.Color(r.floor.color):r.floor.color,a=new s.MeshStandardMaterial({color:o,roughness:r.floor.roughness,metalness:r.floor.metalness,side:s.DoubleSide}),i=new s.Mesh(t,a);i.userData.id="floor",i.name="floor",i.rotation.x=-Math.PI/2,i.position.y=0,r.floor.receiveShadow&&r.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function de(e,r){let n=r.parentElement,t=n?n.clientWidth:window.innerWidth,o=n?n.clientHeight:window.innerHeight,a=new s.PerspectiveCamera(e.camera.fov,t/o,e.camera.near,e.camera.far),i=e.camera.position;return i&&a.position.set(i.x,i.y,i.z),a}function me(e,r){let n=new s.WebGLRenderer({antialias:r.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:r.render.preserveDrawingBuffer,logarithmicDepthBuffer:!0}),t=e.parentElement,o=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight;return t&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),n.setSize(o,a,!1),n.setPixelRatio(r.render.pixelRatio||Math.min(window.devicePixelRatio,2)),r.render.enableShadows&&(n.shadowMap.enabled=!0,n.shadowMap.type=s.VSMShadowMap),n.toneMapping=r.render.toneMapping,n.toneMappingExposure=r.render.toneMappingExposure||1,n.outputColorSpace=s.SRGBColorSpace,n.sortObjects=!0,n}function fe(e,r,n,t,o){let a=new Set,i=new Map,c=new s.Raycaster,l=new s.Vector2,h=new s.Vector2,m=f=>{let p=f;for(;p;){if(!p.visible)return!1;p=p.parent}return!0},u=()=>{let f=new s.Box3;if(r.traverse(A=>{A.visible&&A.userData.id!=="floor"&&A instanceof s.Mesh&&f.expandByObject(A)}),f.isEmpty()){_chunkRBNF6MNHcjs.e.call(void 0, ).warn("No objects to fit to view");return}let p=f.getCenter(new s.Vector3),T=f.getSize(new s.Vector3),v=Math.max(T.x,T.y,T.z),R=n.fov*(Math.PI/180),S=v/(2*Math.tan(R/2));S*=1.5;let O=n.position.clone().sub(t.target).normalize();n.position.copy(p.clone().add(O.multiplyScalar(S))),t.target.copy(p),t.update()},E=typeof o.events.selectionColor=="string"?new s.Color(o.events.selectionColor):o.events.selectionColor instanceof s.Color?o.events.selectionColor:new s.Color("#ff0000"),g=()=>{a.forEach(f=>{f instanceof s.Mesh&&i.has(f)&&(f.material=i.get(f),i.delete(f))}),a.clear()},d=f=>{h.set(f.clientX,f.clientY)},H=f=>{let p=new s.Vector2(f.clientX,f.clientY);if(h.distanceTo(p)>5)return;let T=e.getBoundingClientRect();l.x=(f.clientX-T.left)/T.width*2-1,l.y=-((f.clientY-T.top)/T.height)*2+1,c.setFromCamera(l,n);let v=c.intersectObjects(r.children,!0).filter(R=>m(R.object));if(v.length>0){let R=v[0].object;if(!a.has(R)){if(g(),a.add(R),R instanceof s.Mesh&&R.material instanceof s.Material){i.set(R,R.material);let S=R.material.clone();S.emissive=E.clone(),R.material=S}_optionalChain([o, 'access', _118 => _118.events, 'optionalAccess', _119 => _119.onObjectSelected, 'optionalCall', _120 => _120(R)]),R instanceof s.Mesh&&Object.keys(R.userData).length>0&&_optionalChain([o, 'access', _121 => _121.events, 'optionalAccess', _122 => _122.onMeshMetadataClicked, 'optionalCall', _123 => _123(R.userData)])}}else g(),_optionalChain([o, 'access', _124 => _124.events, 'optionalAccess', _125 => _125.onBackgroundClicked, 'optionalCall', _126 => _126({x:l.x,y:l.y})])},L=f=>{let p=e.getBoundingClientRect();l.x=(f.clientX-p.left)/p.width*2-1,l.y=-((f.clientY-p.top)/p.height)*2+1,c.setFromCamera(l,n);let T=c.intersectObjects(r.children,!0).filter(ee=>m(ee.object));if(T.length===0)return;let v=T[0].object;if(_optionalChain([o, 'access', _127 => _127.events, 'optionalAccess', _128 => _128.onMeshDoubleClicked, 'optionalCall', _129 => _129(v)]),!_optionalChain([o, 'access', _130 => _130.events, 'optionalAccess', _131 => _131.enableDoubleClickZoom]))return;let R=new s.Box3().setFromObject(v);if(R.isEmpty())return;let S=R.getCenter(new s.Vector3),O=R.getSize(new s.Vector3),A=Math.max(O.x,O.y,O.z),K=n.fov*(Math.PI/180),X=A/(2*Math.tan(K/2))*1.5,J=n.position.clone().sub(t.target).normalize(),Q=S.clone().add(J.multiplyScalar(X));ie(n,t,Q,S)},x=f=>{if(_optionalChain([o, 'access', _132 => _132.events, 'optionalAccess', _133 => _133.enableKeyboardControls]))switch(f.key.toLowerCase()){case"f":f.preventDefault(),u();break;case"escape":f.preventDefault(),g();break;case" ":f.preventDefault(),u();break}};return _optionalChain([o, 'access', _134 => _134.events, 'optionalAccess', _135 => _135.enableClickToFocus])&&(e.addEventListener("mousedown",d),e.addEventListener("click",H),e.addEventListener("dblclick",L)),_optionalChain([o, 'access', _136 => _136.events, 'optionalAccess', _137 => _137.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",d),e.removeEventListener("click",H),e.removeEventListener("dblclick",L),e.removeEventListener("keydown",x),g()},fitToView:u,clearSelection:g}}function he(e,r,n){let t=new (0, _OrbitControlsjs.OrbitControls)(e,r),o=n.camera.target;return o&&t.target.set(o.x,o.y,o.z),t.enableDamping=n.controls.enableDamping||!1,t.dampingFactor=n.controls.dampingFactor||.05,t.autoRotate=n.controls.autoRotate||!1,t.autoRotateSpeed=n.controls.autoRotateSpeed||.5,t.enableZoom=_nullishCoalesce(n.controls.enableZoom, () => (!0)),t.enablePan=_nullishCoalesce(n.controls.enablePan, () => (!0)),t.minDistance=n.controls.minDistance||.001,t.maxDistance=n.controls.maxDistance||1/0,t.screenSpacePanning=!1,t.maxPolarAngle=Math.PI,t.update(),t}var B={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function Xe(e,r,n,t,o){if(Ee(e),r.length===0)return;r.forEach(m=>{e.add(m)});let a=z(r),i=a.getCenter(new w.Vector3),c=a.getSize(new w.Vector3),l=Math.max(c.x,c.y,c.z);if(l/Math.min(c.x||1,c.y||1,c.z||1)>B.SCALE_RATIO_THRESHOLD||l>B.HUGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.TINY,n.far=l*B.FAR_PLANE_FACTOR.HUGE):l>B.LARGE_THRESHOLD?(n.near=l*B.NEAR_PLANE_FACTOR.SMALL,n.far=l*B.FAR_PLANE_FACTOR.LARGE):(n.near=Math.max(.01,l*B.NEAR_PLANE_FACTOR.NORMAL),n.far=Math.max(2e3,l*B.FAR_PLANE_FACTOR.NORMAL)),n.updateProjectionMatrix(),o)t.minDistance=n.near*2,t.maxDistance=n.far*.9;else{let m=l*B.INITIAL_DISTANCE_MULTIPLIER;n.position.set(i.x+m*.8,i.y+m,i.z+m*1.2),t.target.copy(i),t.minDistance=n.near*2,t.maxDistance=n.far*.9,t.update()}}function N(e){if(!e||typeof e!="string")return _chunkRBNF6MNHcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new w.Color(16777215);let r=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(r))try{let n=r.startsWith("#")?r:`#${r}`;return new w.Color(n)}catch (e2){return _chunkRBNF6MNHcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new w.Color(16777215)}if(r.includes(",")){let n=r.split(",").map(t=>parseInt(t.trim(),10));if(n.length===3&&n.every(t=>!isNaN(t)&&t>=0&&t<=255))return new w.Color(n[0]/255,n[1]/255,n[2]/255)}try{return new w.Color(r.toLowerCase())}catch (e3){return _chunkRBNF6MNHcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new w.Color(16777215)}}function G(e,r){e.forEach(n=>{n.position.y-=r})}function z(e){let r=new w.Box3;return e.length===0||e.forEach(n=>{n.updateMatrixWorld(!0);let t=new w.Box3().setFromObject(n);r.union(t)}),r}function Ee(e){[...e.children].forEach(n=>{n.userData.id!=="floor"&&(n.traverse(t=>{if(!(t instanceof w.Mesh))return;_optionalChain([t, 'access', _138 => _138.geometry, 'optionalAccess', _139 => _139.dispose, 'call', _140 => _140()]),(Array.isArray(t.material)?t.material:[t.material]).forEach(a=>{for(let i of Object.values(a))i instanceof w.Texture&&i.dispose();a.dispose()})}),n.removeFromParent())})}var Me={};_chunkRBNF6MNHcjs.a.call(void 0, Me,{CONCRETE_MATERIAL:()=>ye,EMISSIVE_MATERIAL:()=>pe,GLASS_MATERIAL:()=>Re,METAL_MATERIAL:()=>ge,PLASTIC_MATERIAL:()=>be,RUBBER_MATERIAL:()=>Te,WOOD_MATERIAL:()=>we});var pe=new b.MeshPhysicalMaterial({color:0,emissive:new b.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ge=new b.MeshPhysicalMaterial({color:new b.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),ye=new b.MeshPhysicalMaterial({color:new b.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:.5,depthTest:!0,polygonOffset:!0,side:b.FrontSide,dithering:!0}),be=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Re=new b.MeshPhysicalMaterial({color:new b.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,opacity:.3,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:b.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Te=new b.MeshPhysicalMaterial({color:new b.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),we=new b.MeshPhysicalMaterial({color:new b.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:b.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});var $=1096174675,W= exports.h =1,k= exports.i =1,Y=12,j=56;function U(e){let r=He(e),n=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.byteLength<Y)throw I("Blob too small to contain SLVA header.",{expectedBytes:Y,availableBytes:r.byteLength});let t=0,o=n.getUint32(t,!0);if(t+=4,o!==$)throw I(`Invalid SLVA magic: 0x${o.toString(16)}`,{expectedMagic:`0x${$.toString(16)}`,actualMagic:`0x${o.toString(16)}`});let a=n.getUint32(t,!0);if(t+=4,a!==W)throw I(`Unsupported SLVA version: ${a}`,{expectedVersion:W,actualVersion:a});let i=n.getUint32(t,!0);if(t+=4,t+i>r.byteLength)throw I("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:r.byteLength-t,offset:t});let c=r.subarray(t,t+i);t+=i;let l;try{l=JSON.parse(xe(c))}catch(A){throw I(`Failed to parse metadata JSON: ${A instanceof Error?A.message:String(A)}`,{metadataLen:i})}if(t+j>r.byteLength)throw I("Insufficient data to read geometry header.",{expectedBytes:j,availableBytes:r.byteLength-t,offset:t});let h=n.getUint32(t,!0);t+=4;let m=n.getFloat64(t,!0);t+=8;let u=n.getFloat64(t,!0);t+=8;let E=n.getFloat64(t,!0);t+=8;let g=n.getFloat64(t,!0);t+=8;let d=n.getFloat64(t,!0);t+=8;let H=n.getFloat64(t,!0);t+=8;let L=n.getUint32(t,!0);t+=4;let x=(h&k)!==0,C=L*3,p=C*(x?4:2);if(t+p>r.byteLength)throw I("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:r.byteLength-t,offset:t,useFloat32:x,vertexCount:L});let T=r.byteOffset+t,v=x?ve(r.buffer,T,C):Ce(r.buffer,T,C);if(t+=p,t+4>r.byteLength)throw I("Insufficient data to read index count.",{expectedBytes:4,availableBytes:r.byteLength-t,offset:t});let R=n.getUint32(t,!0);t+=4;let S=R*4;if(t+S>r.byteLength)throw I("Insufficient data to read indices.",{expectedBytes:S,availableBytes:r.byteLength-t,offset:t,indexCount:R});let O=Se(r.buffer,r.byteOffset+t,R);return{metadata:l,flags:h,vertices:v,indices:O,origin:[m,u,E],scale:[g,d,H]}}function He(e){return typeof e=="string"?_chunkZRQRYG6Fcjs.c.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function xe(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunkRBNF6MNHcjs.d)("No UTF-8 decoder available in this environment.",_chunkRBNF6MNHcjs.c.INVALID_STATE)}function Ce(e,r,n){if(n===0)return new Int16Array(0);if(r%2===0)return new Int16Array(e,r,n);let t=new Uint8Array(n*2);return t.set(new Uint8Array(e,r,n*2)),new Int16Array(t.buffer)}function ve(e,r,n){if(n===0)return new Float32Array(0);if(r%4===0)return new Float32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Float32Array(t.buffer)}function Se(e,r,n){if(n===0)return new Uint32Array(0);if(r%4===0)return new Uint32Array(e,r,n);let t=new Uint8Array(n*4);return t.set(new Uint8Array(e,r,n*4)),new Uint32Array(t.buffer)}function I(e,r){return new (0, _chunkRBNF6MNHcjs.d)(e,_chunkRBNF6MNHcjs.c.VALIDATION_ERROR,{context:r})}async function Z(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,debug:o=!1}=_nullishCoalesce(r, () => ({})),a=o?performance.now():0,i=0;try{let c=performance.now(),l=JSON.parse(e);return i=performance.now()-c,await Ae(l,{mergeByMaterial:n,applyTransforms:t,debug:o,parseTime:i,perfStart:a})}catch(c){return _chunkRBNF6MNHcjs.e.call(void 0, ).error("Error parsing mesh batch:",c),[]}}async function Ae(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1,parseTime:i=0,perfStart:c=a?performance.now():0}=_nullishCoalesce(r, () => ({}));try{let l=performance.now(),h=U(e.compressedData),m=performance.now()-l,u=a?Fe(e.compressedData):0;return q(h,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:m,perfStart:c,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}catch(l){return _chunkRBNF6MNHcjs.e.call(void 0, ).error("Error parsing mesh batch object:",l),[]}}async function at(e,r){let{mergeByMaterial:n=!0,applyTransforms:t=!0,scaleFactor:o=1,debug:a=!1}=_nullishCoalesce(r, () => ({})),i=a?performance.now():0;try{let c=performance.now(),l=U(e),h=performance.now()-c,m=(e instanceof Uint8Array,e.byteLength);return q(l,{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:0,decodeTime:h,perfStart:i,blobBytes:m})}catch(c){return _chunkRBNF6MNHcjs.e.call(void 0, ).error("Error parsing mesh batch blob:",c),[]}}function q(e,r){let{mergeByMaterial:n,applyTransforms:t,scaleFactor:o,debug:a,parseTime:i,decodeTime:c,perfStart:l,blobBytes:h,fallback:m}=r,u=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([m, 'optionalAccess', _141 => _141.materials]))), () => ([])),E=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([m, 'optionalAccess', _142 => _142.groups]))), () => ([])),g=_nullishCoalesce(e.metadata.sourceComponentId, () => (_optionalChain([m, 'optionalAccess', _143 => _143.sourceComponentId]))),d=(e.flags&k)!==0,H=d?Le(e.vertices,t):Be(e.vertices,e.origin,e.scale,t);if(a){let p=e.vertices.byteLength+e.indices.byteLength;_chunkRBNF6MNHcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Materials: ${u.length} | Groups: ${E.length}`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Format: ${d?"float32":"int16 quantized"}`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Blob: ${(h/1024/1024).toFixed(2)} MB | Geometry on wire: ${(p/1024/1024).toFixed(2)} MB`)}let L=performance.now(),x=u.map(Ie),C=[];for(let p of E)if(n&&p.meshes.length>1){let T=Oe(p,H,e.indices,x);T.userData.sourceComponentId=_nullishCoalesce(g, () => (null)),C.push(T)}else{let T=De(p,H,e.indices,x);for(let v of T)v.userData.sourceComponentId=_nullishCoalesce(g, () => (null));C.push(...T)}if(o!==1)for(let p of C)p.scale.set(o,o,o);let f=performance.now()-L;if(a){let p=performance.now()-l;_chunkRBNF6MNHcjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Decode binary: ${c.toFixed(2)}ms`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Create Meshes: ${f.toFixed(2)}ms`),_chunkRBNF6MNHcjs.e.call(void 0, ).debug(` Total: ${p.toFixed(2)}ms`)}return Promise.resolve(C)}function Be(e,r,n,t){let o=new Float32Array(e.length),a=r[0],i=r[1],c=r[2],l=n[0],h=n[1],m=n[2];if(t)for(let u=0;u<e.length;u+=3){let E=a+(e[u]+32767)*l,g=i+(e[u+1]+32767)*h,d=c+(e[u+2]+32767)*m;o[u]=E,o[u+1]=d,o[u+2]=-g}else for(let u=0;u<e.length;u+=3)o[u]=a+(e[u]+32767)*l,o[u+1]=i+(e[u+1]+32767)*h,o[u+2]=c+(e[u+2]+32767)*m;return o}function Le(e,r){if(!r)return e;let n=new Float32Array(e.length);for(let t=0;t<e.length;t+=3){let o=e[t],a=e[t+1],i=e[t+2];n[t]=o,n[t+1]=i,n[t+2]=-a}return n}function Ie(e){let r=N(e.color);return new M.MeshPhysicalMaterial({color:r,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,side:M.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0})}function Oe(e,r,n,t){let o=0,a=0;for(let d of e.meshes)o+=d.vertexCount,a+=d.indexCount;let i=new Float32Array(o*3),c=new Uint32Array(a),l=0,h=0;for(let d of e.meshes){let H=d.vertexStart*3,L=d.vertexCount*3;i.set(r.subarray(H,H+L),l*3);let x=n.subarray(d.indexStart,d.indexStart+d.indexCount),C=l-d.vertexStart;if(C===0)c.set(x,h);else for(let f=0;f<x.length;f++)c[h+f]=x[f]+C;l+=d.vertexCount,h+=d.indexCount}let m=new M.BufferGeometry;m.setAttribute("position",new M.BufferAttribute(i,3)),m.setIndex(new M.BufferAttribute(c,1)),m.computeVertexNormals();let u=new M.Mesh(m,t[e.materialId]),E=e.meshes[0],g=e.meshes.map(d=>d.name).filter(d=>d&&d.length>0);return u.name=g.length>0?g[0]:`merged_material_${e.materialId}`,u.castShadow=!0,u.receiveShadow=!0,u.userData={name:u.name,layer:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _144 => _144.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _145 => _145.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([E, 'optionalAccess', _146 => _146.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(d=>({name:d.name,layer:d.layer,originalIndex:d.originalIndex}))},u}function De(e,r,n,t){let o=[];for(let a of e.meshes){let i=a.vertexStart*3,c=a.vertexCount*3,l=r.slice(i,i+c),h=n.subarray(a.indexStart,a.indexStart+a.indexCount),m=new Uint32Array(h.length),u=a.vertexStart;for(let d=0;d<h.length;d++)m[d]=h[d]-u;let E=new M.BufferGeometry;E.setAttribute("position",new M.BufferAttribute(l,3)),E.setIndex(new M.BufferAttribute(m,1)),E.computeVertexNormals();let g=new M.Mesh(E,t[e.materialId]);g.name=a.name,g.userData={name:a.name,layer:_nullishCoalesce(a.layer, () => ("")),originalIndex:a.originalIndex,metadata:_nullishCoalesce(a.metadata, () => ({}))},g.castShadow=!0,g.receiveShadow=!0,o.push(g)}return o}function Fe(e){return Math.floor(e.length*3/4)}var Pe={Millimeters:1/1e3,Centimeters:1/100,Meters:1,Inches:1/39.37,Feet:1/3.28084},ze="Display";async function ut(e,r){let n=performance.now(),t=[],{allowScaling:o=!0,allowAutoPosition:a=!0,debug:i=!1,parsing:c={}}=_nullishCoalesce(r, () => ({}));try{let l=o?ke(e.modelunits):1;return await Ue(e,t,l,c,i),a&&Ve(t),t}catch(l){throw Ne(l,t),l}finally{i&&$e(n)}}function ke(e){return _nullishCoalesce(Pe[e], () => (1))}async function Ue(e,r,n,t,o){for(let a of e.values){let i=a.InnerTree;for(let c in i){let l=i[c];l&&await _e(l,r,n,t,o)}}}async function _e(e,r,n,t,o){for(let a of e)if(a.type.includes(ze)){let i={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...t},c=await Z(a.data,i);if(n!==1)for(let l of c)l.scale.set(n,n,n);r.push(...c),o&&_chunkRBNF6MNHcjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes from batch`)}}function Ve(e){if(e.length===0)return;let n=z(e).min.y;G(e,n)}function Ne(e,r){_chunkRBNF6MNHcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Ge(r)}function Ge(e){for(let r of e)r.geometry&&r.geometry.dispose(),r.material&&(Array.isArray(r.material)?r.material.forEach(n=>n.dispose()):r.material.dispose())}function $e(e){let r=performance.now()-e;_chunkRBNF6MNHcjs.e.call(void 0, ).info("Time to process meshes:",`${r.toFixed(2)}ms`)}exports.a = Ze; exports.b = Xe; exports.c = N; exports.d = G; exports.e = z; exports.f = Me; exports.g = $; exports.h = W; exports.i = k; exports.j = U; exports.k = Z; exports.l = Ae; exports.m = at; exports.n = Pe; exports.o = ut;
|
|
2
|
+
//# sourceMappingURL=chunk-SVEXPGHW.cjs.map
|