iflow-engine-base 2.1.0 → 2.1.2

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.
@@ -1,4 +1,4 @@
1
- (function(_t,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],_):(_t=typeof globalThis<"u"?globalThis:_t||self,_(_t.BimEngineSDK={},_t.THREE))})(this,(function(_t,_){"use strict";function Uo(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const S=Uo(_);class Vo{engine;scene;constructor(e){this.engine=e,this.scene=new S.Scene;let t=new S.Group;t.name="groupEdge",this.scene.add(t)}}class jo{engine;perspectiveCamera;orthographicCamera;constructor(e){this.engine=e,this.perspectiveCamera=new S.PerspectiveCamera(60,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,n=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new S.OrthographicCamera(t*n/-2,t*n/2,t/2,t/-2,.1,1e3)}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const e=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const n of t.passes)n.camera!==void 0&&(n.camera=e)}switchToPerspectiveCamera(){if(!this.engine.controls)return;const e=this.engine.camera.position.clone(),t=this.engine.controls.target.clone();this.engine.camera=this.perspectiveCamera,this.engine.scene.camera=this.perspectiveCamera,this.perspectiveCamera.position.copy(e),this.perspectiveCamera.lookAt(t),this.engine.controlModule.orbitControls.object=this.perspectiveCamera,this.engine.controlModule.firstPersonControls.camera=this.perspectiveCamera,this.updateComposerCamera(),this.perspectiveCamera.updateProjectionMatrix(),this.perspectiveCamera.updateMatrixWorld()}switchToOrthographicCamera(){if(!this.engine.controls)return;const e=this.engine.camera.position.clone(),t=this.engine.controls.target.clone();this.engine.camera=this.orthographicCamera,this.engine.scene.camera=this.orthographicCamera,this.orthographicCamera.position.copy(e),this.orthographicCamera.lookAt(t),this.engine.controlModule.orbitControls.object=this.orthographicCamera,this.engine.controlModule.firstPersonControls.camera=this.orthographicCamera,this.updateComposerCamera(),this.orthographicCamera.updateProjectionMatrix(),this.orthographicCamera.updateMatrixWorld()}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const e=this.engine.camera,t=this.getCameraType(),n={type:t,position:{x:e.position.x,y:e.position.y,z:e.position.z},rotation:{x:e.rotation.x,y:e.rotation.y,z:e.rotation.z},quaternion:{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w}};return this.engine.controls&&this.engine.controls.target&&(n.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z}),t==="orthographic"&&(n.zoom=e.zoom),n}restoreCameraPose(e){this.getCameraType()!==e.type&&(e.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const n=this.engine.camera;n.position.set(e.position.x,e.position.y,e.position.z),e.quaternion?n.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e.target&&this.engine.controls&&this.engine.controls.target&&this.engine.controls.target.set(e.target.x,e.target.y,e.target.z),e.type==="orthographic"&&e.zoom!==void 0&&(n.zoom=e.zoom,n.updateProjectionMatrix()),n.updateMatrix(),n.updateMatrixWorld(!0),this.engine.controls&&this.engine.controls.update&&this.engine.controls.update()}}class Go{engine;deviceType;constructor(e){this.engine=e,this.deviceType=this.detectDeviceType()}detectDeviceType(){const e=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,n=e.some(c=>c.test(t)),i="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,s=globalThis.screen.width,r=globalThis.screen.height,a=s<=768||r<=768,h=(globalThis.devicePixelRatio||1)>=2;return n||i&&a||i&&h?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}class Wo{engine;renderer;constructor(e){this.engine=e,this.renderer=null}createRenderer(){const{width:e,height:t}=this.engine.deviceModule.getContainerSize();return this.renderer=new S.WebGLRenderer({alpha:!0,premultipliedAlpha:!1,stencil:!0}),this.renderer.setClearColor(0,0),this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=S.PCFSoftShadowMap,this.renderer.localClippingEnabled=!0,this.renderer.outputColorSpace=S.SRGBColorSpace,this.engine.container.appendChild(this.renderer.domElement),this.renderer}disposeRenderer(){this.renderer?.dispose()}}const Es={type:"change"},Si={type:"start"},Bs={type:"end"},Mn=new _.Ray,Os=new _.Plane,Xo=Math.cos(70*_.MathUtils.DEG2RAD),ve=new _.Vector3,Oe=2*Math.PI,de={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Ai=1e-6;class Zo extends _.Controls{constructor(e,t,n=null){super(t,n),this.engine=e,this.state=de.NONE,this.target=new _.Vector3,this.cursor=new _.Vector3,this.origin=new _.Vector3(0,0,0),this.showOriginIcon=!0,this.originPosition={x:0,y:0},this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:_.MOUSE.ROTATE,MIDDLE:_.MOUSE.DOLLY,RIGHT:_.MOUSE.PAN},this.touches={ONE:_.TOUCH.ROTATE,TWO:_.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new _.Vector3,this._lastQuaternion=new _.Quaternion,this._lastTargetPosition=new _.Vector3,this._quat=new _.Quaternion().setFromUnitVectors(t.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new _.Spherical,this._sphericalDelta=new _.Spherical,this._scale=1,this._panOffset=new _.Vector3,this._rotateStart=new _.Vector2,this._rotateEnd=new _.Vector2,this._rotateDelta=new _.Vector2,this._panStart=new _.Vector2,this._panEnd=new _.Vector2,this._panDelta=new _.Vector2,this._dollyStart=new _.Vector2,this._dollyEnd=new _.Vector2,this._dollyDelta=new _.Vector2,this._dollyDirection=new _.Vector3,this._mouse=new _.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Ko.bind(this),this._onPointerDown=qo.bind(this),this._onPointerUp=Yo.bind(this),this._onContextMenu=na.bind(this),this._onMouseWheel=Jo.bind(this),this._onKeyDown=Qo.bind(this),this._onTouchStart=ea.bind(this),this._onTouchMove=ta.bind(this),this._onMouseDown=$o.bind(this),this._onMouseMove=Ho.bind(this),this._interceptControlDown=ia.bind(this),this._interceptControlUp=sa.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Es),this.update(),this.state=de.NONE}update(e=null){this.engine&&this.engine.interactionManager&&this.engine.interactionManager.origin&&this.origin.copy(this.engine.interactionManager.origin);const t=this.object.position;ve.copy(t).sub(this.target),ve.applyQuaternion(this._quat),this._spherical.setFromVector3(ve),this.autoRotate&&this.state===de.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=Oe:n>Math.PI&&(n-=Oe),i<-Math.PI?i+=Oe:i>Math.PI&&(i-=Oe),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=r!=this._spherical.radius}if(ve.setFromSpherical(this._spherical),ve.applyQuaternion(this._quatInverse),this.engine&&this.engine.deviceType==="PC"){const r=new _.Vector3;if(r.copy(this.origin).sub(this.target),r.lengthSq()>1e-4&&(this._sphericalDelta.theta!==0||this._sphericalDelta.phi!==0)){const l=this.enableDamping?this.dampingFactor*3:1,h=new _.Vector3(0,1,0),c=new _.Vector3;this.object.getWorldDirection(c);const d=c.clone().cross(h).normalize(),m=new _.Vector3().copy(this.object.position).sub(this.origin);m.applyAxisAngle(h,Math.PI*this._sphericalDelta.theta*l),m.applyAxisAngle(d,Math.PI*this._sphericalDelta.phi*l),t.copy(this.origin).add(m);const p=new _.Vector3().copy(this.target).sub(this.origin);p.applyAxisAngle(h,Math.PI*this._sphericalDelta.theta*l),p.applyAxisAngle(d,Math.PI*this._sphericalDelta.phi*l),this.target.copy(this.origin).add(p)}else if(this._panOffset.lengthSq()===0&&this._sphericalDelta.phi===0&&this._sphericalDelta.theta===0){if(this._scale!==1){const l=new _.Vector3;this.object.getWorldDirection(l);const h=this._spherical.radius*.05*(this._scale-1);t.add(l.multiplyScalar(h))}}else t.copy(this.target).add(ve);this.object.lookAt(this.target)}else t.copy(this.target).add(ve),this.object.lookAt(this.target);if(this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const a=ve.length();r=this._clampDistance(a*this._scale);const l=a-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){const a=new _.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;const h=new _.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),r=ve.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(Mn.origin.copy(this.object.position),Mn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Mn.direction))<Xo?this.object.lookAt(this.target):(Os.setFromNormalAndCoplanarPoint(this.object.up,this.target),Mn.intersectPlane(Os,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>Ai||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Ai||this._lastTargetPosition.distanceToSquared(this.target)>Ai?(this.dispatchEvent(Es),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Oe/60*this.autoRotateSpeed*e:Oe/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){ve.setFromMatrixColumn(t,0),ve.multiplyScalar(-e),this._panOffset.add(ve)}_panUp(e,t){this.screenSpacePanning===!0?ve.setFromMatrixColumn(t,1):(ve.setFromMatrixColumn(t,0),ve.crossVectors(this.object.up,ve)),ve.multiplyScalar(e),this._panOffset.add(ve)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;ve.copy(i).sub(this.target);let s=ve.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),i=e-n.left,s=t-n.top,r=n.width,a=n.height;this._mouse.x=i/r*2-1,this._mouse.y=-(s/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Oe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Oe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY);let t;if(this.object.isOrthographicCamera)e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY!==0&&this._dollyOut(this._getZoomScale(e.deltaY));else{const n=Math.abs(e.deltaY*.01);t=Math.pow(1.15,this.zoomSpeed*n),e.deltaY>0?this._scale/=t:e.deltaY!==0&&(this._scale*=t)}this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Oe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Oe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new _.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function qo(o){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(o)&&(this._addPointer(o),o.pointerType==="touch"?this._onTouchStart(o):this._onMouseDown(o)))}function Ko(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function Yo(o){switch(this._removePointer(o),this._pointers.length){case 0:this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Bs),this.state=de.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function $o(o){if(this.showOriginIcon&&this.engine&&this.engine.ToolUntils){const t=this.engine.scene?.camera||this.object;this.originPosition=this.engine.ToolUntils.WorldPointToScreenPoint(this.origin.clone(),t),console.log("Origin position:",this.originPosition,"Origin:",this.origin)}let e;switch(o.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case _.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=de.DOLLY;break;case _.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=de.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=de.ROTATE}break;case _.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=de.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=de.PAN}break;default:this.state=de.NONE}this.state!==de.NONE&&this.dispatchEvent(Si)}function Ho(o){switch(this.state){case de.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case de.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case de.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function Jo(o){this.enabled===!1||this.enableZoom===!1||this.state!==de.NONE||(o.preventDefault(),this.dispatchEvent(Si),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(Bs))}function Qo(o){this.enabled!==!1&&this._handleKeyDown(o)}function ea(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case _.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=de.TOUCH_ROTATE;break;case _.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=de.TOUCH_PAN;break;default:this.state=de.NONE}break;case 2:switch(this.touches.TWO){case _.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=de.TOUCH_DOLLY_PAN;break;case _.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=de.TOUCH_DOLLY_ROTATE;break;default:this.state=de.NONE}break;default:this.state=de.NONE}this.state!==de.NONE&&this.dispatchEvent(Si)}function ta(o){switch(this._trackPointer(o),this.state){case de.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case de.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case de.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case de.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=de.NONE}}function na(o){this.enabled!==!1&&o.preventDefault()}function ia(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function sa(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class zs{constructor(e,t,n,i){this._Engine=e,this.camera=t,this.domElement=n,this._isEnabled=!1,this._rayOriginOffset=new S.Vector3(0,-1,0),this._camerLocalDirection=new S.Vector3,this._tmpVector=new S.Vector3,this._rayCaster=new S.Raycaster,this._fallingTime=0,this._euler=new S.Euler(0,0,0,"YZX"),this._prevMouseX=0,this._prevMouseY=0,this.applyGravity=!1,this.gravityMinHeight=!0,this.applyCollision=!0,this.positionEasing=!0,this.lookflag=1,this.lookSpeed=.008,this.moveSpeed=.02,this.playerHeight=1.4,this.maxRotateX=.8,this.g=9.8,this.bindmousedown=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchStart.bind(this):this.onMouseDown.bind(this),this.bindmouseup=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchEnd.bind(this):this.onMouseUp.bind(this),this.bindmousemove=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchMove.bind(this):this.onMouseMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindMousewheel=this.onMousewheel.bind(this),this.needMousewheel=!1,this.moveWheelRun=!0,this.moveWheelStop=!1,this.wheelClock,this.keydown=!1,this.GetEngine=()=>e}set colliders(e){this._rayCastObjects=e}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._euler.setFromQuaternion(this.camera.quaternion),e?this.addEvents():this.removeEvents())}get enabled(){return this._isEnabled}addEvents(){const e=this._Engine?.DeviceType,t=e==="PC"||!e;console.log("[FirstPersonCameraControl] addEvents - DeviceType:",e,"isPC:",t),t?(console.log("[FirstPersonCameraControl] 添加鼠标事件监听器 - mousedown, mouseup"),this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(console.log("[FirstPersonCameraControl] 添加触摸事件监听器"),this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this._Engine&&this._Engine.deviceType!=="PC"?(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)):(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMousewheel(e){debugger;let t;switch(e.wheelDelta?(e.wheelDelta>0&&(t="up"),e.wheelDelta<0&&(t="down")):e.detail&&(e.detail<0&&(t="up"),e.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun==!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0)},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0)},150))}onMouseDown(e){console.log("[FirstPersonCameraControl] onMouseDown 被调用",e),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.screenX-this._prevMouseX:0,n=this._prevMouseY?e.screenY-this._prevMouseY:0,i=this._euler.x-n*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY;let s=this.GetEngine();s.movefirst=!0;var r=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(r)}onMouseUp(e){let t=this.GetEngine();t.movefirst=!1,this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY}onTouchMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.targetTouches[0].clientX-this._prevMouseX:0,n=this._prevMouseY?e.targetTouches[0].clientY-this._prevMouseY:0,i=this._euler.x-n*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY;let s=this.GetEngine();s.movefirst=!0;var r=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(r)}onTouchEnd(e){let t=this.GetEngine();t.movefirst=!1,this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(e){var t=new CustomEvent("bimengine:camerachange",{detail:""});let n=this.GetEngine();switch(n.movefirst=!0,window.dispatchEvent(t),e.keyCode){case 38:this.rotateY(-1);break;case 81:this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this.rotateX(-1);break;case 65:this._camerLocalDirection.x=-1;break;case 40:this.rotateY(1);break;case 83:this._camerLocalDirection.z=-1;break;case 39:this.rotateX(1);break;case 68:this._camerLocalDirection.x=1;break}}onKeyUp(e){let t=this.GetEngine();switch(t.movefirst=!1,e.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break}}rotateX(e){this._euler.y-=e*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler)}rotateY(e){let t=this._euler.x-e*this.lookflag*.5*this.lookSpeed;t>=0?t<this.maxRotateX?this._euler.x=t:this._euler.x=this.maxRotateX:t>-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler)}update(){this.keydown||this.gravityTest(),this.collisionTest()}gravityTest(){if(this.applyGravity){let e=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest();if(t){const n=t.point.add(new S.Vector3(0,this.playerHeight,0));if(this.positionEasing){if(n.y>=this.camera.position.y||n.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(n.y-this.camera.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distance<this.playerHeight&&(this.setCameraHeight(n.y),this._fallingTime=0,e=!1)}e&&this.setCameraHeight(this.camera.position.y-this.g*Math.pow(this._fallingTime,2))}else this.setCameraHeight(this.camera.position.y)}collisionTest(){this._camerLocalDirection.x!==0&&this.collisionTestX(),this._camerLocalDirection.z!==0&&this.collisionTestZ(),this._camerLocalDirection.y!==0&&this.collisionTestY()}collisionTestX(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.x),this.applyCollision){const t=this.hitTest();if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed)}collisionTestZ(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.crossVectors(this.camera.up,this._tmpVector),this._tmpVector.multiplyScalar(this._camerLocalDirection.z),this.applyCollision){const t=this.hitTest();if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed)}collisionTestY(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector=new S.Vector3(0,1,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.y),this.applyCollision){const n=this.hitTest();if(n&&n.distance<.3)return}let t=this.camera.position.clone().addScaledVector(this._tmpVector,this.moveSpeed);this.setCameraHeight(t.y)}setCameraHeight(e){let t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&e<t?this.camera.position.y=t:this.camera.position.y=e}getMinHeight(){let e,t=this.GetEngine(),n=t.ToolUntils?t.ToolUntils.GetBoundingBox(t):null;return t&&n&&(e=n.min.y),e}hitTest(){const e=this.camera.position.clone().add(this._rayOriginOffset);this._rayCaster.ray.origin=e,this._rayCaster.ray.direction=this._tmpVector;var n=this.GetEngine().scene.ground;return n&&n.material.type,null}}class ze{constructor(e,t,n){this.camera=e,this.renderer=t,this.scene=n,this.raycaster=new S.Raycaster}raycaster;worldToScreenNormalized(e){const t=e.clone();return t.project(this.camera),new S.Vector2(t.x,t.y)}worldToScreen(e){const t=new S.Vector3;return t.copy(e).project(this.camera),t.x=t.x*this.renderer.domElement.clientWidth*.5,t.y=-t.y*this.renderer.domElement.clientHeight*.5,t.z=(t.z+1)*.5,t.x+=this.renderer.domElement.clientWidth*.5,t.y+=this.renderer.domElement.clientHeight*.5,new S.Vector2(t.x,t.y)}screenToNormalized(e,t){const n=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight,s=e/n*2-1,r=-(t/i*2-1);return new S.Vector2(s,r)}screenToWorld(e,t,n){if(!this.scene&&!n)return console.warn("WorldToScreen: 需要提供 scene 或 objects 参数才能进行屏幕坐标转世界坐标"),null;const i=this.screenToNormalized(e,t);this.raycaster.setFromCamera(i,this.camera);const s=n||this.scene.children,r=this.raycaster.intersectObjects(s,!0);return r.length>0?r[0].point:null}screenToWorldWithDepth(e,t,n=0){const i=this.screenToNormalized(e,t);this.raycaster.setFromCamera(i,this.camera);const s=new S.Vector3;return this.raycaster.ray.at(n,s),s}updateCamera(e){this.camera=e}updateRenderer(e){this.renderer=e}updateScene(e){this.scene=e}}function Ci(o){const e={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0};e.init=function(u,g){e.self!=null&&e.self.disActive!=null&&e.self.type!=u.type&&e.self.disActive(),e.self=u,g==null&&(g={showCatch:!1}),e.options=g},e.render=function(){e.self&&e.self.render!=null&&e.self.render()},e.active=function(){o.renderer.domElement.addEventListener("mousedown",a),o.renderer.domElement.addEventListener("mouseup",h),o.renderer.domElement.addEventListener("mousemove",l),o.renderer.domElement.addEventListener("touchstart",d,{passive:!1}),o.renderer.domElement.addEventListener("touchend",p,{passive:!1}),o.renderer.domElement.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("keydown",t),window.addEventListener("keyup",n)},e.disActive=function(){o.renderer.domElement.removeEventListener("mousedown",a),o.renderer.domElement.removeEventListener("mouseup",h),o.renderer.domElement.removeEventListener("mousemove",l),o.renderer.domElement.removeEventListener("touchstart",d),o.renderer.domElement.removeEventListener("touchend",p),o.renderer.domElement.removeEventListener("touchmove",m),window.removeEventListener("keydown",t),window.removeEventListener("keyup",n)};function t(u){(u.keyCode===8||u.keyCode===46)&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),u.keyCode===27&&e.self&&e.self.handelKeyEscDown!=null&&e.self.handelKeyEscDown(),u.keyCode===13&&e.self&&e.self.handelKeyEnterDown!=null&&e.self.handelKeyEnterDown(),u.keyCode===32&&e.self&&e.self.handelKeySpaceDown!=null&&e.self.handelKeySpaceDown(),u.key==="Control"&&e.self&&e.self.handelKeyCtrlDown!=null&&e.self.handelKeyCtrlDown(),u.key==="Delete"&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),u.key==="Shift"&&e.self&&e.self.handelKeyShiftDown!=null&&e.self.handelKeyShiftDown(),u.key==="Meta"&&e.self&&e.self.handelKeyMetaDown!=null&&e.self.handelKeyMetaDown()}function n(u){u.key==="Alt"&&e.self&&e.self.handelKeyAltUp!=null&&e.self.handelKeyAltUp(),u.key==="Tab"&&e.self&&e.self.handelKeyTabUp!=null&&e.self.handelKeyTabUp(),u.key==="Control"&&e.self&&e.self.handelKeyCtrlUp!=null&&e.self.handelKeyCtrlUp(),u.key==="Shift"&&e.self&&e.self.handelKeyShiftUp!=null&&e.self.handelKeyShiftUp(),u.key==="Meta"&&e.self&&e.self.handelKeyMetaUp!=null&&e.self.handelKeyMetaUp(),u.key==="Command"&&e.self&&e.self.handelKeyCommandUp!=null&&e.self.handelKeyCommandUp(),u.key==="Windows"&&e.self&&e.self.handelKeyWindowsUp!=null&&e.self.handelKeyWindowsUp()}function i(u){const g=new S.Vector2,y=o.renderer.domElement.clientWidth,w=o.renderer.domElement.clientHeight;return g.x=u.offsetX/y*2-1,g.y=-(u.offsetY/w)*2+1,g}function s(u){const g=new S.Raycaster,y=i(u);return g.setFromCamera(y,o.camera),g}function r(u,g=!1){const y=s(u);if(u.raycaster=y,g){const w=f(y,u);u.catch=w}}function a(u){u.button===0&&(e.mouseDownTime=Date.now(),e.mouseDownPosition=new S.Vector3(u.offsetX,u.offsetY,0),e.self&&e.self.handleMouseDown!=null&&(o.engineStatus.isFree=!0,r(u,!0),u.catch!=null&&o.controlModule.orbitControls.origin.set(u.catch.point.x,u.catch.point.y,u.catch.point.z),e.self.handleMouseDown(u)))}function l(u){e.self&&e.self.handleMouseMove!=null&&(r(u,!0),e.self.handleMouseMove(u))}function h(u){if(u.button!==0)return;const g=Date.now(),y=g-e.mouseDownTime,w=new S.Vector3(u.offsetX,u.offsetY,0);e.self&&e.self.handleMouseUp!=null&&(r(u,!1),e.self.handleMouseUp(u));const x=w.distanceTo(e.mouseDownPosition);if((y<100||x==0)&&e.self&&e.self.handleMouseClick!=null){r(u,!0);const v=g-e.lastClickTime;console.log(v),v<200?e.self.handleMouseDoubleClick!=null&&e.self.handleMouseDoubleClick(u):e.self.handleMouseClick!=null&&e.self.handleMouseClick(u),e.lastClickTime=Date.now()}}function c(u){const g=u.touches[0]||u.changedTouches[0];if(!g)return null;const w=o.renderer.domElement.getBoundingClientRect(),x=g.clientX-w.left,v=g.clientY-w.top;return{offsetX:x,offsetY:v,button:0,clientX:g.clientX,clientY:g.clientY,preventDefault:()=>u.preventDefault(),stopPropagation:()=>u.stopPropagation(),originalEvent:u}}function d(u){if(u.preventDefault(),u.touches.length!==1)return;const g=c(u);g&&a(g)}function m(u){if(u.preventDefault(),u.touches.length!==1)return;const g=c(u);g&&l(g)}function p(u){u.preventDefault();const g=c(u);g&&h(g)}function f(u,g){if(!o.engineStatus.isFree){o.hoverHighLight.clearHighlight();return}o.catchSvg.innerHTML="";const y=o.octreeBox.rayInterationModel(u);let w=u.intersectObjects(o.scene.children.filter(B=>B instanceof S.InstancedMesh),!0);if(w.length>0&&(y.length==0||w[0].distance<y[0].distance)){let B=w[0].object;if(B.ids!=null&&B.ids.length!=0){let V=B.ids[w[0].instanceId],U={object:{url:B.url,id:V,name:V,isInstance:!0},face:w[0].face,distance:w[0].distance,point:w[0].point,instanceId:w[0].instanceId,matrix:B.matrixs[w[0].instanceId]};y.splice(0,0,U)}}if(y.length===0)return;let x=y[0].object.url,v=y[0].object.name,b=o.modelEdge.getModelEdge(x,v);b||(b=[0,0,[]]);let D=[];b[2].forEach(B=>{B[0]!=null&&B[1]!=null&&D.push({X:B[0].X*.5+B[1].X*.5,Y:B[0].Y*.5+B[1].Y*.5,Z:B[0].Z*.5+B[1].Z*.5})});let T=[...b[2].map(B=>B[0]),...D],k="face",P=[],I=[],z=10;if(T.forEach(B=>{if(B!=null){let V=new S.Vector3(B.X,B.Z,-B.Y),U=o.worldToScreen.worldToScreen(V),H=Math.sqrt(Math.pow(U.x-g.offsetX,2)+Math.pow(U.y-g.offsetY,2));H<z&&(z=H,P.push({point:V,distance:H,pointxy:U}))}}),P.length>0?(P.sort((B,V)=>B.distance-V.distance),k="point"):(b[2].forEach(B=>{if(B[0]!=null&&B[1]!=null){let V=new S.Vector3(B[0].X,B[0].Z,-B[0].Y),U=new S.Vector3(B[1].X,B[1].Z,-B[1].Y),H=o.worldToScreen.worldToScreen(V),G=o.worldToScreen.worldToScreen(U),$=C(new S.Vector2(g.offsetX,g.offsetY),H,G);if($<z){let F=E(new S.Vector2(g.offsetX,g.offsetY),H,G),N=M(F,V,U);I.push({distance:$,point:N,pointxy:o.worldToScreen.worldToScreen(N),start:H,end:G})}}}),I.length>0&&(I.sort((B,V)=>B.distance-V.distance),k="line")),k=="point"&&e.options.showCatch){const B=new ze(o.camera,o.renderer,o.scene).worldToScreen(P[0].point);o.catchSvg.innerHTML="";const V=B.x+o.reactBoundingClientRect.left,U=B.y+o.reactBoundingClientRect.top;console.log(V,U);const H=document.createElementNS("http://www.w3.org/2000/svg","polygon");H.setAttribute("class","catchPoint"),H.setAttribute("points",`${V},${U-8} ${V-7},${U+4} ${V+7},${U+4}`),o.catchSvg.appendChild(H),y[0].point=P[0].point}else if(k=="line"&&e.options.showCatch){o.worldToScreen.worldToScreen(I[0].point);const B=I[0].start,V=I[0].end;o.catchSvg.innerHTML="";const U=document.createElementNS("http://www.w3.org/2000/svg","line");U.setAttribute("class","catchLine"),U.setAttribute("x1",(B.x+o.reactBoundingClientRect.left).toString()),U.setAttribute("y1",(B.y+o.reactBoundingClientRect.top).toString()),U.setAttribute("x2",(V.x+o.reactBoundingClientRect.left).toString()),U.setAttribute("y2",(V.y+o.reactBoundingClientRect.top).toString()),U.setAttribute("stroke","rgb(8, 223, 215)"),U.setAttribute("stroke-width","2"),o.catchSvg.appendChild(U),y[0].point=I[0].point}else if(k=="face"&&e.options.showCatch){let B=y[0].point.clone(),V=y[0].normal||(y[0].face?y[0].face.normal:null);const U=(V?V.clone():new S.Vector3(0,0,1)).normalize(),H=Math.abs(U.y)<.9?new S.Vector3(0,1,0):new S.Vector3(1,0,0),G=new S.Vector3().crossVectors(U,H).normalize(),$=new S.Vector3().crossVectors(U,G).normalize(),F=.05,ee=[new S.Vector3().copy(G).add($).multiplyScalar(F),new S.Vector3().copy(G).sub($).multiplyScalar(F),new S.Vector3().copy(G).multiplyScalar(-1).sub($).multiplyScalar(F),new S.Vector3().copy(G).multiplyScalar(-1).add($).multiplyScalar(F)].map(ce=>new S.Vector3().copy(B).add(ce)).map(ce=>o.worldToScreen.worldToScreen(ce));o.catchSvg.innerHTML="";const Y=document.createElementNS("http://www.w3.org/2000/svg","polygon");Y.setAttribute("class","catchFace"),Y.setAttribute("points",ee.map(ce=>`${ce.x+o.reactBoundingClientRect.left},${ce.y+o.reactBoundingClientRect.top}`).join(" ")),Y.setAttribute("fill","rgba(1, 238, 255, 0.2)"),Y.setAttribute("stroke","rgb(0, 255, 247)"),Y.setAttribute("stroke-width","1"),o.catchSvg.appendChild(Y)}return y[0];function C(B,V,U){const H=new S.Vector2().subVectors(U,V),G=H.lengthSq();if(G<1e-10)return B.distanceTo(V);const $=new S.Vector2().subVectors(B,V),F=S.MathUtils.clamp($.dot(H)/G,0,1),N=new S.Vector2().copy(H).multiplyScalar(F).add(V);return B.distanceTo(N)}function E(B,V,U){const H=new S.Vector2().subVectors(U,V),G=H.lengthSq();if(G<1e-10)return 0;const $=new S.Vector2().subVectors(B,V);return S.MathUtils.clamp($.dot(H)/G,0,1)}function M(B,V,U){const H=S.MathUtils.clamp(B,0,1);return new S.Vector3().lerpVectors(V,U,H)}}return e}class ra{engine;orbitControls;firstPersonControls;isActive=!0;originDiv=null;handelBehaved;isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(e){this.engine=e,this.init(),this.handelBehaved=Ci(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new Zo(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new zs(this.engine,this.engine.camera,this.engine.renderer.domElement);const e=document.createElement("div");this.originDiv=e,e.className="originDiv",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.width="30px",e.style.height="30px",e.style.borderRadius="50%",e.style.pointerEvents="none",e.style.backgroundImage="url(/assets/svg/rotate-orbit.svg)",this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setMoveSpeed(e){this.firstPersonControls.moveSpeed=e*.1}getMoveSpeed(){return this.firstPersonControls.moveSpeed*10}setApplyCollision(e){this.firstPersonControls.applyCollision=e}getApplyCollision(){return this.firstPersonControls.applyCollision}setApplyGravity(e){this.firstPersonControls.applyGravity=e}getApplyGravity(){return this.firstPersonControls.applyGravity}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls=new zs(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.orbitControls.enabled=!1,this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0}switchDefaultMode(){this.firstPersonControls&&(this.firstPersonControls.enabled=!1),this.orbitControls.enabled=!0}handleMouseUp(e){this.isDragging=!1,this.isDown=!1}handleMouseMove(e){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(e){this.isDown=!0}handleMouseClick(e){this.isDragging=!1,this.isDown=!1}update(){if(this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.orbitControls.enabled){const e=this.engine.controlModule.orbitControls.origin,n=this.engine.worldToScreen.worldToScreen(e);this.originDiv&&this.isDragging?(this.originDiv.style.left=n.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=n.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}}const Mt={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
1
+ (function(_t,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],_):(_t=typeof globalThis<"u"?globalThis:_t||self,_(_t.BimEngineSDK={},_t.THREE))})(this,(function(_t,_){"use strict";function Uo(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const S=Uo(_);class Vo{engine;scene;constructor(e){this.engine=e,this.scene=new S.Scene;let t=new S.Group;t.name="groupEdge",this.scene.add(t)}}class jo{engine;perspectiveCamera;orthographicCamera;constructor(e){this.engine=e,this.perspectiveCamera=new S.PerspectiveCamera(60,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,n=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new S.OrthographicCamera(t*n/-2,t*n/2,t/2,t/-2,.1,1e3)}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const e=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const n of t.passes)n.camera!==void 0&&(n.camera=e)}switchToPerspectiveCamera(){if(!this.engine.controls)return;const e=this.engine.camera.position.clone(),t=this.engine.controls.target.clone();this.engine.camera=this.perspectiveCamera,this.engine.scene.camera=this.perspectiveCamera,this.perspectiveCamera.position.copy(e),this.perspectiveCamera.lookAt(t),this.engine.controlModule.orbitControls.object=this.perspectiveCamera,this.engine.controlModule.firstPersonControls.camera=this.perspectiveCamera,this.updateComposerCamera(),this.perspectiveCamera.updateProjectionMatrix(),this.perspectiveCamera.updateMatrixWorld()}switchToOrthographicCamera(){if(!this.engine.controls)return;const e=this.engine.camera.position.clone(),t=this.engine.controls.target.clone();this.engine.camera=this.orthographicCamera,this.engine.scene.camera=this.orthographicCamera,this.orthographicCamera.position.copy(e),this.orthographicCamera.lookAt(t),this.engine.controlModule.orbitControls.object=this.orthographicCamera,this.engine.controlModule.firstPersonControls.camera=this.orthographicCamera,this.updateComposerCamera(),this.orthographicCamera.updateProjectionMatrix(),this.orthographicCamera.updateMatrixWorld()}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const e=this.engine.camera,t=this.getCameraType(),n={type:t,position:{x:e.position.x,y:e.position.y,z:e.position.z},rotation:{x:e.rotation.x,y:e.rotation.y,z:e.rotation.z},quaternion:{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w}};return this.engine.controls&&this.engine.controls.target&&(n.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z}),t==="orthographic"&&(n.zoom=e.zoom),n}restoreCameraPose(e){this.getCameraType()!==e.type&&(e.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const n=this.engine.camera;n.position.set(e.position.x,e.position.y,e.position.z),e.quaternion?n.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e.target&&this.engine.controls&&this.engine.controls.target&&this.engine.controls.target.set(e.target.x,e.target.y,e.target.z),e.type==="orthographic"&&e.zoom!==void 0&&(n.zoom=e.zoom,n.updateProjectionMatrix()),n.updateMatrix(),n.updateMatrixWorld(!0),this.engine.controls&&this.engine.controls.update&&this.engine.controls.update()}}class Go{engine;deviceType;constructor(e){this.engine=e,this.deviceType=this.detectDeviceType()}detectDeviceType(){const e=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,n=e.some(c=>c.test(t)),i="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,s=globalThis.screen.width,r=globalThis.screen.height,a=s<=768||r<=768,h=(globalThis.devicePixelRatio||1)>=2;return n||i&&a||i&&h?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}class Wo{engine;renderer;constructor(e){this.engine=e,this.renderer=null}createRenderer(){const{width:e,height:t}=this.engine.deviceModule.getContainerSize();return this.renderer=new S.WebGLRenderer({alpha:!0,premultipliedAlpha:!1,stencil:!0}),this.renderer.setClearColor(0,0),this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=S.PCFSoftShadowMap,this.renderer.localClippingEnabled=!0,this.renderer.outputColorSpace=S.SRGBColorSpace,this.engine.container.appendChild(this.renderer.domElement),this.renderer}disposeRenderer(){this.renderer?.dispose()}}const Es={type:"change"},Si={type:"start"},Bs={type:"end"},Mn=new _.Ray,Os=new _.Plane,Xo=Math.cos(70*_.MathUtils.DEG2RAD),ve=new _.Vector3,Oe=.25*Math.PI,de={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Ai=1e-6;class Zo extends _.Controls{constructor(e,t,n=null){super(t,n),this.engine=e,this.state=de.NONE,this.target=new _.Vector3,this.cursor=new _.Vector3,this.origin=new _.Vector3(0,0,0),this.showOriginIcon=!0,this.originPosition={x:0,y:0},this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:_.MOUSE.ROTATE,MIDDLE:_.MOUSE.DOLLY,RIGHT:_.MOUSE.PAN},this.touches={ONE:_.TOUCH.ROTATE,TWO:_.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new _.Vector3,this._lastQuaternion=new _.Quaternion,this._lastTargetPosition=new _.Vector3,this._quat=new _.Quaternion().setFromUnitVectors(t.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new _.Spherical,this._sphericalDelta=new _.Spherical,this._scale=1,this._panOffset=new _.Vector3,this._rotateStart=new _.Vector2,this._rotateEnd=new _.Vector2,this._rotateDelta=new _.Vector2,this._panStart=new _.Vector2,this._panEnd=new _.Vector2,this._panDelta=new _.Vector2,this._dollyStart=new _.Vector2,this._dollyEnd=new _.Vector2,this._dollyDelta=new _.Vector2,this._dollyDirection=new _.Vector3,this._mouse=new _.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Ko.bind(this),this._onPointerDown=qo.bind(this),this._onPointerUp=Yo.bind(this),this._onContextMenu=na.bind(this),this._onMouseWheel=Jo.bind(this),this._onKeyDown=Qo.bind(this),this._onTouchStart=ea.bind(this),this._onTouchMove=ta.bind(this),this._onMouseDown=$o.bind(this),this._onMouseMove=Ho.bind(this),this._interceptControlDown=ia.bind(this),this._interceptControlUp=sa.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Es),this.update(),this.state=de.NONE}update(e=null){this.engine&&this.engine.interactionManager&&this.engine.interactionManager.origin&&this.origin.copy(this.engine.interactionManager.origin);const t=this.object.position;ve.copy(t).sub(this.target),ve.applyQuaternion(this._quat),this._spherical.setFromVector3(ve),this.autoRotate&&this.state===de.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=Oe:n>Math.PI&&(n-=Oe),i<-Math.PI?i+=Oe:i>Math.PI&&(i-=Oe),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const r=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=r!=this._spherical.radius}if(ve.setFromSpherical(this._spherical),ve.applyQuaternion(this._quatInverse),this.engine&&this.engine.deviceType==="PC"){const r=new _.Vector3;if(r.copy(this.origin).sub(this.target),r.lengthSq()>1e-4&&(this._sphericalDelta.theta!==0||this._sphericalDelta.phi!==0)){const l=this.enableDamping?this.dampingFactor*3:1,h=new _.Vector3(0,1,0),c=new _.Vector3;this.object.getWorldDirection(c);const d=c.clone().cross(h).normalize(),m=new _.Vector3().copy(this.object.position).sub(this.origin);m.applyAxisAngle(h,Math.PI*this._sphericalDelta.theta*l),m.applyAxisAngle(d,Math.PI*this._sphericalDelta.phi*l),t.copy(this.origin).add(m);const p=new _.Vector3().copy(this.target).sub(this.origin);p.applyAxisAngle(h,Math.PI*this._sphericalDelta.theta*l),p.applyAxisAngle(d,Math.PI*this._sphericalDelta.phi*l),this.target.copy(this.origin).add(p)}else if(this._panOffset.lengthSq()===0&&this._sphericalDelta.phi===0&&this._sphericalDelta.theta===0){if(this._scale!==1){const l=new _.Vector3;this.object.getWorldDirection(l);const h=this._spherical.radius*.05*(this._scale-1);t.add(l.multiplyScalar(h))}}else t.copy(this.target).add(ve);this.object.lookAt(this.target)}else t.copy(this.target).add(ve),this.object.lookAt(this.target);if(this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let r=null;if(this.object.isPerspectiveCamera){const a=ve.length();r=this._clampDistance(a*this._scale);const l=a-r;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){const a=new _.Vector3(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;const h=new _.Vector3(this._mouse.x,this._mouse.y,0);h.unproject(this.object),this.object.position.sub(h).add(a),this.object.updateMatrixWorld(),r=ve.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;r!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(r).add(this.object.position):(Mn.origin.copy(this.object.position),Mn.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Mn.direction))<Xo?this.object.lookAt(this.target):(Os.setFromNormalAndCoplanarPoint(this.object.up,this.target),Mn.intersectPlane(Os,this.target))))}else if(this.object.isOrthographicCamera){const r=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),r!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>Ai||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Ai||this._lastTargetPosition.distanceToSquared(this.target)>Ai?(this.dispatchEvent(Es),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Oe/60*this.autoRotateSpeed*e:Oe/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){ve.setFromMatrixColumn(t,0),ve.multiplyScalar(-e),this._panOffset.add(ve)}_panUp(e,t){this.screenSpacePanning===!0?ve.setFromMatrixColumn(t,1):(ve.setFromMatrixColumn(t,0),ve.crossVectors(this.object.up,ve)),ve.multiplyScalar(e),this._panOffset.add(ve)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;ve.copy(i).sub(this.target);let s=ve.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),i=e-n.left,s=t-n.top,r=n.width,a=n.height;this._mouse.x=i/r*2-1,this._mouse.y=-(s/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Oe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Oe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY);let t;if(this.object.isOrthographicCamera)e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY!==0&&this._dollyOut(this._getZoomScale(e.deltaY));else{const n=Math.abs(e.deltaY*.01);t=Math.pow(1.15,this.zoomSpeed*n),e.deltaY>0?this._scale/=t:e.deltaY!==0&&(this._scale*=t)}this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Oe*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(Oe*this._rotateDelta.x/t.clientHeight),this._rotateUp(Oe*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const r=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(r,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new _.Vector2,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function qo(o){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(o)&&(this._addPointer(o),o.pointerType==="touch"?this._onTouchStart(o):this._onMouseDown(o)))}function Ko(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function Yo(o){switch(this._removePointer(o),this._pointers.length){case 0:this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Bs),this.state=de.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function $o(o){if(this.showOriginIcon&&this.engine&&this.engine.ToolUntils){const t=this.engine.scene?.camera||this.object;this.originPosition=this.engine.ToolUntils.WorldPointToScreenPoint(this.origin.clone(),t),console.log("Origin position:",this.originPosition,"Origin:",this.origin)}let e;switch(o.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case _.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=de.DOLLY;break;case _.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=de.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=de.ROTATE}break;case _.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=de.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=de.PAN}break;default:this.state=de.NONE}this.state!==de.NONE&&this.dispatchEvent(Si)}function Ho(o){switch(this.state){case de.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case de.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case de.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function Jo(o){this.enabled===!1||this.enableZoom===!1||this.state!==de.NONE||(o.preventDefault(),this.dispatchEvent(Si),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(Bs))}function Qo(o){this.enabled!==!1&&this._handleKeyDown(o)}function ea(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case _.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=de.TOUCH_ROTATE;break;case _.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=de.TOUCH_PAN;break;default:this.state=de.NONE}break;case 2:switch(this.touches.TWO){case _.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=de.TOUCH_DOLLY_PAN;break;case _.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=de.TOUCH_DOLLY_ROTATE;break;default:this.state=de.NONE}break;default:this.state=de.NONE}this.state!==de.NONE&&this.dispatchEvent(Si)}function ta(o){switch(this._trackPointer(o),this.state){case de.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case de.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case de.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case de.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=de.NONE}}function na(o){this.enabled!==!1&&o.preventDefault()}function ia(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function sa(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class zs{constructor(e,t,n,i){this._Engine=e,this.camera=t,this.domElement=n,this._isEnabled=!1,this._rayOriginOffset=new S.Vector3(0,-1,0),this._camerLocalDirection=new S.Vector3,this._tmpVector=new S.Vector3,this._rayCaster=new S.Raycaster,this._fallingTime=0,this._euler=new S.Euler(0,0,0,"YZX"),this._prevMouseX=0,this._prevMouseY=0,this.applyGravity=!1,this.gravityMinHeight=!0,this.applyCollision=!0,this.positionEasing=!0,this.lookflag=1,this.lookSpeed=.008,this.moveSpeed=.02,this.playerHeight=1.4,this.maxRotateX=.8,this.g=9.8,this.bindmousedown=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchStart.bind(this):this.onMouseDown.bind(this),this.bindmouseup=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchEnd.bind(this):this.onMouseUp.bind(this),this.bindmousemove=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchMove.bind(this):this.onMouseMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindMousewheel=this.onMousewheel.bind(this),this.needMousewheel=!1,this.moveWheelRun=!0,this.moveWheelStop=!1,this.wheelClock,this.keydown=!1,this.GetEngine=()=>e}set colliders(e){this._rayCastObjects=e}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._euler.setFromQuaternion(this.camera.quaternion),e?this.addEvents():this.removeEvents())}get enabled(){return this._isEnabled}addEvents(){const e=this._Engine?.DeviceType,t=e==="PC"||!e;console.log("[FirstPersonCameraControl] addEvents - DeviceType:",e,"isPC:",t),t?(console.log("[FirstPersonCameraControl] 添加鼠标事件监听器 - mousedown, mouseup"),this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(console.log("[FirstPersonCameraControl] 添加触摸事件监听器"),this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this._Engine&&this._Engine.deviceType!=="PC"?(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)):(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMousewheel(e){debugger;let t;switch(e.wheelDelta?(e.wheelDelta>0&&(t="up"),e.wheelDelta<0&&(t="down")):e.detail&&(e.detail<0&&(t="up"),e.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun==!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0)},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0)},150))}onMouseDown(e){console.log("[FirstPersonCameraControl] onMouseDown 被调用",e),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.screenX-this._prevMouseX:0,n=this._prevMouseY?e.screenY-this._prevMouseY:0,i=this._euler.x-n*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY;let s=this.GetEngine();s.movefirst=!0;var r=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(r)}onMouseUp(e){let t=this.GetEngine();t.movefirst=!1,this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY}onTouchMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.targetTouches[0].clientX-this._prevMouseX:0,n=this._prevMouseY?e.targetTouches[0].clientY-this._prevMouseY:0,i=this._euler.x-n*this.lookflag*this.lookSpeed;i>=0?i<this.maxRotateX?this._euler.x=i:this._euler.x=this.maxRotateX:i>-this.maxRotateX?this._euler.x=i:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY;let s=this.GetEngine();s.movefirst=!0;var r=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(r)}onTouchEnd(e){let t=this.GetEngine();t.movefirst=!1,this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(e){var t=new CustomEvent("bimengine:camerachange",{detail:""});let n=this.GetEngine();switch(n.movefirst=!0,window.dispatchEvent(t),e.keyCode){case 38:this.rotateY(-1);break;case 81:this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this.rotateX(-1);break;case 65:this._camerLocalDirection.x=-1;break;case 40:this.rotateY(1);break;case 83:this._camerLocalDirection.z=-1;break;case 39:this.rotateX(1);break;case 68:this._camerLocalDirection.x=1;break}}onKeyUp(e){let t=this.GetEngine();switch(t.movefirst=!1,e.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break}}rotateX(e){this._euler.y-=e*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler)}rotateY(e){let t=this._euler.x-e*this.lookflag*.5*this.lookSpeed;t>=0?t<this.maxRotateX?this._euler.x=t:this._euler.x=this.maxRotateX:t>-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler)}update(){this.keydown||this.gravityTest(),this.collisionTest()}gravityTest(){if(this.applyGravity){let e=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest();if(t){const n=t.point.add(new S.Vector3(0,this.playerHeight,0));if(this.positionEasing){if(n.y>=this.camera.position.y||n.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(n.y-this.camera.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distance<this.playerHeight&&(this.setCameraHeight(n.y),this._fallingTime=0,e=!1)}e&&this.setCameraHeight(this.camera.position.y-this.g*Math.pow(this._fallingTime,2))}else this.setCameraHeight(this.camera.position.y)}collisionTest(){this._camerLocalDirection.x!==0&&this.collisionTestX(),this._camerLocalDirection.z!==0&&this.collisionTestZ(),this._camerLocalDirection.y!==0&&this.collisionTestY()}collisionTestX(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.x),this.applyCollision){const t=this.hitTest();if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed)}collisionTestZ(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.crossVectors(this.camera.up,this._tmpVector),this._tmpVector.multiplyScalar(this._camerLocalDirection.z),this.applyCollision){const t=this.hitTest();if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed)}collisionTestY(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector=new S.Vector3(0,1,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.y),this.applyCollision){const n=this.hitTest();if(n&&n.distance<.3)return}let t=this.camera.position.clone().addScaledVector(this._tmpVector,this.moveSpeed);this.setCameraHeight(t.y)}setCameraHeight(e){let t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&e<t?this.camera.position.y=t:this.camera.position.y=e}getMinHeight(){let e,t=this.GetEngine(),n=t.ToolUntils?t.ToolUntils.GetBoundingBox(t):null;return t&&n&&(e=n.min.y),e}hitTest(){const e=this.camera.position.clone().add(this._rayOriginOffset);this._rayCaster.ray.origin=e,this._rayCaster.ray.direction=this._tmpVector;var n=this.GetEngine().scene.ground;return n&&n.material.type,null}}class ze{constructor(e,t,n){this.camera=e,this.renderer=t,this.scene=n,this.raycaster=new S.Raycaster}raycaster;worldToScreenNormalized(e){const t=e.clone();return t.project(this.camera),new S.Vector2(t.x,t.y)}worldToScreen(e){const t=new S.Vector3;return t.copy(e).project(this.camera),t.x=t.x*this.renderer.domElement.clientWidth*.5,t.y=-t.y*this.renderer.domElement.clientHeight*.5,t.z=(t.z+1)*.5,t.x+=this.renderer.domElement.clientWidth*.5,t.y+=this.renderer.domElement.clientHeight*.5,new S.Vector2(t.x,t.y)}screenToNormalized(e,t){const n=this.renderer.domElement.clientWidth,i=this.renderer.domElement.clientHeight,s=e/n*2-1,r=-(t/i*2-1);return new S.Vector2(s,r)}screenToWorld(e,t,n){if(!this.scene&&!n)return console.warn("WorldToScreen: 需要提供 scene 或 objects 参数才能进行屏幕坐标转世界坐标"),null;const i=this.screenToNormalized(e,t);this.raycaster.setFromCamera(i,this.camera);const s=n||this.scene.children,r=this.raycaster.intersectObjects(s,!0);return r.length>0?r[0].point:null}screenToWorldWithDepth(e,t,n=0){const i=this.screenToNormalized(e,t);this.raycaster.setFromCamera(i,this.camera);const s=new S.Vector3;return this.raycaster.ray.at(n,s),s}updateCamera(e){this.camera=e}updateRenderer(e){this.renderer=e}updateScene(e){this.scene=e}}function Ci(o){const e={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0};e.init=function(u,g){e.self!=null&&e.self.disActive!=null&&e.self.type!=u.type&&e.self.disActive(),e.self=u,g==null&&(g={showCatch:!1}),e.options=g},e.render=function(){e.self&&e.self.render!=null&&e.self.render()},e.active=function(){o.renderer.domElement.addEventListener("mousedown",a),o.renderer.domElement.addEventListener("mouseup",h),o.renderer.domElement.addEventListener("mousemove",l),o.renderer.domElement.addEventListener("touchstart",d,{passive:!1}),o.renderer.domElement.addEventListener("touchend",p,{passive:!1}),o.renderer.domElement.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("keydown",t),window.addEventListener("keyup",n)},e.disActive=function(){o.renderer.domElement.removeEventListener("mousedown",a),o.renderer.domElement.removeEventListener("mouseup",h),o.renderer.domElement.removeEventListener("mousemove",l),o.renderer.domElement.removeEventListener("touchstart",d),o.renderer.domElement.removeEventListener("touchend",p),o.renderer.domElement.removeEventListener("touchmove",m),window.removeEventListener("keydown",t),window.removeEventListener("keyup",n)};function t(u){(u.keyCode===8||u.keyCode===46)&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),u.keyCode===27&&e.self&&e.self.handelKeyEscDown!=null&&e.self.handelKeyEscDown(),u.keyCode===13&&e.self&&e.self.handelKeyEnterDown!=null&&e.self.handelKeyEnterDown(),u.keyCode===32&&e.self&&e.self.handelKeySpaceDown!=null&&e.self.handelKeySpaceDown(),u.key==="Control"&&e.self&&e.self.handelKeyCtrlDown!=null&&e.self.handelKeyCtrlDown(),u.key==="Delete"&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),u.key==="Shift"&&e.self&&e.self.handelKeyShiftDown!=null&&e.self.handelKeyShiftDown(),u.key==="Meta"&&e.self&&e.self.handelKeyMetaDown!=null&&e.self.handelKeyMetaDown()}function n(u){u.key==="Alt"&&e.self&&e.self.handelKeyAltUp!=null&&e.self.handelKeyAltUp(),u.key==="Tab"&&e.self&&e.self.handelKeyTabUp!=null&&e.self.handelKeyTabUp(),u.key==="Control"&&e.self&&e.self.handelKeyCtrlUp!=null&&e.self.handelKeyCtrlUp(),u.key==="Shift"&&e.self&&e.self.handelKeyShiftUp!=null&&e.self.handelKeyShiftUp(),u.key==="Meta"&&e.self&&e.self.handelKeyMetaUp!=null&&e.self.handelKeyMetaUp(),u.key==="Command"&&e.self&&e.self.handelKeyCommandUp!=null&&e.self.handelKeyCommandUp(),u.key==="Windows"&&e.self&&e.self.handelKeyWindowsUp!=null&&e.self.handelKeyWindowsUp()}function i(u){const g=new S.Vector2,y=o.renderer.domElement.clientWidth,w=o.renderer.domElement.clientHeight;return g.x=u.offsetX/y*2-1,g.y=-(u.offsetY/w)*2+1,g}function s(u){const g=new S.Raycaster,y=i(u);return g.setFromCamera(y,o.camera),g}function r(u,g=!1){const y=s(u);if(u.raycaster=y,g){const w=f(y,u);u.catch=w}}function a(u){u.button===0&&(e.mouseDownTime=Date.now(),e.mouseDownPosition=new S.Vector3(u.offsetX,u.offsetY,0),e.self&&e.self.handleMouseDown!=null&&(o.engineStatus.isFree=!0,r(u,!0),u.catch!=null&&o.controlModule.orbitControls.origin.set(u.catch.point.x,u.catch.point.y,u.catch.point.z),e.self.handleMouseDown(u)))}function l(u){e.self&&e.self.handleMouseMove!=null&&(r(u,!0),e.self.handleMouseMove(u))}function h(u){if(u.button!==0)return;const g=Date.now(),y=g-e.mouseDownTime,w=new S.Vector3(u.offsetX,u.offsetY,0);e.self&&e.self.handleMouseUp!=null&&(r(u,!1),e.self.handleMouseUp(u));const x=w.distanceTo(e.mouseDownPosition);if((y<100||x==0)&&e.self&&e.self.handleMouseClick!=null){r(u,!0);const v=g-e.lastClickTime;console.log(v),v<200?e.self.handleMouseDoubleClick!=null&&e.self.handleMouseDoubleClick(u):e.self.handleMouseClick!=null&&e.self.handleMouseClick(u),e.lastClickTime=Date.now()}}function c(u){const g=u.touches[0]||u.changedTouches[0];if(!g)return null;const w=o.renderer.domElement.getBoundingClientRect(),x=g.clientX-w.left,v=g.clientY-w.top;return{offsetX:x,offsetY:v,button:0,clientX:g.clientX,clientY:g.clientY,preventDefault:()=>u.preventDefault(),stopPropagation:()=>u.stopPropagation(),originalEvent:u}}function d(u){if(u.preventDefault(),u.touches.length!==1)return;const g=c(u);g&&a(g)}function m(u){if(u.preventDefault(),u.touches.length!==1)return;const g=c(u);g&&l(g)}function p(u){u.preventDefault();const g=c(u);g&&h(g)}function f(u,g){if(!o.engineStatus.isFree){o.hoverHighLight.clearHighlight();return}o.catchSvg.innerHTML="";const y=o.octreeBox.rayInterationModel(u);let w=u.intersectObjects(o.scene.children.filter(B=>B instanceof S.InstancedMesh),!0);if(w.length>0&&(y.length==0||w[0].distance<y[0].distance)){let B=w[0].object;if(B.ids!=null&&B.ids.length!=0){let V=B.ids[w[0].instanceId],U={object:{url:B.url,id:V,name:V,isInstance:!0},face:w[0].face,distance:w[0].distance,point:w[0].point,instanceId:w[0].instanceId,matrix:B.matrixs[w[0].instanceId]};y.splice(0,0,U)}}if(y.length===0)return;let x=y[0].object.url,v=y[0].object.name,b=o.modelEdge.getModelEdge(x,v);b||(b=[0,0,[]]);let D=[];b[2].forEach(B=>{B[0]!=null&&B[1]!=null&&D.push({X:B[0].X*.5+B[1].X*.5,Y:B[0].Y*.5+B[1].Y*.5,Z:B[0].Z*.5+B[1].Z*.5})});let T=[...b[2].map(B=>B[0]),...D],k="face",P=[],I=[],z=10;if(T.forEach(B=>{if(B!=null){let V=new S.Vector3(B.X,B.Z,-B.Y),U=o.worldToScreen.worldToScreen(V),H=Math.sqrt(Math.pow(U.x-g.offsetX,2)+Math.pow(U.y-g.offsetY,2));H<z&&(z=H,P.push({point:V,distance:H,pointxy:U}))}}),P.length>0?(P.sort((B,V)=>B.distance-V.distance),k="point"):(b[2].forEach(B=>{if(B[0]!=null&&B[1]!=null){let V=new S.Vector3(B[0].X,B[0].Z,-B[0].Y),U=new S.Vector3(B[1].X,B[1].Z,-B[1].Y),H=o.worldToScreen.worldToScreen(V),G=o.worldToScreen.worldToScreen(U),$=C(new S.Vector2(g.offsetX,g.offsetY),H,G);if($<z){let F=E(new S.Vector2(g.offsetX,g.offsetY),H,G),N=M(F,V,U);I.push({distance:$,point:N,pointxy:o.worldToScreen.worldToScreen(N),start:H,end:G})}}}),I.length>0&&(I.sort((B,V)=>B.distance-V.distance),k="line")),k=="point"&&e.options.showCatch){const B=new ze(o.camera,o.renderer,o.scene).worldToScreen(P[0].point);o.catchSvg.innerHTML="";const V=B.x+o.reactBoundingClientRect.left,U=B.y+o.reactBoundingClientRect.top;console.log(V,U);const H=document.createElementNS("http://www.w3.org/2000/svg","polygon");H.setAttribute("class","catchPoint"),H.setAttribute("points",`${V},${U-8} ${V-7},${U+4} ${V+7},${U+4}`),o.catchSvg.appendChild(H),y[0].point=P[0].point}else if(k=="line"&&e.options.showCatch){o.worldToScreen.worldToScreen(I[0].point);const B=I[0].start,V=I[0].end;o.catchSvg.innerHTML="";const U=document.createElementNS("http://www.w3.org/2000/svg","line");U.setAttribute("class","catchLine"),U.setAttribute("x1",(B.x+o.reactBoundingClientRect.left).toString()),U.setAttribute("y1",(B.y+o.reactBoundingClientRect.top).toString()),U.setAttribute("x2",(V.x+o.reactBoundingClientRect.left).toString()),U.setAttribute("y2",(V.y+o.reactBoundingClientRect.top).toString()),U.setAttribute("stroke","rgb(8, 223, 215)"),U.setAttribute("stroke-width","2"),o.catchSvg.appendChild(U),y[0].point=I[0].point}else if(k=="face"&&e.options.showCatch){let B=y[0].point.clone(),V=y[0].normal||(y[0].face?y[0].face.normal:null);const U=(V?V.clone():new S.Vector3(0,0,1)).normalize(),H=Math.abs(U.y)<.9?new S.Vector3(0,1,0):new S.Vector3(1,0,0),G=new S.Vector3().crossVectors(U,H).normalize(),$=new S.Vector3().crossVectors(U,G).normalize(),F=.05,ee=[new S.Vector3().copy(G).add($).multiplyScalar(F),new S.Vector3().copy(G).sub($).multiplyScalar(F),new S.Vector3().copy(G).multiplyScalar(-1).sub($).multiplyScalar(F),new S.Vector3().copy(G).multiplyScalar(-1).add($).multiplyScalar(F)].map(ce=>new S.Vector3().copy(B).add(ce)).map(ce=>o.worldToScreen.worldToScreen(ce));o.catchSvg.innerHTML="";const Y=document.createElementNS("http://www.w3.org/2000/svg","polygon");Y.setAttribute("class","catchFace"),Y.setAttribute("points",ee.map(ce=>`${ce.x+o.reactBoundingClientRect.left},${ce.y+o.reactBoundingClientRect.top}`).join(" ")),Y.setAttribute("fill","rgba(1, 238, 255, 0.2)"),Y.setAttribute("stroke","rgb(0, 255, 247)"),Y.setAttribute("stroke-width","1"),o.catchSvg.appendChild(Y)}return y[0];function C(B,V,U){const H=new S.Vector2().subVectors(U,V),G=H.lengthSq();if(G<1e-10)return B.distanceTo(V);const $=new S.Vector2().subVectors(B,V),F=S.MathUtils.clamp($.dot(H)/G,0,1),N=new S.Vector2().copy(H).multiplyScalar(F).add(V);return B.distanceTo(N)}function E(B,V,U){const H=new S.Vector2().subVectors(U,V),G=H.lengthSq();if(G<1e-10)return 0;const $=new S.Vector2().subVectors(B,V);return S.MathUtils.clamp($.dot(H)/G,0,1)}function M(B,V,U){const H=S.MathUtils.clamp(B,0,1);return new S.Vector3().lerpVectors(V,U,H)}}return e}class ra{engine;orbitControls;firstPersonControls;isActive=!0;originDiv=null;handelBehaved;isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(e){this.engine=e,this.init(),this.handelBehaved=Ci(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new Zo(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new zs(this.engine,this.engine.camera,this.engine.renderer.domElement);const e=document.createElement("div");this.originDiv=e,e.className="originDiv",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.width="30px",e.style.height="30px",e.style.borderRadius="50%",e.style.pointerEvents="none",e.style.backgroundImage="url(/assets/svg/rotate-orbit.svg)",this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setMoveSpeed(e){this.firstPersonControls.moveSpeed=e*.1}getMoveSpeed(){return this.firstPersonControls.moveSpeed*10}setApplyCollision(e){this.firstPersonControls.applyCollision=e}getApplyCollision(){return this.firstPersonControls.applyCollision}setApplyGravity(e){this.firstPersonControls.applyGravity=e}getApplyGravity(){return this.firstPersonControls.applyGravity}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls=new zs(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.orbitControls.enabled=!1,this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0}switchDefaultMode(){this.firstPersonControls&&(this.firstPersonControls.enabled=!1),this.orbitControls.enabled=!0}handleMouseUp(e){this.isDragging=!1,this.isDown=!1}handleMouseMove(e){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(e){this.isDown=!0}handleMouseClick(e){this.isDragging=!1,this.isDown=!1}update(){if(this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.orbitControls.enabled){const e=this.engine.controlModule.orbitControls.origin,n=this.engine.worldToScreen.worldToScreen(e);this.originDiv&&this.isDragging?(this.originDiv.style.left=n.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=n.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}}const Mt={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
2
2
 
3
3
  varying vec2 vUv;
4
4
 
@@ -964,11 +964,11 @@
964
964
  `+r.map(_r).join(`
965
965
  `):" "+_r(r[0]):"as no adapter specified";throw new re("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}const Mr={getAdapter:Fl,adapters:Ni};function Ri(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new Wt(null,o)}function Sr(o){return Ri(o),o.headers=Fe.from(o.headers),o.data=zi.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Mr.getAdapter(o.adapter||on.adapter,o)(o).then(function(n){return Ri(o),n.data=zi.call(o,o.transformResponse,n),n.headers=Fe.from(n.headers),n},function(n){return cr(n)||(Ri(o),n&&n.response&&(n.response.data=zi.call(o,o.transformResponse,n.response),n.response.headers=Fe.from(n.response.headers))),Promise.reject(n)})}const Ar="1.13.2",Gn={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{Gn[o]=function(n){return typeof n===o||"a"+(e<1?"n ":" ")+o}});const Cr={};Gn.transitional=function(e,t,n){function i(s,r){return"[Axios v"+Ar+"] Transitional option '"+s+"'"+r+(n?". "+n:"")}return(s,r,a)=>{if(e===!1)throw new re(i(r," has been removed"+(t?" in "+t:"")),re.ERR_DEPRECATED);return t&&!Cr[r]&&(Cr[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(s,r,a):!0}},Gn.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Ul(o,e,t){if(typeof o!="object")throw new re("options must be an object",re.ERR_BAD_OPTION_VALUE);const n=Object.keys(o);let i=n.length;for(;i-- >0;){const s=n[i],r=e[s];if(r){const a=o[s],l=a===void 0||r(a,s,o);if(l!==!0)throw new re("option "+s+" must be "+l,re.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new re("Unknown option "+s,re.ERR_BAD_OPTION)}}const Wn={assertOptions:Ul,validators:Gn},Je=Wn.validators;let Tt=class{constructor(e){this.defaults=e||{},this.interceptors={request:new rr,response:new rr}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=`
966
966
  `+s):n.stack=s}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Ct(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:s}=t;n!==void 0&&Wn.assertOptions(n,{silentJSONParsing:Je.transitional(Je.boolean),forcedJSONParsing:Je.transitional(Je.boolean),clarifyTimeoutError:Je.transitional(Je.boolean)},!1),i!=null&&(W.isFunction(i)?t.paramsSerializer={serialize:i}:Wn.assertOptions(i,{encode:Je.function,serialize:Je.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Wn.assertOptions(t,{baseUrl:Je.spelling("baseURL"),withXsrfToken:Je.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let r=s&&W.merge(s.common,s[t.method]);s&&W.forEach(["delete","get","head","post","put","patch","common"],f=>{delete s[f]}),t.headers=Fe.concat(r,s);const a=[];let l=!0;this.interceptors.request.forEach(function(u){typeof u.runWhen=="function"&&u.runWhen(t)===!1||(l=l&&u.synchronous,a.unshift(u.fulfilled,u.rejected))});const h=[];this.interceptors.response.forEach(function(u){h.push(u.fulfilled,u.rejected)});let c,d=0,m;if(!l){const f=[Sr.bind(this),void 0];for(f.unshift(...a),f.push(...h),m=f.length,c=Promise.resolve(t);d<m;)c=c.then(f[d++],f[d++]);return c}m=a.length;let p=t;for(;d<m;){const f=a[d++],u=a[d++];try{p=f(p)}catch(g){u.call(this,g);break}}try{c=Sr.call(this,p)}catch(f){return Promise.reject(f)}for(d=0,m=h.length;d<m;)c=c.then(h[d++],h[d++]);return c}getUri(e){e=Ct(this.defaults,e);const t=fr(e.baseURL,e.url,e.allowAbsoluteUrls);return sr(t,e.params,e.paramsSerializer)}};W.forEach(["delete","get","head","options"],function(e){Tt.prototype[e]=function(t,n){return this.request(Ct(n||{},{method:e,url:t,data:(n||{}).data}))}}),W.forEach(["post","put","patch"],function(e){function t(n){return function(s,r,a){return this.request(Ct(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:r}))}}Tt.prototype[e]=t(),Tt.prototype[e+"Form"]=t(!0)});let Vl=class Fo{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(s){t=s});const n=this;this.promise.then(i=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s;const r=new Promise(a=>{n.subscribe(a),s=a}).then(i);return r.cancel=function(){n.unsubscribe(s)},r},e(function(s,r,a){n.reason||(n.reason=new Wt(s,r,a),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=n=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Fo(function(i){e=i}),cancel:e}}};function jl(o){return function(t){return o.apply(null,t)}}function Gl(o){return W.isObject(o)&&o.isAxiosError===!0}const Fi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Fi).forEach(([o,e])=>{Fi[e]=o});function Tr(o){const e=new Tt(o),t=Gs(Tt.prototype.request,e);return W.extend(t,Tt.prototype,e,{allOwnKeys:!0}),W.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return Tr(Ct(o,i))},t}const ye=Tr(on);ye.Axios=Tt,ye.CanceledError=Wt,ye.CancelToken=Vl,ye.isCancel=cr,ye.VERSION=Ar,ye.toFormData=Fn,ye.AxiosError=re,ye.Cancel=ye.CanceledError,ye.all=function(e){return Promise.all(e)},ye.spread=jl,ye.isAxiosError=Gl,ye.mergeConfig=Ct,ye.AxiosHeaders=Fe,ye.formToJSON=o=>ar(W.isHTMLForm(o)?new FormData(o):o),ye.getAdapter=Mr.getAdapter,ye.HttpStatusCode=Fi,ye.default=ye;const{Axios:Nd,AxiosError:Rd,CanceledError:Fd,isCancel:Ud,CancelToken:Vd,VERSION:jd,all:Gd,Cancel:Wd,isAxiosError:Xd,spread:Zd,toFormData:qd,AxiosHeaders:Kd,HttpStatusCode:Yd,formToJSON:$d,getAdapter:Hd,mergeConfig:Jd}=ye;function Pr(o,e){var t;if(window.XMLHttpRequest?t=new XMLHttpRequest:window.ActiveXObject?t=new window.ActiveXObject:alert("请升级至最新版本的浏览器"),t!=null){let n=o;t.open("GET",n,!0),t.send(null),t.onreadystatechange=function(){t.readyState==4&&t.status==200&&(t.responseText.includes("</html>",0)&&t.responseText.includes("</body>",0)&&t.responseText.includes("</head>",0)?e(null):e(t.responseText))},t.onloadend=function(){t.readyState==4&&t.status==404&&t.status==502&&e(null)}}}function Wl(o,e){ye({method:"get",responseType:"blob",url:o}).then(t=>{let n=new window.File([t.data],"zipFolder",{type:"zip"});js.loadAsync(n).then(i=>{const s=new Map,r=[];for(let a in i.files){if(i.files[a].dir)continue;const l=i.file(i.files[a].name);if(l){const h=l.async("blob").then(c=>{const d=URL.createObjectURL(c);s.set("/"+i.files[a].name.replace("\\","/"),d)});r.push(h)}}Promise.all(r).then(()=>{e(s)}).catch(a=>{console.error("解压zip文件失败:",a),e(new Map)})}).catch(i=>{console.error("加载zip文件失败:",i),e(new Map)})}).catch(t=>{console.error("下载zip文件失败:",t),e(new Map)})}function Dr(o,e){ye({method:"get",responseType:"blob",url:o}).then(n=>{let i=new window.File([n.data],"semantics",{type:"zip"});js.loadAsync(i).then(s=>{for(let r in s.files)s.file(s.files[r].name).async("blob").then(l=>{t(l,"utf-8",function(h,c){e(c)})})})});function t(n,i,s){var r=new FileReader,a=new Blob([n]);r.onload=function(l){s(null,l.target.result)},r.onerror=function(l){s(l.error,null)},r.readAsText(a,i)}}const Ui=new WeakMap;class Xl extends _.Loader{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,i){const s=new _.FileLoader(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,r=>{this.parse(r,t,i)},n,i)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,_.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,i,s=_.LinearSRGBColorSpace,r=()=>{}){const a={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:s};return this.decodeGeometry(e,a).then(t).catch(r)}decodeGeometry(e,t){const n=JSON.stringify(t);if(Ui.has(e)){const l=Ui.get(e);if(l.key===n)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i;const s=this.workerNextTaskID++,r=e.byteLength,a=this._getWorker(s,r).then(l=>(i=l,new Promise((h,c)=>{i._callbacks[s]={resolve:h,reject:c},i.postMessage({type:"decode",id:s,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return a.catch(()=>!0).then(()=>{i&&s&&this._releaseTask(i,s)}),Ui.set(e,{key:n,promise:a}),a}_createGeometry(e){const t=new _.BufferGeometry;e.index&&t.setIndex(new _.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const{name:i,array:s,itemSize:r,stride:a,vertexColorSpace:l}=e.attributes[n];let h;if(r===a)h=new _.BufferAttribute(s,r);else{const c=new _.InterleavedBuffer(s,a);h=new _.InterleavedBufferAttribute(c,r,0)}i==="color"&&(this._assignVertexColorSpace(h,l),h.normalized=!(s instanceof Float32Array)),t.setAttribute(i,h)}return t}_assignVertexColorSpace(e,t){if(t!==_.SRGBColorSpace)return;const n=new _.Color;for(let i=0,s=e.count;i<s;i++)n.fromBufferAttribute(e,i),_.ColorManagement.colorSpaceToWorking(n,_.SRGBColorSpace),e.setXYZ(i,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new _.FileLoader(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((i,s)=>{n.load(e,i,void 0,s)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const i=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const s=Zl.toString(),r=["/* draco decoder */",i,"","/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join(`
967
- `);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const i=new Worker(this.workerSourceURL);i._callbacks={},i._taskCosts={},i._taskLoad=0,i.postMessage({type:"init",decoderConfig:this.decoderConfig}),i.onmessage=function(s){const r=s.data;switch(r.type){case"decode":i._callbacks[r.id].resolve(r);break;case"error":i._callbacks[r.id].reject(r);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+r.type+'"')}},this.workerPool.push(i)}else this.workerPool.sort(function(i,s){return i._taskLoad>s._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function Zl(){let o,e;onmessage=function(r){const a=r.data;switch(a.type){case"init":o=a.decoderConfig,e=new Promise(function(c){o.onModuleLoaded=function(d){c({draco:d})},DracoDecoderModule(o)});break;case"decode":const l=a.buffer,h=a.taskConfig;e.then(c=>{const d=c.draco,m=new d.Decoder;try{const p=t(d,m,new Int8Array(l),h),f=p.attributes.map(u=>u.array.buffer);p.index&&f.push(p.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:p},f)}catch(p){console.error(p),self.postMessage({type:"error",id:a.id,error:p.message})}finally{d.destroy(m)}});break}};function t(r,a,l,h){const c=h.attributeIDs,d=h.attributeTypes;let m,p;const f=a.GetEncodedGeometryType(l);if(f===r.TRIANGULAR_MESH)m=new r.Mesh,p=a.DecodeArrayToMesh(l,l.byteLength,m);else if(f===r.POINT_CLOUD)m=new r.PointCloud,p=a.DecodeArrayToPointCloud(l,l.byteLength,m);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!p.ok()||m.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+p.error_msg());const u={index:null,attributes:[]};for(const g in c){const y=self[d[g]];let w,x;if(h.useUniqueIDs)x=c[g],w=a.GetAttributeByUniqueId(m,x);else{if(x=a.GetAttributeId(m,r[c[g]]),x===-1)continue;w=a.GetAttribute(m,x)}const v=i(r,a,m,g,y,w);g==="color"&&(v.vertexColorSpace=h.vertexColorSpace),u.attributes.push(v)}return f===r.TRIANGULAR_MESH&&(u.index=n(r,a,m)),r.destroy(m),u}function n(r,a,l){const c=l.num_faces()*3,d=c*4,m=r._malloc(d);a.GetTrianglesUInt32Array(l,d,m);const p=new Uint32Array(r.HEAPF32.buffer,m,c).slice();return r._free(m),{array:p,itemSize:1}}function i(r,a,l,h,c,d){const m=l.num_points(),p=d.num_components(),f=s(r,c),u=p*c.BYTES_PER_ELEMENT,g=Math.ceil(u/4)*4,y=g/c.BYTES_PER_ELEMENT,w=m*u,x=m*g,v=r._malloc(w);a.GetAttributeDataArrayForAllPoints(l,d,f,w,v);const b=new c(r.HEAPF32.buffer,v,w/c.BYTES_PER_ELEMENT);let D;if(u===g)D=b.slice();else{D=new c(x/c.BYTES_PER_ELEMENT);let T=0;for(let k=0,P=b.length;k<P;k++){for(let I=0;I<p;I++)D[T+I]=b[k*p+I];T+=y}}return r._free(v),{name:h,count:m,itemSize:p,array:D,stride:y}}function s(r,a){switch(a){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}var ut=(o=>(o.ModelLoadStart="model-load-start",o.ModelLoadProgress="model-load-progress",o.ModelLoaded="model-loaded",o.ModelError="model-error",o.SelectionChanged="selection-changed",o.HoverChanged="hover-changed",o.Click="click",o.MouseMove="mouse-move",o.CameraChanged="camera-changed",o.CameraIdle="camera-idle",o.ViewportResize="viewport-resize",o.EngineFree="engine-free",o.EngineBusy="engine-busy",o.MeasureChanged="measure-changed",o.SectionMove="section-move",o))(ut||{});function ql(o,e,t,n){let i=0,s=0,r=0,a=o.models.find(p=>p.url==t),l=e.circularMeps,h=e.rectMeps.filter(p=>p.type==="风管"),c=e.rectMeps.filter(p=>p.type==="桥架"),d=e.ellipseMeps,m=o.scene;if(new S.MeshBasicMaterial,new S.BufferGeometry,l&&l.length){let p=[],f=0;for(let u of l)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Circle",m,p,t)}if(h&&h.length){let p=[],f=0;for(let u of h)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Rect",m,p,t)}if(d&&d.length){let p=[],f=0;for(let u of d)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Ellipse",m,p,t)}if(c&&c.length){let p=[],f=0;for(let u of c)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Bridge",m,p,t)}}function Xn(o,e,t,n,i){let s,r,a={width:1,height:1,length:1,diameter:1,color:new S.Color,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};switch(o){case"Rect":r=Zn("Rect",a);break;case"Bridge":r=Zn("Bridge",a);break;case"Circle":r=Zn("Circle",a);break;case"Ellipse":r=Zn("Ellipse",a);break}r&&(s=new S.InstancedMesh(r.geometry,r.material,t.length),s.url=n,e.add(s));let l=[],h=[];for(var c=0;c<t.length;c++){let p=t[c],f=new S.Vector3(p.startPoint.X,0,-p.startPoint.Y),u=new S.Vector3(p.endPoint.X,0,-p.endPoint.Y),g=new S.Vector3(p.startPoint.X,p.startPoint.Z,-p.startPoint.Y),y=new S.Vector3(p.endPoint.X,p.endPoint.Z,-p.endPoint.Y),w=0,x=0,v=0;if(Math.abs(u.clone().sub(f.clone()).z)<.01&&Math.abs(u.clone().sub(f.clone()).x)<.01){if(w=(p.startPoint.Z>p.endPoint.Z?1:-1)*Math.PI*.5,p.base_x!=null){var d=new S.Vector3(p.base_x.X,0,-p.base_x.Y);x=(d.clone().cross(new S.Vector3(0,0,1)).y<=0?1:-1)*d.angleTo(new S.Vector3(0,0,1))+Math.PI*.5}}else x=(u.clone().sub(f.clone()).cross(new S.Vector3(0,0,1)).y>0?-1:1)*u.clone().sub(f.clone()).angleTo(new S.Vector3(0,0,1)),w=(p.startPoint.Z>p.endPoint.Z?1:-1)*u.clone().sub(f.clone()).angleTo(y.clone().sub(g.clone()));let b=new S.Matrix4;const D=new S.Euler(w,x,v,"YXZ");let T=b.clone().makeRotationFromEuler(D),k,P;o==="Circle"?(k=p.diameter,P=p.diameter):(k=p.width,P=p.height);let I=b.clone().makeScale(k,P,p.length);b.multiplyMatrices(T,I),b.setPosition(p.position.x,p.position.y,p.position.z),s.setMatrixAt(c,b.clone()),s.setColorAt(c,p.color),s.geometry.computeBoundingBox();let z=s.geometry.boundingBox.min.clone().applyMatrix4(b.clone()),C=s.geometry.boundingBox.max.clone().applyMatrix4(b.clone()),E=new S.Vector3(Math.min(z.x,C.x),Math.min(z.y,C.y),Math.min(z.z,C.z)),M=new S.Vector3(Math.max(z.x,C.x),Math.max(z.y,C.y),Math.max(z.z,C.z)),B=E.clone().add(M.clone()).multiplyScalar(.5),V={name:p.name,min:E,max:M,center:B,dbid:c,materialName:r.material.name},U=null,H=null;o==="Circle"&&(U={x:p.startPoint.X*.3048,y:p.startPoint.Z*.3048,z:-p.startPoint.Y*.3048},H={x:p.endPoint.X*.3048,y:p.endPoint.Z*.3048,z:-p.endPoint.Y*.3048},V.minC=U,V.maxC=H),s.ids||(s.ids=[]),s.matrixs||(s.matrixs=[]),s.matrixs.push(b.clone()),h.push(b.clone()),s.ids.push(Number(p.id)),l.push(V)}s.castShadow=!0,s.ElementInfos=l,s.name="rootModel",s.TypeName="InstancedMesh-Pipe",s.PipeType=o,s.MeshId=null,s.realMaterial=s.material.clone(),s.originalMaterial=s.material.clone(),s.matrixsClone=h;let m=[];m={geometry:s.geometry,matrix:s.matrix,position:s.position,rotation:s.rotation},s.meshs=m,s.instanceMatrix&&s.instanceMatrix.array&&(s.cloneInstanceMatrix=Array.from(s.instanceMatrix.array))}function Zn(o,e,t){let n=new S.Shape;switch(e.width=e.width*.3048,e.height=e.height*.3048,e.diameter=e.diameter*.3048,o){case"Rect":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Ellipse":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Bridge":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(-e.width/2+.01,e.height/2),n.lineTo(-e.width/2+.01,-e.height/2+.01),n.lineTo(e.width/2-.01,-e.height/2+.01),n.lineTo(e.width/2-.01,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Circle":n.moveTo(0,0),n.absarc(0,0,e.diameter*.5,0,Math.PI*2,!1);break}const i={depth:e.length*.3048,bevelEnabled:!1};return s(n,i,e.color,e.position,e.rotation);function s(r,a,l,h,c){let d=new S.ExtrudeGeometry(r,a),m=new S.MeshStandardMaterial({color:l,side:S.DoubleSide}),p=new S.Mesh(d,m);return p.position.set(h.x,h.y,h.z),p.rotation._order="YXZ",p.rotation.set(c.x,c.y,c.z),p}}function kr(o,e=!1){const t=o[0].index!==null,n=new Set(Object.keys(o[0].attributes)),i=new Set(Object.keys(o[0].morphAttributes)),s={},r={},a=o[0].morphTargetsRelative,l=new _.BufferGeometry;let h=0;for(let c=0;c<o.length;++c){const d=o[c];let m=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in d.attributes){if(!n.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;s[p]===void 0&&(s[p]=[]),s[p].push(d.attributes[p]),m++}if(m!==n.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in d.morphAttributes){if(!i.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". .morphAttributes must be consistent throughout all geometries."),null;r[p]===void 0&&(r[p]=[]),r[p].push(d.morphAttributes[p])}if(e){let p;if(t)p=d.index.count;else if(d.attributes.position!==void 0)p=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". The geometry must have either an index or a position attribute"),null;l.addGroup(h,p,c),h+=p}}if(t){let c=0;const d=[];for(let m=0;m<o.length;++m){const p=o[m].index;for(let f=0;f<p.count;++f)d.push(p.getX(f)+c);c+=o[m].attributes.position.count}l.setIndex(d)}for(const c in s){const d=Ir(s[c]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+c+" attribute."),null;l.setAttribute(c,d)}for(const c in r){const d=r[c][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[c]=[];for(let m=0;m<d;++m){const p=[];for(let u=0;u<r[c].length;++u)p.push(r[c][u][m]);const f=Ir(p);if(!f)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+c+" morphAttribute."),null;l.morphAttributes[c].push(f)}}return l}function Ir(o){let e,t,n,i=-1,s=0;for(let h=0;h<o.length;++h){const c=o[h];if(e===void 0&&(e=c.array.constructor),e!==c.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=c.itemSize),t!==c.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(n===void 0&&(n=c.normalized),n!==c.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(i===-1&&(i=c.gpuType),i!==c.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=c.count*t}const r=new e(s),a=new _.BufferAttribute(r,t,n);let l=0;for(let h=0;h<o.length;++h){const c=o[h];if(c.isInterleavedBufferAttribute){const d=l/t;for(let m=0,p=c.count;m<p;m++)for(let f=0;f<t;f++){const u=c.getComponent(m,f);a.setComponent(m+d,f,u)}}else r.set(c.array,l);l+=c.count*t}return i!==void 0&&(a.gpuType=i),a}function Lr(o,e){if(e===_.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),o;if(e===_.TriangleFanDrawMode||e===_.TriangleStripDrawMode){let t=o.getIndex();if(t===null){const r=[],a=o.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)r.push(l);o.setIndex(r),t=o.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),o}const n=t.count-2,i=[];if(e===_.TriangleFanDrawMode)for(let r=1;r<=n;r++)i.push(t.getX(0)),i.push(t.getX(r)),i.push(t.getX(r+1));else for(let r=0;r<n;r++)r%2===0?(i.push(t.getX(r)),i.push(t.getX(r+1)),i.push(t.getX(r+2))):(i.push(t.getX(r+2)),i.push(t.getX(r+1)),i.push(t.getX(r)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=o.clone();return s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),o}class Kl extends _.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Ql(t)}),this.register(function(t){return new ec(t)}),this.register(function(t){return new cc(t)}),this.register(function(t){return new hc(t)}),this.register(function(t){return new uc(t)}),this.register(function(t){return new nc(t)}),this.register(function(t){return new ic(t)}),this.register(function(t){return new sc(t)}),this.register(function(t){return new rc(t)}),this.register(function(t){return new Jl(t)}),this.register(function(t){return new oc(t)}),this.register(function(t){return new tc(t)}),this.register(function(t){return new lc(t)}),this.register(function(t){return new ac(t)}),this.register(function(t){return new $l(t)}),this.register(function(t){return new dc(t)}),this.register(function(t){return new fc(t)})}load(e,t,n,i){const s=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const h=_.LoaderUtils.extractUrlBase(e);r=_.LoaderUtils.resolveURL(h,this.path)}else r=_.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(h){i?i(h):console.error(h),s.manager.itemError(e),s.manager.itemEnd(e)},l=new _.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(h){try{s.parse(h,r,function(c){t(c),s.manager.itemEnd(e)},a)}catch(c){a(c)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let s;const r={},a={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===Er){try{r[le.KHR_BINARY_GLTF]=new pc(e)}catch(d){i&&i(d);return}s=JSON.parse(r[le.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new Tc(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c<this.pluginCallbacks.length;c++){const d=this.pluginCallbacks[c](h);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[d.name]=d,r[d.name]=!0}if(s.extensionsUsed)for(let c=0;c<s.extensionsUsed.length;++c){const d=s.extensionsUsed[c],m=s.extensionsRequired||[];switch(d){case le.KHR_MATERIALS_UNLIT:r[d]=new Hl;break;case le.KHR_DRACO_MESH_COMPRESSION:r[d]=new mc(s,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:r[d]=new gc;break;case le.KHR_MESH_QUANTIZATION:r[d]=new yc;break;default:m.indexOf(d)>=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}h.setExtensions(r),h.setPlugins(a),h.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,s){n.parse(e,t,i,s)})}}function Yl(){let o={};return{get:function(e){return o[e]},add:function(e,t){o[e]=t},remove:function(e){delete o[e]},removeAll:function(){o={}}}}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class $l{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const s=t[n];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let h;const c=new _.Color(16777215);l.color!==void 0&&c.setRGB(l.color[0],l.color[1],l.color[2],_.LinearSRGBColorSpace);const d=l.range!==void 0?l.range:0;switch(l.type){case"directional":h=new _.DirectionalLight(c),h.target.position.set(0,0,-1),h.add(h.target);break;case"point":h=new _.PointLight(c),h.distance=d;break;case"spot":h=new _.SpotLight(c),h.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,h.angle=l.spot.outerConeAngle,h.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,h.target.position.set(0,0,-1),h.add(h.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return h.position.set(0,0,0),Qe(h,l),l.intensity!==void 0&&(h.intensity=l.intensity),h.name=t.createUniqueName(l.name||"light_"+e),i=Promise.resolve(h),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,s=n.json.nodes[e],a=(s.extensions&&s.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return n._getNodeRef(t.cache,a,l)})}}class Hl{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return _.MeshBasicMaterial}extendParams(e,t,n){const i=[];e.color=new _.Color(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const r=s.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],_.LinearSRGBColorSpace),e.opacity=r[3]}s.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",s.baseColorTexture,_.SRGBColorSpace))}return Promise.all(i)}}class Jl{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class Ql{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];if(r.clearcoatFactor!==void 0&&(t.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&s.push(n.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&s.push(n.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(s.push(n.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){const a=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new _.Vector2(a,a)}return Promise.all(s)}}class ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}}class tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return r.iridescenceFactor!==void 0&&(t.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&s.push(n.assignTexture(t,"iridescenceMap",r.iridescenceTexture)),r.iridescenceIor!==void 0&&(t.iridescenceIOR=r.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),r.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),r.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),r.iridescenceThicknessTexture!==void 0&&s.push(n.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(s)}}class nc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new _.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const r=i.extensions[this.name];if(r.sheenColorFactor!==void 0){const a=r.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],_.LinearSRGBColorSpace)}return r.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&s.push(n.assignTexture(t,"sheenColorMap",r.sheenColorTexture,_.SRGBColorSpace)),r.sheenRoughnessTexture!==void 0&&s.push(n.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(s)}}class ic{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return r.transmissionFactor!==void 0&&(t.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&s.push(n.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(s)}}class sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];t.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&s.push(n.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const a=r.attenuationColor||[1,1,1];return t.attenuationColor=new _.Color().setRGB(a[0],a[1],a[2],_.LinearSRGBColorSpace),Promise.all(s)}}class rc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class oc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];t.specularIntensity=r.specularFactor!==void 0?r.specularFactor:1,r.specularTexture!==void 0&&s.push(n.assignTexture(t,"specularIntensityMap",r.specularTexture));const a=r.specularColorFactor||[1,1,1];return t.specularColor=new _.Color().setRGB(a[0],a[1],a[2],_.LinearSRGBColorSpace),r.specularColorTexture!==void 0&&s.push(n.assignTexture(t,"specularColorMap",r.specularColorTexture,_.SRGBColorSpace)),Promise.all(s)}}class ac{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return t.bumpScale=r.bumpFactor!==void 0?r.bumpFactor:1,r.bumpTexture!==void 0&&s.push(n.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(s)}}class lc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return r.anisotropyStrength!==void 0&&(t.anisotropy=r.anisotropyStrength),r.anisotropyRotation!==void 0&&(t.anisotropyRotation=r.anisotropyRotation),r.anisotropyTexture!==void 0&&s.push(n.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(s)}}class cc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const s=i.extensions[this.name],r=t.options.ktx2Loader;if(!r){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,r)}}class hc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const r=s.extensions[t],a=i.images[r.source];let l=n.textureLoader;if(a.uri){const h=n.options.manager.getHandler(a.uri);h!==null&&(l=h)}return n.loadTextureImage(e,r.source,l)}}class uc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const r=s.extensions[t],a=i.images[r.source];let l=n.textureLoader;if(a.uri){const h=n.options.manager.getHandler(a.uri);h!==null&&(l=h)}return n.loadTextureImage(e,r.source,l)}}class dc{constructor(e){this.name=le.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(a){const l=i.byteOffset||0,h=i.byteLength||0,c=i.count,d=i.byteStride,m=new Uint8Array(a,l,h);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(c,d,m,i.mode,i.filter).then(function(p){return p.buffer}):r.ready.then(function(){const p=new ArrayBuffer(c*d);return r.decodeGltfBuffer(new Uint8Array(p),c,d,m,i.mode,i.filter),p})})}else return null}}class fc{constructor(e){this.name=le.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const h of i.primitives)if(h.mode!==Ve.TRIANGLES&&h.mode!==Ve.TRIANGLE_STRIP&&h.mode!==Ve.TRIANGLE_FAN&&h.mode!==void 0)return null;const r=n.extensions[this.name].attributes,a=[],l={};for(const h in r)a.push(this.parser.getDependency("accessor",r[h]).then(c=>(l[h]=c,l[h])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(h=>{const c=h.pop(),d=c.isGroup?c.children:[c],m=h[0].count,p=[];for(const f of d){const u=new _.Matrix4,g=new _.Vector3,y=new _.Quaternion,w=new _.Vector3(1,1,1),x=new _.InstancedMesh(f.geometry,f.material,m);for(let v=0;v<m;v++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,v),l.ROTATION&&y.fromBufferAttribute(l.ROTATION,v),l.SCALE&&w.fromBufferAttribute(l.SCALE,v),x.setMatrixAt(v,u.compose(g,y,w));for(const v in l)if(v==="_COLOR_0"){const b=l[v];x.instanceColor=new _.InstancedBufferAttribute(b.array,b.itemSize,b.normalized)}else v!=="TRANSLATION"&&v!=="ROTATION"&&v!=="SCALE"&&f.geometry.setAttribute(v,l[v]);_.Object3D.prototype.copy.call(x,f),this.parser.assignFinalMaterial(x),p.push(x)}return c.isGroup?(c.clear(),c.add(...p),c):p[0]}))}}const Er="glTF",ln=12,Br={JSON:1313821514,BIN:5130562};class pc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ln),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Er)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-ln,s=new DataView(e,ln);let r=0;for(;r<i;){const a=s.getUint32(r,!0);r+=4;const l=s.getUint32(r,!0);if(r+=4,l===Br.JSON){const h=new Uint8Array(e,ln+r,a);this.content=n.decode(h)}else if(l===Br.BIN){const h=ln+r;this.body=e.slice(h,h+a)}r+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class mc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,a={},l={},h={};for(const c in r){const d=ji[c]||c.toLowerCase();a[d]=r[c]}for(const c in e.attributes){const d=ji[c]||c.toLowerCase();if(r[c]!==void 0){const m=n.accessors[e.attributes[c]],p=Xt[m.componentType];h[d]=p.name,l[d]=m.normalized===!0}}return t.getDependency("bufferView",s).then(function(c){return new Promise(function(d,m){i.decodeDracoFile(c,function(p){for(const f in p.attributes){const u=p.attributes[f],g=l[f];g!==void 0&&(u.normalized=g)}d(p)},a,h,_.LinearSRGBColorSpace,m)})})}}class gc{constructor(){this.name=le.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class yc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Or extends _.Interpolant{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let r=0;r!==i;r++)t[r]=n[s+r];return t}interpolate_(e,t,n,i){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,l=a*2,h=a*3,c=i-t,d=(n-t)/c,m=d*d,p=m*d,f=e*h,u=f-h,g=-2*p+3*m,y=p-m,w=1-g,x=y-m+d;for(let v=0;v!==a;v++){const b=r[u+v+a],D=r[u+v+l]*c,T=r[f+v+a],k=r[f+v]*c;s[v]=w*b+x*D+g*T+y*k}return s}}const wc=new _.Quaternion;class xc extends Or{interpolate_(e,t,n,i){const s=super.interpolate_(e,t,n,i);return wc.fromArray(s).normalize().toArray(s),s}}const Ve={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Xt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},zr={9728:_.NearestFilter,9729:_.LinearFilter,9984:_.NearestMipmapNearestFilter,9985:_.LinearMipmapNearestFilter,9986:_.NearestMipmapLinearFilter,9987:_.LinearMipmapLinearFilter},Nr={33071:_.ClampToEdgeWrapping,33648:_.MirroredRepeatWrapping,10497:_.RepeatWrapping},Vi={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ji={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},dt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},vc={CUBICSPLINE:void 0,LINEAR:_.InterpolateLinear,STEP:_.InterpolateDiscrete},Gi={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function bc(o){return o.DefaultMaterial===void 0&&(o.DefaultMaterial=new _.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:_.FrontSide})),o.DefaultMaterial}function Pt(o,e,t){for(const n in t.extensions)o[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Qe(o,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(o.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function _c(o,e,t){let n=!1,i=!1,s=!1;for(let h=0,c=e.length;h<c;h++){const d=e[h];if(d.POSITION!==void 0&&(n=!0),d.NORMAL!==void 0&&(i=!0),d.COLOR_0!==void 0&&(s=!0),n&&i&&s)break}if(!n&&!i&&!s)return Promise.resolve(o);const r=[],a=[],l=[];for(let h=0,c=e.length;h<c;h++){const d=e[h];if(n){const m=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):o.attributes.position;r.push(m)}if(i){const m=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):o.attributes.normal;a.push(m)}if(s){const m=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):o.attributes.color;l.push(m)}}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(l)]).then(function(h){const c=h[0],d=h[1],m=h[2];return n&&(o.morphAttributes.position=c),i&&(o.morphAttributes.normal=d),s&&(o.morphAttributes.color=m),o.morphTargetsRelative=!0,o})}function Mc(o,e){if(o.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)o.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(o.morphTargetInfluences.length===t.length){o.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)o.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Sc(o){let e;const t=o.extensions&&o.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Wi(t.attributes):e=o.indices+":"+Wi(o.attributes)+":"+o.mode,o.targets!==void 0)for(let n=0,i=o.targets.length;n<i;n++)e+=":"+Wi(o.targets[n]);return e}function Wi(o){let e="";const t=Object.keys(o).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+o[t[n]]+";";return e}function Xi(o){switch(o){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Ac(o){return o.search(/\.jpe?g($|\?)/i)>0||o.search(/^data\:image\/jpeg/)===0?"image/jpeg":o.search(/\.webp($|\?)/i)>0||o.search(/^data\:image\/webp/)===0?"image/webp":o.search(/\.ktx2($|\?)/i)>0||o.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Cc=new _.Matrix4;class Tc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Yl,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,r=-1;if(typeof navigator<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const l=a.match(/Version\/(\d+)/);i=n&&l?parseInt(l[1],10):-1,s=a.indexOf("Firefox")>-1,r=s?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||s&&r<98?this.textureLoader=new _.TextureLoader(this.options.manager):this.textureLoader=new _.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new _.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(r){const a={scene:r[0][i.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:i.asset,parser:n,userData:{}};return Pt(s,a,i),Qe(a,i),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,s=t.length;i<s;i++){const r=t[i].joints;for(let a=0,l=r.length;a<l;a++)e[r[a]].isBone=!0}for(let i=0,s=e.length;i<s;i++){const r=e[i];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),s=(r,a)=>{const l=this.associations.get(r);l!=null&&this.associations.set(a,l);for(const[h,c]of r.children.entries())s(c,a.children[h])};return s(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const s=e(t[i]);s&&n.push(s)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":i=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(s,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(s,r){n.load(_.LoaderUtils.resolveURL(t.uri,i.path),s,void 0,function(){r(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,s=t.byteOffset||0;return n.slice(s,s+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const r=Vi[i.type],a=Xt[i.componentType],l=i.normalized===!0,h=new a(i.count*r);return Promise.resolve(new _.BufferAttribute(h,r,l))}const s=[];return i.bufferView!==void 0?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),i.sparse!==void 0&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then(function(r){const a=r[0],l=Vi[i.type],h=Xt[i.componentType],c=h.BYTES_PER_ELEMENT,d=c*l,m=i.byteOffset||0,p=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,f=i.normalized===!0;let u,g;if(p&&p!==d){const y=Math.floor(m/p),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+y+":"+i.count;let x=t.cache.get(w);x||(u=new h(a,y*p,i.count*p/c),x=new _.InterleavedBuffer(u,p/c),t.cache.add(w,x)),g=new _.InterleavedBufferAttribute(x,l,m%p/c,f)}else a===null?u=new h(i.count*l):u=new h(a,m,i.count*l),g=new _.BufferAttribute(u,l,f);if(i.sparse!==void 0){const y=Vi.SCALAR,w=Xt[i.sparse.indices.componentType],x=i.sparse.indices.byteOffset||0,v=i.sparse.values.byteOffset||0,b=new w(r[1],x,i.sparse.count*y),D=new h(r[2],v,i.sparse.count*l);a!==null&&(g=new _.BufferAttribute(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let T=0,k=b.length;T<k;T++){const P=b[T];if(g.setX(P,D[T*l]),l>=2&&g.setY(P,D[T*l+1]),l>=3&&g.setZ(P,D[T*l+2]),l>=4&&g.setW(P,D[T*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=f}return g})}loadTexture(e){const t=this.json,n=this.options,s=t.textures[e].source,r=t.images[s];let a=this.textureLoader;if(r.uri){const l=n.manager.getHandler(r.uri);l!==null&&(a=l)}return this.loadTextureImage(e,s,a)}loadTextureImage(e,t,n){const i=this,s=this.json,r=s.textures[e],a=s.images[t],l=(a.uri||a.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const h=this.loadImageSource(t,n).then(function(c){c.flipY=!1,c.name=r.name||a.name||"",c.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(c.name=a.uri);const m=(s.samplers||{})[r.sampler]||{};return c.magFilter=zr[m.magFilter]||_.LinearFilter,c.minFilter=zr[m.minFilter]||_.LinearMipmapLinearFilter,c.wrapS=Nr[m.wrapS]||_.RepeatWrapping,c.wrapT=Nr[m.wrapT]||_.RepeatWrapping,c.generateMipmaps=!c.isCompressedTexture&&c.minFilter!==_.NearestFilter&&c.minFilter!==_.LinearFilter,i.associations.set(c,{textures:e}),c}).catch(function(){return null});return this.textureCache[l]=h,h}loadImageSource(e,t){const n=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=i.images[e],a=self.URL||self.webkitURL;let l=r.uri||"",h=!1;if(r.bufferView!==void 0)l=n.getDependency("bufferView",r.bufferView).then(function(d){h=!0;const m=new Blob([d],{type:r.mimeType});return l=a.createObjectURL(m),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(l).then(function(d){return new Promise(function(m,p){let f=m;t.isImageBitmapLoader===!0&&(f=function(u){const g=new _.Texture(u);g.needsUpdate=!0,m(g)}),t.load(_.LoaderUtils.resolveURL(d,s.path),f,void 0,p)})}).then(function(d){return h===!0&&a.revokeObjectURL(l),Qe(d,r),d.userData.mimeType=r.mimeType||Ac(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=c,c}assignTexture(e,t,n,i){const s=this;return this.getDependency("texture",n.index).then(function(r){if(!r)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(r=r.clone(),r.channel=n.texCoord),s.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=s.associations.get(r);r=s.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(r,a),s.associations.set(r,l)}}return i!==void 0&&(r.colorSpace=i),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new _.PointsMaterial,_.Material.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(a,l)),n=l}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new _.LineBasicMaterial,_.Material.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(a,l)),n=l}if(i||s||r){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),s&&(a+="vertex-colors:"),r&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=n.clone(),s&&(l.vertexColors=!0),r&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(n))),n=l}e.material=n}getMaterialType(){return _.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,i=this.extensions,s=n.materials[e];let r;const a={},l=s.extensions||{},h=[];if(l[le.KHR_MATERIALS_UNLIT]){const d=i[le.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),h.push(d.extendParams(a,s,t))}else{const d=s.pbrMetallicRoughness||{};if(a.color=new _.Color(1,1,1),a.opacity=1,Array.isArray(d.baseColorFactor)){const m=d.baseColorFactor;a.color.setRGB(m[0],m[1],m[2],_.LinearSRGBColorSpace),a.opacity=m[3]}d.baseColorTexture!==void 0&&h.push(t.assignTexture(a,"map",d.baseColorTexture,_.SRGBColorSpace)),a.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,a.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(h.push(t.assignTexture(a,"metalnessMap",d.metallicRoughnessTexture)),h.push(t.assignTexture(a,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(m){return m.getMaterialType&&m.getMaterialType(e)}),h.push(Promise.all(this._invokeAll(function(m){return m.extendMaterialParams&&m.extendMaterialParams(e,a)})))}s.doubleSided===!0&&(a.side=_.DoubleSide);const c=s.alphaMode||Gi.OPAQUE;if(c===Gi.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,c===Gi.MASK&&(a.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&r!==_.MeshBasicMaterial&&(h.push(t.assignTexture(a,"normalMap",s.normalTexture)),a.normalScale=new _.Vector2(1,1),s.normalTexture.scale!==void 0)){const d=s.normalTexture.scale;a.normalScale.set(d,d)}if(s.occlusionTexture!==void 0&&r!==_.MeshBasicMaterial&&(h.push(t.assignTexture(a,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&r!==_.MeshBasicMaterial){const d=s.emissiveFactor;a.emissive=new _.Color().setRGB(d[0],d[1],d[2],_.LinearSRGBColorSpace)}return s.emissiveTexture!==void 0&&r!==_.MeshBasicMaterial&&h.push(t.assignTexture(a,"emissiveMap",s.emissiveTexture,_.SRGBColorSpace)),Promise.all(h).then(function(){const d=new r(a);return s.name&&(d.name=s.name),Qe(d,s),t.associations.set(d,{materials:e}),s.extensions&&Pt(i,d,s),d})}createUniqueName(e){const t=_.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function s(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return Rr(l,a,t)})}const r=[];for(let a=0,l=e.length;a<l;a++){const h=e[a],c=Sc(h),d=i[c];if(d)r.push(d.promise);else{let m;h.extensions&&h.extensions[le.KHR_DRACO_MESH_COMPRESSION]?m=s(h):m=Rr(new _.BufferGeometry,h,t),i[c]={primitive:h,promise:m},r.push(m)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,i=this.extensions,s=n.meshes[e],r=s.primitives,a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l].material===void 0?bc(this.cache):this.getDependency("material",r[l].material);a.push(c)}return a.push(t.loadGeometries(r)),Promise.all(a).then(function(l){const h=l.slice(0,l.length-1),c=l[l.length-1],d=[];for(let p=0,f=c.length;p<f;p++){const u=c[p],g=r[p];let y;const w=h[p];if(g.mode===Ve.TRIANGLES||g.mode===Ve.TRIANGLE_STRIP||g.mode===Ve.TRIANGLE_FAN||g.mode===void 0)y=s.isSkinnedMesh===!0?new _.SkinnedMesh(u,w):new _.Mesh(u,w),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),g.mode===Ve.TRIANGLE_STRIP?y.geometry=Lr(y.geometry,_.TriangleStripDrawMode):g.mode===Ve.TRIANGLE_FAN&&(y.geometry=Lr(y.geometry,_.TriangleFanDrawMode));else if(g.mode===Ve.LINES)y=new _.LineSegments(u,w);else if(g.mode===Ve.LINE_STRIP)y=new _.Line(u,w);else if(g.mode===Ve.LINE_LOOP)y=new _.LineLoop(u,w);else if(g.mode===Ve.POINTS)y=new _.Points(u,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(y.geometry.morphAttributes).length>0&&Mc(y,s),y.name=t.createUniqueName(s.name||"mesh_"+e),Qe(y,s),g.extensions&&Pt(i,y,g),t.assignFinalMaterial(y),d.push(y)}for(let p=0,f=d.length;p<f;p++)t.associations.set(d[p],{meshes:e,primitives:p});if(d.length===1)return s.extensions&&Pt(i,d[0],s),d[0];const m=new _.Group;s.extensions&&Pt(i,m,s),t.associations.set(m,{meshes:e});for(let p=0,f=d.length;p<f;p++)m.add(d[p]);return m})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new _.PerspectiveCamera(_.MathUtils.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new _.OrthographicCamera(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Qe(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,s=t.joints.length;i<s;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const s=i.pop(),r=i,a=[],l=[];for(let h=0,c=r.length;h<c;h++){const d=r[h];if(d){a.push(d);const m=new _.Matrix4;s!==null&&m.fromArray(s.array,h*16),l.push(m)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[h])}return new _.Skeleton(a,l)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,r=[],a=[],l=[],h=[],c=[];for(let d=0,m=i.channels.length;d<m;d++){const p=i.channels[d],f=i.samplers[p.sampler],u=p.target,g=u.node,y=i.parameters!==void 0?i.parameters[f.input]:f.input,w=i.parameters!==void 0?i.parameters[f.output]:f.output;u.node!==void 0&&(r.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",y)),l.push(this.getDependency("accessor",w)),h.push(f),c.push(u))}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(l),Promise.all(h),Promise.all(c)]).then(function(d){const m=d[0],p=d[1],f=d[2],u=d[3],g=d[4],y=[];for(let x=0,v=m.length;x<v;x++){const b=m[x],D=p[x],T=f[x],k=u[x],P=g[x];if(b===void 0)continue;b.updateMatrix&&b.updateMatrix();const I=n._createAnimationTracks(b,D,T,k,P);if(I)for(let z=0;z<I.length;z++)y.push(I[z])}const w=new _.AnimationClip(s,void 0,y);return Qe(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(s){const r=n._getNodeRef(n.meshCache,i.mesh,s);return i.weights!==void 0&&r.traverse(function(a){if(a.isMesh)for(let l=0,h=i.weights.length;l<h;l++)a.morphTargetInfluences[l]=i.weights[l]}),r})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],s=n._loadNodeShallow(e),r=[],a=i.children||[];for(let h=0,c=a.length;h<c;h++)r.push(n.getDependency("node",a[h]));const l=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([s,Promise.all(r),l]).then(function(h){const c=h[0],d=h[1],m=h[2];m!==null&&c.traverse(function(p){p.isSkinnedMesh&&p.bind(m,Cc)});for(let p=0,f=d.length;p<f;p++)c.add(d[p]);return c})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],r=s.name?i.createUniqueName(s.name):"",a=[],l=i._invokeOne(function(h){return h.createNodeMesh&&h.createNodeMesh(e)});return l&&a.push(l),s.camera!==void 0&&a.push(i.getDependency("camera",s.camera).then(function(h){return i._getNodeRef(i.cameraCache,s.camera,h)})),i._invokeAll(function(h){return h.createNodeAttachment&&h.createNodeAttachment(e)}).forEach(function(h){a.push(h)}),this.nodeCache[e]=Promise.all(a).then(function(h){let c;if(s.isBone===!0?c=new _.Bone:h.length>1?c=new _.Group:h.length===1?c=h[0]:c=new _.Object3D,c!==h[0])for(let d=0,m=h.length;d<m;d++)c.add(h[d]);if(s.name&&(c.userData.name=s.name,c.name=r),Qe(c,s),s.extensions&&Pt(n,c,s),s.matrix!==void 0){const d=new _.Matrix4;d.fromArray(s.matrix),c.applyMatrix4(d)}else s.translation!==void 0&&c.position.fromArray(s.translation),s.rotation!==void 0&&c.quaternion.fromArray(s.rotation),s.scale!==void 0&&c.scale.fromArray(s.scale);if(!i.associations.has(c))i.associations.set(c,{});else if(s.mesh!==void 0&&i.meshCache.refs[s.mesh]>1){const d=i.associations.get(c);i.associations.set(c,{...d})}return i.associations.get(c).nodes=e,c}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,s=new _.Group;n.name&&(s.name=i.createUniqueName(n.name)),Qe(s,n),n.extensions&&Pt(t,s,n);const r=n.nodes||[],a=[];for(let l=0,h=r.length;l<h;l++)a.push(i.getDependency("node",r[l]));return Promise.all(a).then(function(l){for(let c=0,d=l.length;c<d;c++)s.add(l[c]);const h=c=>{const d=new Map;for(const[m,p]of i.associations)(m instanceof _.Material||m instanceof _.Texture)&&d.set(m,p);return c.traverse(m=>{const p=i.associations.get(m);p!=null&&d.set(m,p)}),d};return i.associations=h(s),s})}_createAnimationTracks(e,t,n,i,s){const r=[],a=e.name?e.name:e.uuid,l=[];dt[s.path]===dt.weights?e.traverse(function(m){m.morphTargetInfluences&&l.push(m.name?m.name:m.uuid)}):l.push(a);let h;switch(dt[s.path]){case dt.weights:h=_.NumberKeyframeTrack;break;case dt.rotation:h=_.QuaternionKeyframeTrack;break;case dt.translation:case dt.scale:h=_.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:h=_.NumberKeyframeTrack;break;case 2:case 3:default:h=_.VectorKeyframeTrack;break}break}const c=i.interpolation!==void 0?vc[i.interpolation]:_.InterpolateLinear,d=this._getArrayFromAccessor(n);for(let m=0,p=l.length;m<p;m++){const f=new h(l[m]+"."+dt[s.path],t.array,d,c);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(f),r.push(f)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Xi(t.constructor),i=new Float32Array(t.length);for(let s=0,r=t.length;s<r;s++)i[s]=t[s]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof _.QuaternionKeyframeTrack?xc:Or;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Pc(o,e,t){const n=e.attributes,i=new _.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],l=a.min,h=a.max;if(l!==void 0&&h!==void 0){if(i.set(new _.Vector3(l[0],l[1],l[2]),new _.Vector3(h[0],h[1],h[2])),a.normalized){const c=Xi(Xt[a.componentType]);i.min.multiplyScalar(c),i.max.multiplyScalar(c)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const a=new _.Vector3,l=new _.Vector3;for(let h=0,c=s.length;h<c;h++){const d=s[h];if(d.POSITION!==void 0){const m=t.json.accessors[d.POSITION],p=m.min,f=m.max;if(p!==void 0&&f!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(f[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(f[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(f[2]))),m.normalized){const u=Xi(Xt[m.componentType]);l.multiplyScalar(u)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}o.boundingBox=i;const r=new _.Sphere;i.getCenter(r.center),r.radius=i.min.distanceTo(i.max)/2,o.boundingSphere=r}function Rr(o,e,t){const n=e.attributes,i=[];function s(r,a){return t.getDependency("accessor",r).then(function(l){o.setAttribute(a,l)})}for(const r in n){const a=ji[r]||r.toLowerCase();a in o.attributes||i.push(s(n[r],a))}if(e.indices!==void 0&&!o.index){const r=t.getDependency("accessor",e.indices).then(function(a){o.setIndex(a)});i.push(r)}return _.ColorManagement.workingColorSpace!==_.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${_.ColorManagement.workingColorSpace}" not supported.`),Qe(o,e),Pc(o,e,t),Promise.all(i).then(function(){return e.targets!==void 0?_c(o,e.targets,t):o})}function Dc(o,e,t){let n=new S.Group;n.name=e,o.scene.add(n),Dr(e+"/info",i=>{let s=JSON.parse(i);o.engineStatus.models.push({type:"light",info:s,name:s.baseInfo.name,status:"loading",url:e,elements:new Map}),o.models==null&&(o.models=[]),o.models.push({url:e,nodesMap:new Map,boundingBox:{min:new S.Vector3(s.baseInfo.min.X*.3048,s.baseInfo.min.Z*.3048,-s.baseInfo.min.Y*.3048),max:new S.Vector3(s.baseInfo.max.X*.3048,s.baseInfo.max.Z*.3048,-s.baseInfo.max.Y*.3048)}}),o.events.trigger(ut.EngineFree,e)})}function kc(o,e){o.engineStatus.models.filter(t=>e==null||t.url==e).forEach(t=>{t.loadStatus==null&&(t.loadStatus={mep:!1,instance:!1,normal:!1}),t.status==="loading"&&t.type==="light"&&(t.loadStatus.modelMep!=!0&&(t.loadStatus.modelMep=!0,ql(o,t.info.modelMep,t.url)),t.loadStatus.normal!=!0&&Ic(o,t))})}function Ic(o,e){if(o.camera.position,e.size,e.info==null||e.info.lods==null)return;e.info.lods.forEach(i=>{if(i.status!=!0)if(i.glbs==null)console.log("加载GLB............."),i.glbs={},Wl(e.url+i.path,s=>{Pr(s.get("/nodes.json"),r=>{let a=JSON.parse(r);o.models.find(c=>c.url==e.url).nodesMap==null&&(o.models.find(c=>c.url==e.url).nodesMap=new Map);let l=o.models.find(c=>c.url==e.url).nodesMap,h=0;for(let c in a){a[c].forEach(p=>{p.glb=c,l.has(p.id)==!1?l.set(p.id,{infos:[p]}):l.get(p.id).infos.push(p)});let d=new Kl;const m=new Xl;m.setDecoderPath("/draco/"),m.preload(),d.setDRACOLoader(m),d.load(s.get(c+".glb"),p=>{i.glbs[c]=p.scene.children,i.glbs[c].forEach(f=>{f.geometry.computeVertexNormals()}),h++,h==Object.keys(a).length&&o.engineStatus.isFree&&(o.events.trigger(ut.EngineFree,e.url),o.viewCube.CameraGoHome())})}Pr(s.get("/instances.json"),c=>{let d=JSON.parse(c);o.models.find(m=>m.url==e.url).instanceNodes=d})})});else{let s=n(e,i,i.octreeBox),r=[],a=o.models.find(h=>h.url==e.url);s.forEach(h=>{a.nodesMap.has(h)&&a.nodesMap.get(h).infos.forEach(c=>{let d=i.glbs[c.glb][c.mesh];if(d!=null&&d.geometry!=null&&d.material!=null){let m=new S.Matrix4;m.elements=c.matrix;let p=new S.Mesh(d.geometry.clone().applyMatrix4(m),d.material),f=new S.Box3().setFromObject(p);c.box=f,c.mesh=p,p.name=h,p.glb=c.glb,p.url=e.url,d.geometry.attributes.position!=null&&r.push(p)}})}),Lc(e.url,o,r);let l=a.instanceNodes;if(l!=null)for(let h in l)(l[h].isLoaded==null||l[h].isLoaded==!1)&&(l[h].isLoaded=!0,l[h].forEach(c=>{if(i.glbs[h]!=null){let d=i.glbs[h][c.mesh];Ec(e.url,c.mesh,o,d,c.children)}}))}});function n(i,s,r){let a=[];if(r.status!=!0){if(!o.engineStatus.isFree)return a;let l=new S.Vector3(r.min.X,r.min.Z,-r.min.Y),h=new S.Vector3(r.max.X,r.max.Z,-r.max.Y);h.distanceTo(l);let c=o.camera.position,d=new S.Vector3(l.x+h.x/2,l.y+h.y/2,l.z+h.z/2);c.distanceTo(d),r.elements.forEach(m=>{a.push(m)}),r.children.forEach(m=>{a.push(...n(i,s,m))}),r.children.findIndex(m=>m.status!=!0)==-1&&(r.status=!0),r.children.length==0&&(r.status=!0)}return a}}function Lc(o,e,t){let n=[];t.forEach(i=>{n.findIndex(r=>r.glb==i.glb)==-1?n.push({glb:i.glb,meshes:[i],currentIndex:i.geometry.index.count,indexes:new Map}):(n.find(r=>r.glb==i.glb).meshes.push(i),n.find(r=>r.glb==i.glb).currentIndex+=i.geometry.index.count);let s=n.find(r=>r.glb==i.glb);s.indexes.set(Number(i.name),[s.currentIndex-i.geometry.index.count,s.currentIndex])}),n.forEach(i=>{let s=e.scene.children.find(r=>r instanceof S.Mesh&&r.url==o&&r.glb==i.glb);if(s!=null)s.castShadow=!0,s.receiveShadow=!0;else{let r=new S.BufferGeometry,a=Bc(i.meshes[0].material);r=kr(i.meshes.map(c=>c.geometry),!1);let l=new S.Mesh(r,a);l.castShadow=!0,l.receiveShadow=!0,e.scene.add(l),l.index=e.scene.children.length-1,l.url=o,l.glb=i.glb,l.indexes=i.indexes,l.materialClone=a,l.geometrys=i.meshes.map(c=>c.geometry);let h=e.models.find(c=>c.url==o);if(h!=null){let c=0;i.indexes.forEach(d=>{h.nodesMap.get(Number(i.meshes[c].name)).indexes==null&&(h.nodesMap.get(Number(i.meshes[c].name)).indexes=[]),h.nodesMap.get(Number(i.meshes[c].name)).indexes.push([l.index,c++,d[0],d[1]])})}}})}function Ec(o,e,t,n,i){if(n==null)return;let s=new S.InstancedMesh(n.geometry,n.material,i.length);t.scene.add(s);const r=new Float32Array(i.length*3);for(let l=0;l<i.length;l++)r[l*3]=1,r[l*3+1]=1,r[l*3+2]=1;s.instanceColor=new S.InstancedBufferAttribute(r,3);let a=[];for(let l=0;l<i.length;l++){let h=i[l],c=new S.Matrix4;c.elements=h.matrix,s.setMatrixAt(l,c),s.matrixs||(s.matrixs=[]),s.matrixs.push(c.clone()),a.push(c.clone()),t.models.find(d=>d.url==o).nodesMap.has(h.id)?(t.models.find(d=>d.url==o).nodesMap.get(h.id).indexes==null&&(t.models.find(d=>d.url==o).nodesMap.get(h.id).indexes=[]),t.models.find(d=>d.url==o).nodesMap.get(h.id).indexes.push([t.scene.children.length-1,l,0,0])):t.models.find(d=>d.url==o).nodesMap.set(h.id,{instance:!0,info:h,indexes:[[t.scene.children.length-1,l,0,0]]})}s.index=t.scene.children.length-1,s.materialClone=n.material,s.url=o,s.glb=n.glb,s.ids=i.map(l=>l.id),s.matrixsClone=a}function Bc(o){return o.map!=null&&(o.map.colorSpace=S.SRGBColorSpace,o.map.needsUpdate=!0),o.shadowSide=S.FrontSide,o.side=o.side,o}class Oc{engine;constructor(e){this.engine=e}async loadModels(e,t){console.log("待加载模型",e);for(const i of e)n(i)==="light"&&Dc(this.engine,i);function n(i){const s=i.split(".").pop();return s==="glb"||s==="gltf"?"gltf":"light"}}}class zc{engine;isFree;highlightModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.models=[]}init(){this.engine.events.on(ut.EngineFree,e=>{this.updateFree(!0),kc(this.engine,e)}),this.engine.events.on(ut.EngineBusy,()=>{this.updateFree(!1)})}updateFree(e){this.isFree=e}closeAllFunction=()=>{}}class Nc{listeners=new Map;debugMode=!1;setDebugMode(e){this.debugMode=e}on(e,t){const n=String(e);this.listeners.has(n)||this.listeners.set(n,[]),this.listeners.get(n).push(t),this.debugMode&&console.debug(`[EventModule] 注册事件监听器: ${n}, 当前监听器数量: ${this.listeners.get(n).length}`)}off(e,t){const n=String(e);if(!this.listeners.has(n)){this.debugMode&&console.warn(`[EventModule] 尝试移除不存在的事件监听器: ${n}`);return}const i=this.listeners.get(n),s=i.indexOf(t);s!==-1?(i.splice(s,1),this.debugMode&&console.debug(`[EventModule] 移除事件监听器: ${n}, 剩余监听器数量: ${i.length}`)):this.debugMode&&console.warn(`[EventModule] 尝试移除的回调函数未找到: ${n}`)}trigger(e,t){const n=String(e);if(!this.listeners.has(n)){this.debugMode&&(console.warn(`[EventModule] 触发事件但未找到监听器: ${n}`),console.debug("[EventModule] 当前已注册的事件类型:",Array.from(this.listeners.keys())));return}const i=this.listeners.get(n);this.debugMode&&console.debug(`[EventModule] 触发事件: ${n}, 监听器数量: ${i.length}`,t),i.forEach((s,r)=>{try{s(t)}catch(a){console.error(`[EventModule] 事件监听器执行错误 [${n}] #${r}:`,a)}})}}class Rc{engine;constructor(e){this.engine=e}init(){const e=new S.DirectionalLight(16777215,1);e.position.set(100,200,100),e.castShadow=!0,e.shadow.mapSize.width=2048,e.shadow.mapSize.height=2048,e.shadow.camera.near=.1,e.shadow.camera.far=5e3,e.shadow.bias=-5e-5,e.shadow.normalBias=.02;const t=50;e.shadow.camera.left=-t,e.shadow.camera.right=t,e.shadow.camera.top=t,e.shadow.camera.bottom=-t,e.shadow.radius=2;const n=new S.DirectionalLight(16777215,2);this.engine.scene.add(e),this.engine.scene.add(n),this.engine.scene.dirLight=n;const i=new S.AmbientLight(16777215,1);this.engine.scene.add(i)}}var _e=(o=>(o.ModelLoadStart="model-load-start",o.ModelLoadProgress="model-load-progress",o.ModelLoaded="model-loaded",o.ModelError="model-error",o.SelectionChanged="selection-changed",o.HoverChanged="hover-changed",o.Click="click",o.MouseMove="mouse-move",o.CameraChanged="camera-changed",o.CameraIdle="camera-idle",o.EngineFree="engine-free",o.EngineBusy="engine-busy",o.MeasureChanged="measure-changed",o.MeasureClick="measure-click",o.SectionMove="section-move",o))(_e||{});class Fc{engine;behavior;isCtrlDown=!1;highlightedInstances=[];highlightColor=new S.Color(43775);constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved,this.behavior.init(this)}active(){this.behavior.active()}disActive(){this.behavior.disActive()}handelKeyCtrlUp(){this.isCtrlDown=!1}handelKeyCtrlDown(){this.isCtrlDown=!0}hoverOldId=null;handleMouseMove(e){if(!this.engine.engineStatus.isFree){this.engine.hoverHighLight.clearHighlight();return}let t=this.getCatchMeshs(e);t!=null?t.length>0&&this.engine.hoverHighLight.hightMesh(t):this.engine.hoverHighLight.clearHighlight()}getCatchMeshs(e){if(e.catch==null)return this.hoverOldId=null,null;if(e.catch.object.isInstance){let t=e.catch.object,n=e.catch.object.id,i=this.engine.models.find(a=>a.url==t.url).nodesMap.get(n),s=new Map;i?.indexes.forEach(a=>{this.engine.scene.children[a[0]]instanceof S.InstancedMesh&&(s.has(a[0])?s.get(a[0])?.push(a[1]):s.set(a[0],[a[1]]))});let r=[];return s.forEach((a,l)=>{let h=this.engine.scene.children[l];a.forEach(c=>{let d=h.geometry.clone();d.applyMatrix4(h.matrixs[c]),r.push(new S.Mesh(d,h.material))})}),this.hoverOldId==n?[]:(this.hoverOldId=n,this.engine.hoverHighLight.clearHighlight(),r)}else{const t=e.catch;t.object;let n=t.object,i=n.name,a=this.engine.models.find(l=>l.url===n.url).nodesMap.get(i).infos.map(l=>l.mesh);return this.hoverOldId==i?[]:(this.hoverOldId=i,this.engine.hoverHighLight.clearHighlight(),a)}}handleMouseClick(e){if(e.catch!=null){const t=e.catch;let n=t.object;this.isCtrlDown||this.engine.modelToolModule.unhighlightAllModels(),console.log([{url:n.url,ids:[n.name]}]),this.engine.controlModule.orbitControls.origin.set(t.point.x,t.point.y,t.point.z),this.engine.modelToolModule.highlightModel([{url:n.url,ids:[n.name]}]),this.engine.events.trigger(_e.Click,[{url:n.url,ids:[n.name]}])}else this.engine.modelToolModule.unhighlightAllModels()}handleMouseDoubleClick(e){if(e.catch){const n=e.catch;n.object;let i=n.object,r=this.engine.models.find(a=>a.url===i.url).nodesMap.get(i.name);if(n.object.isInstance){let a=n.matrix,l=[];r.indexes.forEach(c=>{let d=c[0],m=this.engine.scene.children[d].geometry.boundingSphere;const p=new S.Box3,f=m.center.clone().applyMatrix4(a),u=m.radius,g=new S.Vector3;g.setFromMatrixScale(a);const y=Math.max(g.x,g.y,g.z),w=u*y;p.min.set(f.x-w,f.y-w,f.z-w),p.max.set(f.x+w,f.y+w,f.z+w),l.push(p)});let h=t(l);this.engine.viewCube.zoomToModel(h)}else{let a=r.infos.map(h=>h.box),l=t(a);this.engine.viewCube.zoomToModel(l)}}function t(n){let i=new S.Vector3(1e8,1e9,1e10),s=new S.Vector3(-1e8,-1e9,-1e10);return n.forEach(r=>{r.min.x<i.x&&(i.x=r.min.x),r.min.y<i.y&&(i.y=r.min.y),r.min.z<i.z&&(i.z=r.min.z),r.max.x>s.x&&(s.x=r.max.x),r.max.y>s.y&&(s.y=r.max.y),r.max.z>s.z&&(s.z=r.max.z)}),new S.Box3(i,s)}}handleMouseClickInstance(e){return e.intersectObjects(this.engine.scene.children.filter(n=>n instanceof S.InstancedMesh),!0)}}class Uc{engine;highlightMaterial;hideMaterial;translucentMaterial;constructor(e){this.engine=e,this.highlightMaterial=new S.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:S.DoubleSide}),this.hideMaterial=new S.MeshBasicMaterial({color:0,transparent:!0,opacity:0,side:S.DoubleSide}),this.translucentMaterial=new S.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:S.DoubleSide}),this.highlightMaterial.clippingPlanes=this.engine.sectionPlane,this.hideMaterial.clippingPlanes=this.engine.sectionPlane,this.translucentMaterial.clippingPlanes=this.engine.sectionPlane}split_merge_model(e){if(e.isSplit||e instanceof S.InstancedMesh)return;let t=e.materialClone.clone(),n=kr(e.geometrys,!0);n.groups.forEach(i=>{i.materialIndex=0}),e.geometry=n,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){}highlightModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{this.engine.scene.children[a[0]]instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(console.log(this.engine.scene.children[a[0]].materialClone.color),this.split_merge_model(this.engine.scene.children[a[0]]),this.engine.scene.children[a[0]].geometry.groups[a[1]].materialIndex=1)})}),Vc(n,this.engine);let i=this.engine.engineStatus.highlightModels.find(s=>s.url==t.url);i!=null?i.ids.push(...t.ids):this.engine.engineStatus.highlightModels.push(t)})}unhighlightModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(i=>{let s=this.engine.models.find(r=>r.url==t.url).nodesMap.get(i);s!=null&&s.indexes!=null&&s.indexes.forEach(r=>{this.engine.scene.children[r[0]]instanceof S.InstancedMesh?n.has(r[0])?n.get(r[0])?.push(r[1]):n.set(r[0],[r[1]]):this.engine.scene.children[r[0]].geometry.groups[r[1]].materialIndex=0})}),Fr(n,this.engine,"highlightModel")})}unhighlightAllModels(e=!0){this.engine.engineStatus.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus.highlightModels=[])}hideModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);this.engine.modelEdge.hideModelEdge(t.url,s),r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(this.split_merge_model(this.engine.scene.children[a[0]]),l.geometry.groups[a[1]].materialIndex=-1,l.geometry.groups[a[1]].visible=!1)})}),n.size>0&&Gc(n,this.engine);let i=this.engine.engineStatus.hideModels.find(s=>s.url==t.url);i!=null?i.ids.push(...t.ids):this.engine.engineStatus.hideModels.push({url:t.url,ids:t.ids}),this.engine.engineStatus.highlightModels=[]})}showModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);this.engine.modelEdge.showModelEdge(t.url,s),r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(l.geometry.groups[a[1]].materialIndex=0,l.geometry.groups[a[1]].visible=!0)})}),n.size>0&&Ur(n,this.engine);let i=this.engine.engineStatus.hideModels.find(s=>s.url==t.url);i&&(t.ids.forEach(s=>{const r=i.ids.indexOf(s);r!==-1&&i.ids.splice(r,1)}),i.ids.length===0&&(this.engine.engineStatus.hideModels=this.engine.engineStatus.hideModels.filter(s=>s!==i)))})}isolateModel(e){let t=[];this.engine.models.forEach(n=>{let i={url:n.url,ids:[]},s=e.find(r=>r.url==n.url);for(let r of n.nodesMap)s==null?i.ids.push(r[0]):s.ids.includes(r[0])||i.ids.push(r[0]);t.push(i)}),this.unhighlightAllModels(),this.hideModel(t)}translucentOtherModel(e){let t=[];this.engine.models.forEach(n=>{let i={url:n.url,ids:[]},s=e.find(r=>r.url==n.url);for(let r of n.nodesMap)s==null?i.ids.push(r[0]):s.ids.includes(r[0])||i.ids.push(r[0]);t.push(i)}),this.translucentModel(t)}setModelColor(e,t){e.material.color.set(t)}setAllModelsColor(e){this.engine.scene.children.forEach(t=>{t.isMesh})}restoreAllModelsColor(){this.engine.scene.children.forEach(e=>{e.isMesh})}translucentModel(e){this.unhighlightAllModels(),e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(this.split_merge_model(this.engine.scene.children[a[0]]),l.geometry.groups[a[1]].materialIndex=2)})}),jc(n,this.engine);let i=this.engine.engineStatus.translucentModels.find(s=>s.url==t.url);i!=null?i.ids.push(...t.ids):this.engine.engineStatus.translucentModels.push({url:t.url,ids:t.ids})}),this.engine.engineStatus.highlightModels=[]}unTranslucentModel(){this.engine.engineStatus.translucentModels.forEach(t=>{let n=new Map;t.ids.forEach(i=>{let s=this.engine.models.find(r=>r.url==t.url).nodesMap.get(i);s!=null&&s.indexes!=null&&s.indexes.forEach(r=>{const a=this.engine.scene.children[r[0]];a instanceof S.InstancedMesh?n.has(r[0])?n.get(r[0])?.push(r[1]):n.set(r[0],[r[1]]):(this.split_merge_model(this.engine.scene.children[r[0]]),a.geometry.groups[r[1]].materialIndex=0)})}),n.size>0&&Ur(n,this.engine),Fr(n,this.engine,"translucentModel")}),this.engine.engineStatus.translucentModels=[]}showAllModels(){this.engine.engineStatus.hideModels&&this.engine.engineStatus.hideModels.length>0&&this.showModel(this.engine.engineStatus.hideModels),this.engine.engineStatus.hideModels=[],this.unhighlightAllModels()}batchSelectSameLevelTypeModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevelType(n.levelName,n.typeName,i=>{this.engine.modelToolModule.highlightModel(i)})}batchSelectSameLevelModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevel(n.levelName,i=>{this.engine.modelToolModule.highlightModel(i)})}batchSelectSameTypeModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithType(n.typeName,i=>{this.engine.modelToolModule.highlightModel(i)})}}function Vc(o,e){o.forEach((t,n)=>{const i=e.scene.children[n];if(!(i instanceof S.InstancedMesh))return;const s=i.geometry,r=new S.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:S.DoubleSide}),a=new S.InstancedMesh(s,r,t.length);a.name="highlightModel",a.key=n;const l=new Map,h=new S.Matrix4,c=new S.Matrix4;c.makeScale(0,0,0),t.forEach((d,m)=>{i.getMatrixAt(d,h),l.set(d,h.clone()),i.setMatrixAt(d,c),a.setMatrixAt(m,h)}),i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function Fr(o,e,t){o.forEach((n,i)=>{const s=e.scene.children[i];if(!(s instanceof S.InstancedMesh))return;n.forEach(a=>{const l=s.matrixsClone[a];l&&s.setMatrixAt(a,l)}),s.instanceMatrix.needsUpdate=!0,e.scene.children.filter(a=>a.key==i&&a.name==t).forEach(a=>{e.scene.remove(a)})})}function jc(o,e){o.forEach((t,n)=>{const i=e.scene.children[n];if(!(i instanceof S.InstancedMesh))return;const s=i.geometry,r=new S.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:S.DoubleSide}),a=new S.InstancedMesh(s,r,t.length);a.name="translucentModel",a.key=n;const l=new Map,h=new S.Matrix4,c=new S.Matrix4;c.makeScale(0,0,0),t.forEach((d,m)=>{i.getMatrixAt(d,h),l.set(d,h.clone()),i.setMatrixAt(d,c),a.setMatrixAt(m,h)}),i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function Gc(o,e){e.scene.children.filter(t=>t.name=="highlightModel").forEach(t=>{e.scene.remove(t)}),o.forEach((t,n)=>{const i=e.scene.children[n];if(!(i instanceof S.InstancedMesh))return;const s=new Map,r=new S.Matrix4,a=new S.Matrix4;a.makeScale(0,0,0),t.forEach((l,h)=>{i.getMatrixAt(l,r),s.set(l,r.clone()),i.setMatrixAt(l,a)}),i.instanceMatrix.needsUpdate=!0})}function Ur(o,e){o.forEach((t,n)=>{const i=e.scene.children[n];i instanceof S.InstancedMesh&&(t.forEach(s=>{const r=i.matrixs[s];r&&i.setMatrixAt(s,r)}),i.instanceMatrix.needsUpdate=!0)})}class Wc{engine;currentMode="";isManualMode=!1;gtaoPass=null;ssaoPass=null;saturationPass=null;outputPass=null;fxaaPass=null;constructor(e){this.engine=e}init(){this.cachePassReferences(),this.autoSwitch("advanced")}switchModel(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}autoSwitch(e){this.isManualMode||(this.currentMode=e,this.applyMode(e))}enableAutoMode(){this.isManualMode=!1}get isManual(){return this.isManualMode}setMode(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}getCurrentMode(){return this.currentMode}cachePassReferences(){this.engine.composerModule?.composer&&(this.engine.composerModule.gtaoPass&&(this.gtaoPass=this.engine.composerModule.gtaoPass),this.engine.composerModule.ssaoPass&&(this.ssaoPass=this.engine.composerModule.ssaoPass),this.engine.composerModule.saturationPass&&(this.saturationPass=this.engine.composerModule.saturationPass),this.engine.composerModule.outputPass&&(this.outputPass=this.engine.composerModule.outputPass),this.engine.composerModule.fxaaPass&&(this.fxaaPass=this.engine.composerModule.fxaaPass))}applyMode(e){switch(e){case"simple":this.setShadows(!1),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!1);break;case"balance":this.setShadows(!0),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!1);break;case"advanced":this.setShadows(!0),this.setSSAO(!1),this.setGTAO(!0),this.setSaturation(!0),this.setOutputPass(!0),this.setFXAA(!0);break;default:console.warn(`[EngineModelModule] Unknown mode: ${e}`)}this.engine.updateVersionDisplay?.()}setShadows(e){this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e);const t=this.engine.scene?.children.find(n=>n instanceof S.DirectionalLight);t&&(t.castShadow=e),this.engine.scene?.traverse(n=>{n.material&&(n.castShadow!==void 0&&(n.castShadow=e),n.receiveShadow!==void 0&&(n.receiveShadow=e))})}setGTAO(e){this.engine.composerModule?.composer&&this.gtaoPass&&(this.gtaoPass.enabled=e)}setSSAO(e){this.engine.composerModule?.composer&&this.ssaoPass&&(this.ssaoPass.enabled=e)}setSaturation(e){this.saturationPass&&(this.saturationPass.enabled=e)}setOutputPass(e){this.outputPass&&(this.outputPass.enabled=e)}setFXAA(e){this.fxaaPass&&(this.fxaaPass.enabled=e)}setPerformanceMode(){this.setMode("simple")}setBalancedMode(){this.setMode("balance")}setQualityMode(){this.setMode("advanced")}setSuperQualityMode(){this.setMode("superAdvanced")}setShadowQuality(e){const t=this.engine.scene?.children.find(s=>s instanceof S.DirectionalLight),i={low:1024,medium:2048,high:2048}[e];t?.shadow&&i&&(t.shadow.mapSize.width=i,t.shadow.mapSize.height=i,t.shadow.map?.dispose(),t.shadow.map=null)}setSaturationValue(e){this.saturationPass&&(this.saturationPass.uniforms.saturation.value=e)}setContrastValue(e){this.saturationPass&&(this.saturationPass.uniforms.contrast.value=e)}setGTAOIntensity(e){this.gtaoPass&&(this.gtaoPass.blendIntensity=e)}}class qn{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;constructor(e){this.engine=e,this.init()}init(){this.overlayMaterial=new S.MeshBasicMaterial({color:16777215,transparent:!0,opacity:0,blending:S.AdditiveBlending,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,n=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const i=(Array.isArray(e)?e:e?[e]:[]).filter(s=>s?.geometry);if(i.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=n;for(const s of i){const r=new S.Mesh(s.geometry,this.overlayMaterial);s.updateWorldMatrix(!0,!1),r.matrix.copy(s.matrixWorld),r.matrixAutoUpdate=!1,this.engine.scene.add(r),this.overlayMeshes.push(r)}this.animState="fadeIn",this.animStartTime=performance.now()}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now())}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const n=Math.min(e/qn.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(n)*t,n>=1&&(this.animState="idle")}else if(this.animState==="fadeOut"){const n=Math.min(e/qn.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(n))*t,n>=1&&(this.removeOverlayMeshes(),this.animState="idle")}}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e);this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.animState="idle"}}var Kn={exports:{}},Xc=Kn.exports,Vr;function Zc(){return Vr||(Vr=1,(function(o,e){(function(t,n){o.exports=n()})(Xc,function(){var t=function(){function n(p){return r.appendChild(p.dom),p}function i(p){for(var f=0;f<r.children.length;f++)r.children[f].style.display=f===p?"block":"none";s=p}var s=0,r=document.createElement("div");r.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",r.addEventListener("click",function(p){p.preventDefault(),i(++s%r.children.length)},!1);var a=(performance||Date).now(),l=a,h=0,c=n(new t.Panel("FPS","#0ff","#002")),d=n(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var m=n(new t.Panel("MB","#f08","#201"));return i(0),{REVISION:16,dom:r,addPanel:n,showPanel:i,begin:function(){a=(performance||Date).now()},end:function(){h++;var p=(performance||Date).now();if(d.update(p-a,200),p>l+1e3&&(c.update(1e3*h/(p-l),100),l=p,h=0,m)){var f=performance.memory;m.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return p},update:function(){a=this.end()},domElement:r,setMode:i}};return t.Panel=function(n,i,s){var r=1/0,a=0,l=Math.round,h=l(window.devicePixelRatio||1),c=80*h,d=48*h,m=3*h,p=2*h,f=3*h,u=15*h,g=74*h,y=30*h,w=document.createElement("canvas");w.width=c,w.height=d,w.style.cssText="width:80px;height:48px";var x=w.getContext("2d");return x.font="bold "+9*h+"px Helvetica,Arial,sans-serif",x.textBaseline="top",x.fillStyle=s,x.fillRect(0,0,c,d),x.fillStyle=i,x.fillText(n,m,p),x.fillRect(f,u,g,y),x.fillStyle=s,x.globalAlpha=.9,x.fillRect(f,u,g,y),{dom:w,update:function(v,b){r=Math.min(r,v),a=Math.max(a,v),x.fillStyle=s,x.globalAlpha=1,x.fillRect(0,0,c,u),x.fillStyle=i,x.fillText(l(v)+" "+n+" ("+l(r)+"-"+l(a)+")",m,p),x.drawImage(w,f+h,u,g-h,y,f,u,g-h,y),x.fillRect(f+g-h,u,h,y),x.fillStyle=s,x.globalAlpha=.9,x.fillRect(f+g-h,u,h,l((1-v/b)*y))}}},t})})(Kn)),Kn.exports}var qc=Zc();const Kc=Us(qc);var Zt=Object.freeze({Linear:Object.freeze({None:function(o){return o},In:function(o){return o},Out:function(o){return o},InOut:function(o){return o}}),Quadratic:Object.freeze({In:function(o){return o*o},Out:function(o){return o*(2-o)},InOut:function(o){return(o*=2)<1?.5*o*o:-.5*(--o*(o-2)-1)}}),Cubic:Object.freeze({In:function(o){return o*o*o},Out:function(o){return--o*o*o+1},InOut:function(o){return(o*=2)<1?.5*o*o*o:.5*((o-=2)*o*o+2)}}),Quartic:Object.freeze({In:function(o){return o*o*o*o},Out:function(o){return 1- --o*o*o*o},InOut:function(o){return(o*=2)<1?.5*o*o*o*o:-.5*((o-=2)*o*o*o-2)}}),Quintic:Object.freeze({In:function(o){return o*o*o*o*o},Out:function(o){return--o*o*o*o*o+1},InOut:function(o){return(o*=2)<1?.5*o*o*o*o*o:.5*((o-=2)*o*o*o*o+2)}}),Sinusoidal:Object.freeze({In:function(o){return 1-Math.sin((1-o)*Math.PI/2)},Out:function(o){return Math.sin(o*Math.PI/2)},InOut:function(o){return .5*(1-Math.sin(Math.PI*(.5-o)))}}),Exponential:Object.freeze({In:function(o){return o===0?0:Math.pow(1024,o-1)},Out:function(o){return o===1?1:1-Math.pow(2,-10*o)},InOut:function(o){return o===0?0:o===1?1:(o*=2)<1?.5*Math.pow(1024,o-1):.5*(-Math.pow(2,-10*(o-1))+2)}}),Circular:Object.freeze({In:function(o){return 1-Math.sqrt(1-o*o)},Out:function(o){return Math.sqrt(1- --o*o)},InOut:function(o){return(o*=2)<1?-.5*(Math.sqrt(1-o*o)-1):.5*(Math.sqrt(1-(o-=2)*o)+1)}}),Elastic:Object.freeze({In:function(o){return o===0?0:o===1?1:-Math.pow(2,10*(o-1))*Math.sin((o-1.1)*5*Math.PI)},Out:function(o){return o===0?0:o===1?1:Math.pow(2,-10*o)*Math.sin((o-.1)*5*Math.PI)+1},InOut:function(o){return o===0?0:o===1?1:(o*=2,o<1?-.5*Math.pow(2,10*(o-1))*Math.sin((o-1.1)*5*Math.PI):.5*Math.pow(2,-10*(o-1))*Math.sin((o-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(o){var e=1.70158;return o===1?1:o*o*((e+1)*o-e)},Out:function(o){var e=1.70158;return o===0?0:--o*o*((e+1)*o+e)+1},InOut:function(o){var e=2.5949095;return(o*=2)<1?.5*(o*o*((e+1)*o-e)):.5*((o-=2)*o*((e+1)*o+e)+2)}}),Bounce:Object.freeze({In:function(o){return 1-Zt.Bounce.Out(1-o)},Out:function(o){return o<1/2.75?7.5625*o*o:o<2/2.75?7.5625*(o-=1.5/2.75)*o+.75:o<2.5/2.75?7.5625*(o-=2.25/2.75)*o+.9375:7.5625*(o-=2.625/2.75)*o+.984375},InOut:function(o){return o<.5?Zt.Bounce.In(o*2)*.5:Zt.Bounce.Out(o*2-1)*.5+.5}}),generatePow:function(o){return o===void 0&&(o=4),o=o<Number.EPSILON?Number.EPSILON:o,o=o>1e4?1e4:o,{In:function(e){return Math.pow(e,o)},Out:function(e){return 1-Math.pow(1-e,o)},InOut:function(e){return e<.5?Math.pow(e*2,o)/2:(1-Math.pow(2-e*2,o))/2+.5}}}}),cn=function(){return performance.now()},Yc=(function(){function o(){this._tweens={},this._tweensAddedDuringUpdate={}}return o.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},o.prototype.removeAll=function(){this._tweens={}},o.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},o.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},o.prototype.update=function(e,t){e===void 0&&(e=cn()),t===void 0&&(t=!1);var n=Object.keys(this._tweens);if(n.length===0)return!1;for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<n.length;i++){var s=this._tweens[n[i]],r=!t;s&&s.update(e,r)===!1&&!t&&delete this._tweens[n[i]]}n=Object.keys(this._tweensAddedDuringUpdate)}return!0},o})(),Zi={Linear:function(o,e){var t=o.length-1,n=t*e,i=Math.floor(n),s=Zi.Utils.Linear;return e<0?s(o[0],o[1],n):e>1?s(o[t],o[t-1],t-n):s(o[i],o[i+1>t?t:i+1],n-i)},Utils:{Linear:function(o,e,t){return(e-o)*t+o}}},jr=(function(){function o(){}return o.nextId=function(){return o._nextId++},o._nextId=0,o})(),qi=new Yc,$c=(function(){function o(e,t){t===void 0&&(t=qi),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=Zt.Linear.None,this._interpolationFunction=Zi.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=jr.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return o.prototype.getId=function(){return this._id},o.prototype.isPlaying=function(){return this._isPlaying},o.prototype.isPaused=function(){return this._isPaused},o.prototype.getDuration=function(){return this._duration},o.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},o.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},o.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},o.prototype.start=function(e,t){if(e===void 0&&(e=cn()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var n in this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},o.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},o.prototype._setupProperties=function(e,t,n,i,s){for(var r in n){var a=e[r],l=Array.isArray(a),h=l?"array":typeof a,c=!l&&Array.isArray(n[r]);if(!(h==="undefined"||h==="function")){if(c){var d=n[r];if(d.length===0)continue;for(var m=[a],p=0,f=d.length;p<f;p+=1){var u=this._handleRelativeValue(a,d[p]);if(isNaN(u)){c=!1,console.warn("Found invalid interpolation list. Skipping.");break}m.push(u)}c&&(n[r]=m)}if((h==="object"||l)&&a&&!c){t[r]=l?[]:{};var g=a;for(var y in g)t[r][y]=g[y];i[r]=l?[]:{};var d=n[r];if(!this._isDynamic){var w={};for(var y in d)w[y]=d[y];n[r]=d=w}this._setupProperties(g,t[r],d,i[r],s)}else(typeof t[r]>"u"||s)&&(t[r]=a),l||(t[r]*=1),c?i[r]=n[r].slice().reverse():i[r]=t[r]||0}}},o.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},o.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},o.prototype.pause=function(e){return e===void 0&&(e=cn()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},o.prototype.resume=function(e){return e===void 0&&(e=cn()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},o.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},o.prototype.group=function(e){return e===void 0&&(e=qi),this._group=e,this},o.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},o.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},o.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},o.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},o.prototype.easing=function(e){return e===void 0&&(e=Zt.Linear.None),this._easingFunction=e,this},o.prototype.interpolation=function(e){return e===void 0&&(e=Zi.Linear),this._interpolationFunction=e,this},o.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},o.prototype.onStart=function(e){return this._onStartCallback=e,this},o.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},o.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},o.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},o.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},o.prototype.onStop=function(e){return this._onStopCallback=e,this},o.prototype.update=function(e,t){var n=this,i;if(e===void 0&&(e=cn()),t===void 0&&(t=!0),this._isPaused)return!0;var s,r=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>r)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=e-this._startTime,l=this._duration+((i=this._repeatDelayTime)!==null&&i!==void 0?i:this._delayTime),h=this._duration+this._repeat*l,c=function(){if(n._duration===0||a>h)return 1;var g=Math.trunc(a/l),y=a-g*l,w=Math.min(y/n._duration,1);return w===0&&a===n._duration?1:w},d=c(),m=this._easingFunction(d);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,m),this._onUpdateCallback&&this._onUpdateCallback(this._object,d),this._duration===0||a>=this._duration)if(this._repeat>0){var p=Math.min(Math.trunc((a-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=p);for(s in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[s]=="string"&&(this._valuesStartRepeat[s]=this._valuesStartRepeat[s]+parseFloat(this._valuesEnd[s])),this._yoyo&&this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=l*p,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var f=0,u=this._chainedTweens.length;f<u;f++)this._chainedTweens[f].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},o.prototype._updateProperties=function(e,t,n,i){for(var s in n)if(t[s]!==void 0){var r=t[s]||0,a=n[s],l=Array.isArray(e[s]),h=Array.isArray(a),c=!l&&h;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],r,a,i):(a=this._handleRelativeValue(r,a),typeof a=="number"&&(e[s]=r+(a-r)*i))}},o.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},o.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];typeof n=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(n):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},o})();jr.nextId;var et=qi;et.getAll.bind(et),et.removeAll.bind(et),et.add.bind(et),et.remove.bind(et),et.update.bind(et);var hn={Easing:Zt,Tween:$c};class Hc extends _.DataTextureLoader{constructor(e){super(e),this.type=_.HalfFloatType}parse(e){const r=function(k,P){switch(k){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(P||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(P||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(P||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(P||""))}},d=function(k,P,I){P=P||1024;let C=k.pos,E=-1,M=0,B="",V=String.fromCharCode.apply(null,new Uint16Array(k.subarray(C,C+128)));for(;0>(E=V.indexOf(`
967
+ `);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const i=new Worker(this.workerSourceURL);i._callbacks={},i._taskCosts={},i._taskLoad=0,i.postMessage({type:"init",decoderConfig:this.decoderConfig}),i.onmessage=function(s){const r=s.data;switch(r.type){case"decode":i._callbacks[r.id].resolve(r);break;case"error":i._callbacks[r.id].reject(r);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+r.type+'"')}},this.workerPool.push(i)}else this.workerPool.sort(function(i,s){return i._taskLoad>s._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function Zl(){let o,e;onmessage=function(r){const a=r.data;switch(a.type){case"init":o=a.decoderConfig,e=new Promise(function(c){o.onModuleLoaded=function(d){c({draco:d})},DracoDecoderModule(o)});break;case"decode":const l=a.buffer,h=a.taskConfig;e.then(c=>{const d=c.draco,m=new d.Decoder;try{const p=t(d,m,new Int8Array(l),h),f=p.attributes.map(u=>u.array.buffer);p.index&&f.push(p.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:p},f)}catch(p){console.error(p),self.postMessage({type:"error",id:a.id,error:p.message})}finally{d.destroy(m)}});break}};function t(r,a,l,h){const c=h.attributeIDs,d=h.attributeTypes;let m,p;const f=a.GetEncodedGeometryType(l);if(f===r.TRIANGULAR_MESH)m=new r.Mesh,p=a.DecodeArrayToMesh(l,l.byteLength,m);else if(f===r.POINT_CLOUD)m=new r.PointCloud,p=a.DecodeArrayToPointCloud(l,l.byteLength,m);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!p.ok()||m.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+p.error_msg());const u={index:null,attributes:[]};for(const g in c){const y=self[d[g]];let w,x;if(h.useUniqueIDs)x=c[g],w=a.GetAttributeByUniqueId(m,x);else{if(x=a.GetAttributeId(m,r[c[g]]),x===-1)continue;w=a.GetAttribute(m,x)}const v=i(r,a,m,g,y,w);g==="color"&&(v.vertexColorSpace=h.vertexColorSpace),u.attributes.push(v)}return f===r.TRIANGULAR_MESH&&(u.index=n(r,a,m)),r.destroy(m),u}function n(r,a,l){const c=l.num_faces()*3,d=c*4,m=r._malloc(d);a.GetTrianglesUInt32Array(l,d,m);const p=new Uint32Array(r.HEAPF32.buffer,m,c).slice();return r._free(m),{array:p,itemSize:1}}function i(r,a,l,h,c,d){const m=l.num_points(),p=d.num_components(),f=s(r,c),u=p*c.BYTES_PER_ELEMENT,g=Math.ceil(u/4)*4,y=g/c.BYTES_PER_ELEMENT,w=m*u,x=m*g,v=r._malloc(w);a.GetAttributeDataArrayForAllPoints(l,d,f,w,v);const b=new c(r.HEAPF32.buffer,v,w/c.BYTES_PER_ELEMENT);let D;if(u===g)D=b.slice();else{D=new c(x/c.BYTES_PER_ELEMENT);let T=0;for(let k=0,P=b.length;k<P;k++){for(let I=0;I<p;I++)D[T+I]=b[k*p+I];T+=y}}return r._free(v),{name:h,count:m,itemSize:p,array:D,stride:y}}function s(r,a){switch(a){case Float32Array:return r.DT_FLOAT32;case Int8Array:return r.DT_INT8;case Int16Array:return r.DT_INT16;case Int32Array:return r.DT_INT32;case Uint8Array:return r.DT_UINT8;case Uint16Array:return r.DT_UINT16;case Uint32Array:return r.DT_UINT32}}}var ut=(o=>(o.ModelLoadStart="model-load-start",o.ModelLoadProgress="model-load-progress",o.ModelLoaded="model-loaded",o.ModelError="model-error",o.SelectionChanged="selection-changed",o.HoverChanged="hover-changed",o.Click="click",o.MouseMove="mouse-move",o.CameraChanged="camera-changed",o.CameraIdle="camera-idle",o.ViewportResize="viewport-resize",o.EngineFree="engine-free",o.EngineBusy="engine-busy",o.MeasureChanged="measure-changed",o.SectionMove="section-move",o))(ut||{});function ql(o,e,t,n){let i=0,s=0,r=0,a=o.models.find(p=>p.url==t),l=e.circularMeps,h=e.rectMeps.filter(p=>p.type==="风管"),c=e.rectMeps.filter(p=>p.type==="桥架"),d=e.ellipseMeps,m=o.scene;if(new S.MeshBasicMaterial,new S.BufferGeometry,l&&l.length){let p=[],f=0;for(let u of l)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Circle",m,p,t)}if(h&&h.length){let p=[],f=0;for(let u of h)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Rect",m,p,t)}if(d&&d.length){let p=[],f=0;for(let u of d)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Ellipse",m,p,t)}if(c&&c.length){let p=[],f=0;for(let u of c)u.color=u.color.split(",").map(g=>parseInt(g)/255),u.color=new S.Color(u.color[0],u.color[1],u.color[2]),u.position={x:u.startPoint.X*.3048+i,y:u.startPoint.Z*.3048+s,z:-u.startPoint.Y*.3048+r},u.rotation={x:0,y:0,z:0},u.indexes=[[o.scene.children.length,f++,0,0]],a.nodesMap.set(Number(u.id),u),p.push(u);Xn("Bridge",m,p,t)}}function Xn(o,e,t,n,i){let s,r,a={width:1,height:1,length:1,diameter:1,color:new S.Color,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};switch(o){case"Rect":r=Zn("Rect",a);break;case"Bridge":r=Zn("Bridge",a);break;case"Circle":r=Zn("Circle",a);break;case"Ellipse":r=Zn("Ellipse",a);break}r&&(s=new S.InstancedMesh(r.geometry,r.material,t.length),s.url=n,e.add(s));let l=[],h=[];for(var c=0;c<t.length;c++){let p=t[c],f=new S.Vector3(p.startPoint.X,0,-p.startPoint.Y),u=new S.Vector3(p.endPoint.X,0,-p.endPoint.Y),g=new S.Vector3(p.startPoint.X,p.startPoint.Z,-p.startPoint.Y),y=new S.Vector3(p.endPoint.X,p.endPoint.Z,-p.endPoint.Y),w=0,x=0,v=0;if(Math.abs(u.clone().sub(f.clone()).z)<.01&&Math.abs(u.clone().sub(f.clone()).x)<.01){if(w=(p.startPoint.Z>p.endPoint.Z?1:-1)*Math.PI*.5,p.base_x!=null){var d=new S.Vector3(p.base_x.X,0,-p.base_x.Y);x=(d.clone().cross(new S.Vector3(0,0,1)).y<=0?1:-1)*d.angleTo(new S.Vector3(0,0,1))+Math.PI*.5}}else x=(u.clone().sub(f.clone()).cross(new S.Vector3(0,0,1)).y>0?-1:1)*u.clone().sub(f.clone()).angleTo(new S.Vector3(0,0,1)),w=(p.startPoint.Z>p.endPoint.Z?1:-1)*u.clone().sub(f.clone()).angleTo(y.clone().sub(g.clone()));let b=new S.Matrix4;const D=new S.Euler(w,x,v,"YXZ");let T=b.clone().makeRotationFromEuler(D),k,P;o==="Circle"?(k=p.diameter,P=p.diameter):(k=p.width,P=p.height);let I=b.clone().makeScale(k,P,p.length);b.multiplyMatrices(T,I),b.setPosition(p.position.x,p.position.y,p.position.z),s.setMatrixAt(c,b.clone()),s.setColorAt(c,p.color),s.geometry.computeBoundingBox();let z=s.geometry.boundingBox.min.clone().applyMatrix4(b.clone()),C=s.geometry.boundingBox.max.clone().applyMatrix4(b.clone()),E=new S.Vector3(Math.min(z.x,C.x),Math.min(z.y,C.y),Math.min(z.z,C.z)),M=new S.Vector3(Math.max(z.x,C.x),Math.max(z.y,C.y),Math.max(z.z,C.z)),B=E.clone().add(M.clone()).multiplyScalar(.5),V={name:p.name,min:E,max:M,center:B,dbid:c,materialName:r.material.name},U=null,H=null;o==="Circle"&&(U={x:p.startPoint.X*.3048,y:p.startPoint.Z*.3048,z:-p.startPoint.Y*.3048},H={x:p.endPoint.X*.3048,y:p.endPoint.Z*.3048,z:-p.endPoint.Y*.3048},V.minC=U,V.maxC=H),s.ids||(s.ids=[]),s.matrixs||(s.matrixs=[]),s.matrixs.push(b.clone()),h.push(b.clone()),s.ids.push(Number(p.id)),l.push(V)}s.castShadow=!0,s.ElementInfos=l,s.name="rootModel",s.TypeName="InstancedMesh-Pipe",s.PipeType=o,s.MeshId=null,s.realMaterial=s.material.clone(),s.originalMaterial=s.material.clone(),s.matrixsClone=h;let m=[];m={geometry:s.geometry,matrix:s.matrix,position:s.position,rotation:s.rotation},s.meshs=m,s.instanceMatrix&&s.instanceMatrix.array&&(s.cloneInstanceMatrix=Array.from(s.instanceMatrix.array))}function Zn(o,e,t){let n=new S.Shape;switch(e.width=e.width*.3048,e.height=e.height*.3048,e.diameter=e.diameter*.3048,o){case"Rect":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Ellipse":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Bridge":n.moveTo(-e.width/2,-e.height/2),n.lineTo(-e.width/2,e.height/2),n.lineTo(-e.width/2+.01,e.height/2),n.lineTo(-e.width/2+.01,-e.height/2+.01),n.lineTo(e.width/2-.01,-e.height/2+.01),n.lineTo(e.width/2-.01,e.height/2),n.lineTo(e.width/2,e.height/2),n.lineTo(e.width/2,-e.height/2),n.lineTo(-e.width/2,-e.height/2);break;case"Circle":n.moveTo(0,0),n.absarc(0,0,e.diameter*.5,0,Math.PI*2,!1);break}const i={depth:e.length*.3048,bevelEnabled:!1};return s(n,i,e.color,e.position,e.rotation);function s(r,a,l,h,c){let d=new S.ExtrudeGeometry(r,a),m=new S.MeshStandardMaterial({color:l,side:S.DoubleSide}),p=new S.Mesh(d,m);return p.position.set(h.x,h.y,h.z),p.rotation._order="YXZ",p.rotation.set(c.x,c.y,c.z),p}}function kr(o,e=!1){const t=o[0].index!==null,n=new Set(Object.keys(o[0].attributes)),i=new Set(Object.keys(o[0].morphAttributes)),s={},r={},a=o[0].morphTargetsRelative,l=new _.BufferGeometry;let h=0;for(let c=0;c<o.length;++c){const d=o[c];let m=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in d.attributes){if(!n.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;s[p]===void 0&&(s[p]=[]),s[p].push(d.attributes[p]),m++}if(m!==n.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in d.morphAttributes){if(!i.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". .morphAttributes must be consistent throughout all geometries."),null;r[p]===void 0&&(r[p]=[]),r[p].push(d.morphAttributes[p])}if(e){let p;if(t)p=d.index.count;else if(d.attributes.position!==void 0)p=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+c+". The geometry must have either an index or a position attribute"),null;l.addGroup(h,p,c),h+=p}}if(t){let c=0;const d=[];for(let m=0;m<o.length;++m){const p=o[m].index;for(let f=0;f<p.count;++f)d.push(p.getX(f)+c);c+=o[m].attributes.position.count}l.setIndex(d)}for(const c in s){const d=Ir(s[c]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+c+" attribute."),null;l.setAttribute(c,d)}for(const c in r){const d=r[c][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[c]=[];for(let m=0;m<d;++m){const p=[];for(let u=0;u<r[c].length;++u)p.push(r[c][u][m]);const f=Ir(p);if(!f)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+c+" morphAttribute."),null;l.morphAttributes[c].push(f)}}return l}function Ir(o){let e,t,n,i=-1,s=0;for(let h=0;h<o.length;++h){const c=o[h];if(e===void 0&&(e=c.array.constructor),e!==c.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=c.itemSize),t!==c.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(n===void 0&&(n=c.normalized),n!==c.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(i===-1&&(i=c.gpuType),i!==c.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=c.count*t}const r=new e(s),a=new _.BufferAttribute(r,t,n);let l=0;for(let h=0;h<o.length;++h){const c=o[h];if(c.isInterleavedBufferAttribute){const d=l/t;for(let m=0,p=c.count;m<p;m++)for(let f=0;f<t;f++){const u=c.getComponent(m,f);a.setComponent(m+d,f,u)}}else r.set(c.array,l);l+=c.count*t}return i!==void 0&&(a.gpuType=i),a}function Lr(o,e){if(e===_.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),o;if(e===_.TriangleFanDrawMode||e===_.TriangleStripDrawMode){let t=o.getIndex();if(t===null){const r=[],a=o.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)r.push(l);o.setIndex(r),t=o.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),o}const n=t.count-2,i=[];if(e===_.TriangleFanDrawMode)for(let r=1;r<=n;r++)i.push(t.getX(0)),i.push(t.getX(r)),i.push(t.getX(r+1));else for(let r=0;r<n;r++)r%2===0?(i.push(t.getX(r)),i.push(t.getX(r+1)),i.push(t.getX(r+2))):(i.push(t.getX(r+2)),i.push(t.getX(r+1)),i.push(t.getX(r)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=o.clone();return s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),o}class Kl extends _.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Ql(t)}),this.register(function(t){return new ec(t)}),this.register(function(t){return new cc(t)}),this.register(function(t){return new hc(t)}),this.register(function(t){return new uc(t)}),this.register(function(t){return new nc(t)}),this.register(function(t){return new ic(t)}),this.register(function(t){return new sc(t)}),this.register(function(t){return new rc(t)}),this.register(function(t){return new Jl(t)}),this.register(function(t){return new oc(t)}),this.register(function(t){return new tc(t)}),this.register(function(t){return new lc(t)}),this.register(function(t){return new ac(t)}),this.register(function(t){return new $l(t)}),this.register(function(t){return new dc(t)}),this.register(function(t){return new fc(t)})}load(e,t,n,i){const s=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const h=_.LoaderUtils.extractUrlBase(e);r=_.LoaderUtils.resolveURL(h,this.path)}else r=_.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const a=function(h){i?i(h):console.error(h),s.manager.itemError(e),s.manager.itemEnd(e)},l=new _.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(h){try{s.parse(h,r,function(c){t(c),s.manager.itemEnd(e)},a)}catch(c){a(c)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let s;const r={},a={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===Er){try{r[le.KHR_BINARY_GLTF]=new pc(e)}catch(d){i&&i(d);return}s=JSON.parse(r[le.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new Tc(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c<this.pluginCallbacks.length;c++){const d=this.pluginCallbacks[c](h);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[d.name]=d,r[d.name]=!0}if(s.extensionsUsed)for(let c=0;c<s.extensionsUsed.length;++c){const d=s.extensionsUsed[c],m=s.extensionsRequired||[];switch(d){case le.KHR_MATERIALS_UNLIT:r[d]=new Hl;break;case le.KHR_DRACO_MESH_COMPRESSION:r[d]=new mc(s,this.dracoLoader);break;case le.KHR_TEXTURE_TRANSFORM:r[d]=new gc;break;case le.KHR_MESH_QUANTIZATION:r[d]=new yc;break;default:m.indexOf(d)>=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}h.setExtensions(r),h.setPlugins(a),h.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,s){n.parse(e,t,i,s)})}}function Yl(){let o={};return{get:function(e){return o[e]},add:function(e,t){o[e]=t},remove:function(e){delete o[e]},removeAll:function(){o={}}}}const le={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class $l{constructor(e){this.parser=e,this.name=le.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const s=t[n];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let h;const c=new _.Color(16777215);l.color!==void 0&&c.setRGB(l.color[0],l.color[1],l.color[2],_.LinearSRGBColorSpace);const d=l.range!==void 0?l.range:0;switch(l.type){case"directional":h=new _.DirectionalLight(c),h.target.position.set(0,0,-1),h.add(h.target);break;case"point":h=new _.PointLight(c),h.distance=d;break;case"spot":h=new _.SpotLight(c),h.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,h.angle=l.spot.outerConeAngle,h.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,h.target.position.set(0,0,-1),h.add(h.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return h.position.set(0,0,0),Qe(h,l),l.intensity!==void 0&&(h.intensity=l.intensity),h.name=t.createUniqueName(l.name||"light_"+e),i=Promise.resolve(h),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,s=n.json.nodes[e],a=(s.extensions&&s.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return n._getNodeRef(t.cache,a,l)})}}class Hl{constructor(){this.name=le.KHR_MATERIALS_UNLIT}getMaterialType(){return _.MeshBasicMaterial}extendParams(e,t,n){const i=[];e.color=new _.Color(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const r=s.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],_.LinearSRGBColorSpace),e.opacity=r[3]}s.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",s.baseColorTexture,_.SRGBColorSpace))}return Promise.all(i)}}class Jl{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class Ql{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];if(r.clearcoatFactor!==void 0&&(t.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&s.push(n.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&s.push(n.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(s.push(n.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){const a=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new _.Vector2(a,a)}return Promise.all(s)}}class ec{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}}class tc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return r.iridescenceFactor!==void 0&&(t.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&s.push(n.assignTexture(t,"iridescenceMap",r.iridescenceTexture)),r.iridescenceIor!==void 0&&(t.iridescenceIOR=r.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),r.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),r.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),r.iridescenceThicknessTexture!==void 0&&s.push(n.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(s)}}class nc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new _.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const r=i.extensions[this.name];if(r.sheenColorFactor!==void 0){const a=r.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],_.LinearSRGBColorSpace)}return r.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&s.push(n.assignTexture(t,"sheenColorMap",r.sheenColorTexture,_.SRGBColorSpace)),r.sheenRoughnessTexture!==void 0&&s.push(n.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(s)}}class ic{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return r.transmissionFactor!==void 0&&(t.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&s.push(n.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(s)}}class sc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];t.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&s.push(n.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const a=r.attenuationColor||[1,1,1];return t.attenuationColor=new _.Color().setRGB(a[0],a[1],a[2],_.LinearSRGBColorSpace),Promise.all(s)}}class rc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class oc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];t.specularIntensity=r.specularFactor!==void 0?r.specularFactor:1,r.specularTexture!==void 0&&s.push(n.assignTexture(t,"specularIntensityMap",r.specularTexture));const a=r.specularColorFactor||[1,1,1];return t.specularColor=new _.Color().setRGB(a[0],a[1],a[2],_.LinearSRGBColorSpace),r.specularColorTexture!==void 0&&s.push(n.assignTexture(t,"specularColorMap",r.specularColorTexture,_.SRGBColorSpace)),Promise.all(s)}}class ac{constructor(e){this.parser=e,this.name=le.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return t.bumpScale=r.bumpFactor!==void 0?r.bumpFactor:1,r.bumpTexture!==void 0&&s.push(n.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(s)}}class lc{constructor(e){this.parser=e,this.name=le.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:_.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],r=i.extensions[this.name];return r.anisotropyStrength!==void 0&&(t.anisotropy=r.anisotropyStrength),r.anisotropyRotation!==void 0&&(t.anisotropyRotation=r.anisotropyRotation),r.anisotropyTexture!==void 0&&s.push(n.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(s)}}class cc{constructor(e){this.parser=e,this.name=le.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const s=i.extensions[this.name],r=t.options.ktx2Loader;if(!r){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,r)}}class hc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const r=s.extensions[t],a=i.images[r.source];let l=n.textureLoader;if(a.uri){const h=n.options.manager.getHandler(a.uri);h!==null&&(l=h)}return n.loadTextureImage(e,r.source,l)}}class uc{constructor(e){this.parser=e,this.name=le.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const r=s.extensions[t],a=i.images[r.source];let l=n.textureLoader;if(a.uri){const h=n.options.manager.getHandler(a.uri);h!==null&&(l=h)}return n.loadTextureImage(e,r.source,l)}}class dc{constructor(e){this.name=le.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(a){const l=i.byteOffset||0,h=i.byteLength||0,c=i.count,d=i.byteStride,m=new Uint8Array(a,l,h);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(c,d,m,i.mode,i.filter).then(function(p){return p.buffer}):r.ready.then(function(){const p=new ArrayBuffer(c*d);return r.decodeGltfBuffer(new Uint8Array(p),c,d,m,i.mode,i.filter),p})})}else return null}}class fc{constructor(e){this.name=le.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const h of i.primitives)if(h.mode!==Ve.TRIANGLES&&h.mode!==Ve.TRIANGLE_STRIP&&h.mode!==Ve.TRIANGLE_FAN&&h.mode!==void 0)return null;const r=n.extensions[this.name].attributes,a=[],l={};for(const h in r)a.push(this.parser.getDependency("accessor",r[h]).then(c=>(l[h]=c,l[h])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(h=>{const c=h.pop(),d=c.isGroup?c.children:[c],m=h[0].count,p=[];for(const f of d){const u=new _.Matrix4,g=new _.Vector3,y=new _.Quaternion,w=new _.Vector3(1,1,1),x=new _.InstancedMesh(f.geometry,f.material,m);for(let v=0;v<m;v++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,v),l.ROTATION&&y.fromBufferAttribute(l.ROTATION,v),l.SCALE&&w.fromBufferAttribute(l.SCALE,v),x.setMatrixAt(v,u.compose(g,y,w));for(const v in l)if(v==="_COLOR_0"){const b=l[v];x.instanceColor=new _.InstancedBufferAttribute(b.array,b.itemSize,b.normalized)}else v!=="TRANSLATION"&&v!=="ROTATION"&&v!=="SCALE"&&f.geometry.setAttribute(v,l[v]);_.Object3D.prototype.copy.call(x,f),this.parser.assignFinalMaterial(x),p.push(x)}return c.isGroup?(c.clear(),c.add(...p),c):p[0]}))}}const Er="glTF",ln=12,Br={JSON:1313821514,BIN:5130562};class pc{constructor(e){this.name=le.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,ln),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Er)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-ln,s=new DataView(e,ln);let r=0;for(;r<i;){const a=s.getUint32(r,!0);r+=4;const l=s.getUint32(r,!0);if(r+=4,l===Br.JSON){const h=new Uint8Array(e,ln+r,a);this.content=n.decode(h)}else if(l===Br.BIN){const h=ln+r;this.body=e.slice(h,h+a)}r+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class mc{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=le.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,a={},l={},h={};for(const c in r){const d=ji[c]||c.toLowerCase();a[d]=r[c]}for(const c in e.attributes){const d=ji[c]||c.toLowerCase();if(r[c]!==void 0){const m=n.accessors[e.attributes[c]],p=Xt[m.componentType];h[d]=p.name,l[d]=m.normalized===!0}}return t.getDependency("bufferView",s).then(function(c){return new Promise(function(d,m){i.decodeDracoFile(c,function(p){for(const f in p.attributes){const u=p.attributes[f],g=l[f];g!==void 0&&(u.normalized=g)}d(p)},a,h,_.LinearSRGBColorSpace,m)})})}}class gc{constructor(){this.name=le.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class yc{constructor(){this.name=le.KHR_MESH_QUANTIZATION}}class Or extends _.Interpolant{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let r=0;r!==i;r++)t[r]=n[s+r];return t}interpolate_(e,t,n,i){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,l=a*2,h=a*3,c=i-t,d=(n-t)/c,m=d*d,p=m*d,f=e*h,u=f-h,g=-2*p+3*m,y=p-m,w=1-g,x=y-m+d;for(let v=0;v!==a;v++){const b=r[u+v+a],D=r[u+v+l]*c,T=r[f+v+a],k=r[f+v]*c;s[v]=w*b+x*D+g*T+y*k}return s}}const wc=new _.Quaternion;class xc extends Or{interpolate_(e,t,n,i){const s=super.interpolate_(e,t,n,i);return wc.fromArray(s).normalize().toArray(s),s}}const Ve={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Xt={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},zr={9728:_.NearestFilter,9729:_.LinearFilter,9984:_.NearestMipmapNearestFilter,9985:_.LinearMipmapNearestFilter,9986:_.NearestMipmapLinearFilter,9987:_.LinearMipmapLinearFilter},Nr={33071:_.ClampToEdgeWrapping,33648:_.MirroredRepeatWrapping,10497:_.RepeatWrapping},Vi={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},ji={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},dt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},vc={CUBICSPLINE:void 0,LINEAR:_.InterpolateLinear,STEP:_.InterpolateDiscrete},Gi={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function bc(o){return o.DefaultMaterial===void 0&&(o.DefaultMaterial=new _.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:_.FrontSide})),o.DefaultMaterial}function Pt(o,e,t){for(const n in t.extensions)o[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Qe(o,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(o.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function _c(o,e,t){let n=!1,i=!1,s=!1;for(let h=0,c=e.length;h<c;h++){const d=e[h];if(d.POSITION!==void 0&&(n=!0),d.NORMAL!==void 0&&(i=!0),d.COLOR_0!==void 0&&(s=!0),n&&i&&s)break}if(!n&&!i&&!s)return Promise.resolve(o);const r=[],a=[],l=[];for(let h=0,c=e.length;h<c;h++){const d=e[h];if(n){const m=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):o.attributes.position;r.push(m)}if(i){const m=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):o.attributes.normal;a.push(m)}if(s){const m=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):o.attributes.color;l.push(m)}}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(l)]).then(function(h){const c=h[0],d=h[1],m=h[2];return n&&(o.morphAttributes.position=c),i&&(o.morphAttributes.normal=d),s&&(o.morphAttributes.color=m),o.morphTargetsRelative=!0,o})}function Mc(o,e){if(o.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)o.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(o.morphTargetInfluences.length===t.length){o.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)o.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Sc(o){let e;const t=o.extensions&&o.extensions[le.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Wi(t.attributes):e=o.indices+":"+Wi(o.attributes)+":"+o.mode,o.targets!==void 0)for(let n=0,i=o.targets.length;n<i;n++)e+=":"+Wi(o.targets[n]);return e}function Wi(o){let e="";const t=Object.keys(o).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+o[t[n]]+";";return e}function Xi(o){switch(o){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Ac(o){return o.search(/\.jpe?g($|\?)/i)>0||o.search(/^data\:image\/jpeg/)===0?"image/jpeg":o.search(/\.webp($|\?)/i)>0||o.search(/^data\:image\/webp/)===0?"image/webp":o.search(/\.ktx2($|\?)/i)>0||o.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Cc=new _.Matrix4;class Tc{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Yl,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,r=-1;if(typeof navigator<"u"){const a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;const l=a.match(/Version\/(\d+)/);i=n&&l?parseInt(l[1],10):-1,s=a.indexOf("Firefox")>-1,r=s?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||s&&r<98?this.textureLoader=new _.TextureLoader(this.options.manager):this.textureLoader=new _.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new _.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(r){const a={scene:r[0][i.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:i.asset,parser:n,userData:{}};return Pt(s,a,i),Qe(a,i),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,s=t.length;i<s;i++){const r=t[i].joints;for(let a=0,l=r.length;a<l;a++)e[r[a]].isBone=!0}for(let i=0,s=e.length;i<s;i++){const r=e[i];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),s=(r,a)=>{const l=this.associations.get(r);l!=null&&this.associations.set(a,l);for(const[h,c]of r.children.entries())s(c,a.children[h])};return s(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const s=e(t[i]);s&&n.push(s)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":i=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(s,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[le.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(s,r){n.load(_.LoaderUtils.resolveURL(t.uri,i.path),s,void 0,function(){r(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,s=t.byteOffset||0;return n.slice(s,s+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const r=Vi[i.type],a=Xt[i.componentType],l=i.normalized===!0,h=new a(i.count*r);return Promise.resolve(new _.BufferAttribute(h,r,l))}const s=[];return i.bufferView!==void 0?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),i.sparse!==void 0&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then(function(r){const a=r[0],l=Vi[i.type],h=Xt[i.componentType],c=h.BYTES_PER_ELEMENT,d=c*l,m=i.byteOffset||0,p=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,f=i.normalized===!0;let u,g;if(p&&p!==d){const y=Math.floor(m/p),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+y+":"+i.count;let x=t.cache.get(w);x||(u=new h(a,y*p,i.count*p/c),x=new _.InterleavedBuffer(u,p/c),t.cache.add(w,x)),g=new _.InterleavedBufferAttribute(x,l,m%p/c,f)}else a===null?u=new h(i.count*l):u=new h(a,m,i.count*l),g=new _.BufferAttribute(u,l,f);if(i.sparse!==void 0){const y=Vi.SCALAR,w=Xt[i.sparse.indices.componentType],x=i.sparse.indices.byteOffset||0,v=i.sparse.values.byteOffset||0,b=new w(r[1],x,i.sparse.count*y),D=new h(r[2],v,i.sparse.count*l);a!==null&&(g=new _.BufferAttribute(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let T=0,k=b.length;T<k;T++){const P=b[T];if(g.setX(P,D[T*l]),l>=2&&g.setY(P,D[T*l+1]),l>=3&&g.setZ(P,D[T*l+2]),l>=4&&g.setW(P,D[T*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=f}return g})}loadTexture(e){const t=this.json,n=this.options,s=t.textures[e].source,r=t.images[s];let a=this.textureLoader;if(r.uri){const l=n.manager.getHandler(r.uri);l!==null&&(a=l)}return this.loadTextureImage(e,s,a)}loadTextureImage(e,t,n){const i=this,s=this.json,r=s.textures[e],a=s.images[t],l=(a.uri||a.bufferView)+":"+r.sampler;if(this.textureCache[l])return this.textureCache[l];const h=this.loadImageSource(t,n).then(function(c){c.flipY=!1,c.name=r.name||a.name||"",c.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(c.name=a.uri);const m=(s.samplers||{})[r.sampler]||{};return c.magFilter=zr[m.magFilter]||_.LinearFilter,c.minFilter=zr[m.minFilter]||_.LinearMipmapLinearFilter,c.wrapS=Nr[m.wrapS]||_.RepeatWrapping,c.wrapT=Nr[m.wrapT]||_.RepeatWrapping,c.generateMipmaps=!c.isCompressedTexture&&c.minFilter!==_.NearestFilter&&c.minFilter!==_.LinearFilter,i.associations.set(c,{textures:e}),c}).catch(function(){return null});return this.textureCache[l]=h,h}loadImageSource(e,t){const n=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const r=i.images[e],a=self.URL||self.webkitURL;let l=r.uri||"",h=!1;if(r.bufferView!==void 0)l=n.getDependency("bufferView",r.bufferView).then(function(d){h=!0;const m=new Blob([d],{type:r.mimeType});return l=a.createObjectURL(m),l});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(l).then(function(d){return new Promise(function(m,p){let f=m;t.isImageBitmapLoader===!0&&(f=function(u){const g=new _.Texture(u);g.needsUpdate=!0,m(g)}),t.load(_.LoaderUtils.resolveURL(d,s.path),f,void 0,p)})}).then(function(d){return h===!0&&a.revokeObjectURL(l),Qe(d,r),d.userData.mimeType=r.mimeType||Ac(r.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=c,c}assignTexture(e,t,n,i){const s=this;return this.getDependency("texture",n.index).then(function(r){if(!r)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(r=r.clone(),r.channel=n.texCoord),s.extensions[le.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[le.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=s.associations.get(r);r=s.extensions[le.KHR_TEXTURE_TRANSFORM].extendTexture(r,a),s.associations.set(r,l)}}return i!==void 0&&(r.colorSpace=i),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new _.PointsMaterial,_.Material.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(a,l)),n=l}else if(e.isLine){const a="LineBasicMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new _.LineBasicMaterial,_.Material.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(a,l)),n=l}if(i||s||r){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),s&&(a+="vertex-colors:"),r&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=n.clone(),s&&(l.vertexColors=!0),r&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(n))),n=l}e.material=n}getMaterialType(){return _.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,i=this.extensions,s=n.materials[e];let r;const a={},l=s.extensions||{},h=[];if(l[le.KHR_MATERIALS_UNLIT]){const d=i[le.KHR_MATERIALS_UNLIT];r=d.getMaterialType(),h.push(d.extendParams(a,s,t))}else{const d=s.pbrMetallicRoughness||{};if(a.color=new _.Color(1,1,1),a.opacity=1,Array.isArray(d.baseColorFactor)){const m=d.baseColorFactor;a.color.setRGB(m[0],m[1],m[2],_.LinearSRGBColorSpace),a.opacity=m[3]}d.baseColorTexture!==void 0&&h.push(t.assignTexture(a,"map",d.baseColorTexture,_.SRGBColorSpace)),a.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,a.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(h.push(t.assignTexture(a,"metalnessMap",d.metallicRoughnessTexture)),h.push(t.assignTexture(a,"roughnessMap",d.metallicRoughnessTexture))),r=this._invokeOne(function(m){return m.getMaterialType&&m.getMaterialType(e)}),h.push(Promise.all(this._invokeAll(function(m){return m.extendMaterialParams&&m.extendMaterialParams(e,a)})))}s.doubleSided===!0&&(a.side=_.DoubleSide);const c=s.alphaMode||Gi.OPAQUE;if(c===Gi.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,c===Gi.MASK&&(a.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&r!==_.MeshBasicMaterial&&(h.push(t.assignTexture(a,"normalMap",s.normalTexture)),a.normalScale=new _.Vector2(1,1),s.normalTexture.scale!==void 0)){const d=s.normalTexture.scale;a.normalScale.set(d,d)}if(s.occlusionTexture!==void 0&&r!==_.MeshBasicMaterial&&(h.push(t.assignTexture(a,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&r!==_.MeshBasicMaterial){const d=s.emissiveFactor;a.emissive=new _.Color().setRGB(d[0],d[1],d[2],_.LinearSRGBColorSpace)}return s.emissiveTexture!==void 0&&r!==_.MeshBasicMaterial&&h.push(t.assignTexture(a,"emissiveMap",s.emissiveTexture,_.SRGBColorSpace)),Promise.all(h).then(function(){const d=new r(a);return s.name&&(d.name=s.name),Qe(d,s),t.associations.set(d,{materials:e}),s.extensions&&Pt(i,d,s),d})}createUniqueName(e){const t=_.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function s(a){return n[le.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return Rr(l,a,t)})}const r=[];for(let a=0,l=e.length;a<l;a++){const h=e[a],c=Sc(h),d=i[c];if(d)r.push(d.promise);else{let m;h.extensions&&h.extensions[le.KHR_DRACO_MESH_COMPRESSION]?m=s(h):m=Rr(new _.BufferGeometry,h,t),i[c]={primitive:h,promise:m},r.push(m)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,i=this.extensions,s=n.meshes[e],r=s.primitives,a=[];for(let l=0,h=r.length;l<h;l++){const c=r[l].material===void 0?bc(this.cache):this.getDependency("material",r[l].material);a.push(c)}return a.push(t.loadGeometries(r)),Promise.all(a).then(function(l){const h=l.slice(0,l.length-1),c=l[l.length-1],d=[];for(let p=0,f=c.length;p<f;p++){const u=c[p],g=r[p];let y;const w=h[p];if(g.mode===Ve.TRIANGLES||g.mode===Ve.TRIANGLE_STRIP||g.mode===Ve.TRIANGLE_FAN||g.mode===void 0)y=s.isSkinnedMesh===!0?new _.SkinnedMesh(u,w):new _.Mesh(u,w),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),g.mode===Ve.TRIANGLE_STRIP?y.geometry=Lr(y.geometry,_.TriangleStripDrawMode):g.mode===Ve.TRIANGLE_FAN&&(y.geometry=Lr(y.geometry,_.TriangleFanDrawMode));else if(g.mode===Ve.LINES)y=new _.LineSegments(u,w);else if(g.mode===Ve.LINE_STRIP)y=new _.Line(u,w);else if(g.mode===Ve.LINE_LOOP)y=new _.LineLoop(u,w);else if(g.mode===Ve.POINTS)y=new _.Points(u,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(y.geometry.morphAttributes).length>0&&Mc(y,s),y.name=t.createUniqueName(s.name||"mesh_"+e),Qe(y,s),g.extensions&&Pt(i,y,g),t.assignFinalMaterial(y),d.push(y)}for(let p=0,f=d.length;p<f;p++)t.associations.set(d[p],{meshes:e,primitives:p});if(d.length===1)return s.extensions&&Pt(i,d[0],s),d[0];const m=new _.Group;s.extensions&&Pt(i,m,s),t.associations.set(m,{meshes:e});for(let p=0,f=d.length;p<f;p++)m.add(d[p]);return m})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new _.PerspectiveCamera(_.MathUtils.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new _.OrthographicCamera(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Qe(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,s=t.joints.length;i<s;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const s=i.pop(),r=i,a=[],l=[];for(let h=0,c=r.length;h<c;h++){const d=r[h];if(d){a.push(d);const m=new _.Matrix4;s!==null&&m.fromArray(s.array,h*16),l.push(m)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[h])}return new _.Skeleton(a,l)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,r=[],a=[],l=[],h=[],c=[];for(let d=0,m=i.channels.length;d<m;d++){const p=i.channels[d],f=i.samplers[p.sampler],u=p.target,g=u.node,y=i.parameters!==void 0?i.parameters[f.input]:f.input,w=i.parameters!==void 0?i.parameters[f.output]:f.output;u.node!==void 0&&(r.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",y)),l.push(this.getDependency("accessor",w)),h.push(f),c.push(u))}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(l),Promise.all(h),Promise.all(c)]).then(function(d){const m=d[0],p=d[1],f=d[2],u=d[3],g=d[4],y=[];for(let x=0,v=m.length;x<v;x++){const b=m[x],D=p[x],T=f[x],k=u[x],P=g[x];if(b===void 0)continue;b.updateMatrix&&b.updateMatrix();const I=n._createAnimationTracks(b,D,T,k,P);if(I)for(let z=0;z<I.length;z++)y.push(I[z])}const w=new _.AnimationClip(s,void 0,y);return Qe(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(s){const r=n._getNodeRef(n.meshCache,i.mesh,s);return i.weights!==void 0&&r.traverse(function(a){if(a.isMesh)for(let l=0,h=i.weights.length;l<h;l++)a.morphTargetInfluences[l]=i.weights[l]}),r})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],s=n._loadNodeShallow(e),r=[],a=i.children||[];for(let h=0,c=a.length;h<c;h++)r.push(n.getDependency("node",a[h]));const l=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([s,Promise.all(r),l]).then(function(h){const c=h[0],d=h[1],m=h[2];m!==null&&c.traverse(function(p){p.isSkinnedMesh&&p.bind(m,Cc)});for(let p=0,f=d.length;p<f;p++)c.add(d[p]);return c})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],r=s.name?i.createUniqueName(s.name):"",a=[],l=i._invokeOne(function(h){return h.createNodeMesh&&h.createNodeMesh(e)});return l&&a.push(l),s.camera!==void 0&&a.push(i.getDependency("camera",s.camera).then(function(h){return i._getNodeRef(i.cameraCache,s.camera,h)})),i._invokeAll(function(h){return h.createNodeAttachment&&h.createNodeAttachment(e)}).forEach(function(h){a.push(h)}),this.nodeCache[e]=Promise.all(a).then(function(h){let c;if(s.isBone===!0?c=new _.Bone:h.length>1?c=new _.Group:h.length===1?c=h[0]:c=new _.Object3D,c!==h[0])for(let d=0,m=h.length;d<m;d++)c.add(h[d]);if(s.name&&(c.userData.name=s.name,c.name=r),Qe(c,s),s.extensions&&Pt(n,c,s),s.matrix!==void 0){const d=new _.Matrix4;d.fromArray(s.matrix),c.applyMatrix4(d)}else s.translation!==void 0&&c.position.fromArray(s.translation),s.rotation!==void 0&&c.quaternion.fromArray(s.rotation),s.scale!==void 0&&c.scale.fromArray(s.scale);if(!i.associations.has(c))i.associations.set(c,{});else if(s.mesh!==void 0&&i.meshCache.refs[s.mesh]>1){const d=i.associations.get(c);i.associations.set(c,{...d})}return i.associations.get(c).nodes=e,c}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,s=new _.Group;n.name&&(s.name=i.createUniqueName(n.name)),Qe(s,n),n.extensions&&Pt(t,s,n);const r=n.nodes||[],a=[];for(let l=0,h=r.length;l<h;l++)a.push(i.getDependency("node",r[l]));return Promise.all(a).then(function(l){for(let c=0,d=l.length;c<d;c++)s.add(l[c]);const h=c=>{const d=new Map;for(const[m,p]of i.associations)(m instanceof _.Material||m instanceof _.Texture)&&d.set(m,p);return c.traverse(m=>{const p=i.associations.get(m);p!=null&&d.set(m,p)}),d};return i.associations=h(s),s})}_createAnimationTracks(e,t,n,i,s){const r=[],a=e.name?e.name:e.uuid,l=[];dt[s.path]===dt.weights?e.traverse(function(m){m.morphTargetInfluences&&l.push(m.name?m.name:m.uuid)}):l.push(a);let h;switch(dt[s.path]){case dt.weights:h=_.NumberKeyframeTrack;break;case dt.rotation:h=_.QuaternionKeyframeTrack;break;case dt.translation:case dt.scale:h=_.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:h=_.NumberKeyframeTrack;break;case 2:case 3:default:h=_.VectorKeyframeTrack;break}break}const c=i.interpolation!==void 0?vc[i.interpolation]:_.InterpolateLinear,d=this._getArrayFromAccessor(n);for(let m=0,p=l.length;m<p;m++){const f=new h(l[m]+"."+dt[s.path],t.array,d,c);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(f),r.push(f)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Xi(t.constructor),i=new Float32Array(t.length);for(let s=0,r=t.length;s<r;s++)i[s]=t[s]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof _.QuaternionKeyframeTrack?xc:Or;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Pc(o,e,t){const n=e.attributes,i=new _.Box3;if(n.POSITION!==void 0){const a=t.json.accessors[n.POSITION],l=a.min,h=a.max;if(l!==void 0&&h!==void 0){if(i.set(new _.Vector3(l[0],l[1],l[2]),new _.Vector3(h[0],h[1],h[2])),a.normalized){const c=Xi(Xt[a.componentType]);i.min.multiplyScalar(c),i.max.multiplyScalar(c)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const a=new _.Vector3,l=new _.Vector3;for(let h=0,c=s.length;h<c;h++){const d=s[h];if(d.POSITION!==void 0){const m=t.json.accessors[d.POSITION],p=m.min,f=m.max;if(p!==void 0&&f!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(f[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(f[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(f[2]))),m.normalized){const u=Xi(Xt[m.componentType]);l.multiplyScalar(u)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}o.boundingBox=i;const r=new _.Sphere;i.getCenter(r.center),r.radius=i.min.distanceTo(i.max)/2,o.boundingSphere=r}function Rr(o,e,t){const n=e.attributes,i=[];function s(r,a){return t.getDependency("accessor",r).then(function(l){o.setAttribute(a,l)})}for(const r in n){const a=ji[r]||r.toLowerCase();a in o.attributes||i.push(s(n[r],a))}if(e.indices!==void 0&&!o.index){const r=t.getDependency("accessor",e.indices).then(function(a){o.setIndex(a)});i.push(r)}return _.ColorManagement.workingColorSpace!==_.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${_.ColorManagement.workingColorSpace}" not supported.`),Qe(o,e),Pc(o,e,t),Promise.all(i).then(function(){return e.targets!==void 0?_c(o,e.targets,t):o})}function Dc(o,e,t){let n=new S.Group;n.name=e,o.scene.add(n),Dr(e+"/info",i=>{let s=JSON.parse(i);o.engineStatus.models.push({type:"light",info:s,name:s.baseInfo.name,status:"loading",url:e,elements:new Map}),o.models==null&&(o.models=[]),o.models.push({url:e,nodesMap:new Map,boundingBox:{min:new S.Vector3(s.baseInfo.min.X*.3048,s.baseInfo.min.Z*.3048,-s.baseInfo.min.Y*.3048),max:new S.Vector3(s.baseInfo.max.X*.3048,s.baseInfo.max.Z*.3048,-s.baseInfo.max.Y*.3048)}}),o.events.trigger(ut.EngineFree,e)})}function kc(o,e){o.engineStatus.models.filter(t=>e==null||t.url==e).forEach(t=>{t.loadStatus==null&&(t.loadStatus={mep:!1,instance:!1,normal:!1}),t.status==="loading"&&t.type==="light"&&(t.loadStatus.modelMep!=!0&&(t.loadStatus.modelMep=!0,ql(o,t.info.modelMep,t.url)),t.loadStatus.normal!=!0&&Ic(o,t))})}function Ic(o,e){if(o.camera.position,e.size,e.info==null||e.info.lods==null)return;e.info.lods.forEach(i=>{if(i.status!=!0)if(i.glbs==null)console.log("加载GLB............."),i.glbs={},Wl(e.url+i.path,s=>{Pr(s.get("/nodes.json"),r=>{let a=JSON.parse(r);o.models.find(c=>c.url==e.url).nodesMap==null&&(o.models.find(c=>c.url==e.url).nodesMap=new Map);let l=o.models.find(c=>c.url==e.url).nodesMap,h=0;for(let c in a){a[c].forEach(p=>{p.glb=c,l.has(p.id)==!1?l.set(p.id,{infos:[p]}):l.get(p.id).infos.push(p)});let d=new Kl;const m=new Xl;m.setDecoderPath("/draco/"),m.preload(),d.setDRACOLoader(m),d.load(s.get(c+".glb"),p=>{i.glbs[c]=p.scene.children,i.glbs[c].forEach(f=>{f.geometry.computeVertexNormals()}),h++,h==Object.keys(a).length&&o.engineStatus.isFree&&(o.events.trigger(ut.EngineFree,e.url),o.viewCube.CameraGoHome())})}Pr(s.get("/instances.json"),c=>{let d=JSON.parse(c);o.models.find(m=>m.url==e.url).instanceNodes=d})})});else{let s=n(e,i,i.octreeBox),r=[],a=o.models.find(h=>h.url==e.url);s.forEach(h=>{a.nodesMap.has(h)&&a.nodesMap.get(h).infos.forEach(c=>{let d=i.glbs[c.glb][c.mesh];if(d!=null&&d.geometry!=null&&d.material!=null){let m=new S.Matrix4;m.elements=c.matrix;let p=new S.Mesh(d.geometry.clone().applyMatrix4(m),d.material),f=new S.Box3().setFromObject(p);c.box=f,c.mesh=p,p.name=h,p.glb=c.glb,p.url=e.url,d.geometry.attributes.position!=null&&r.push(p)}})}),Lc(e.url,o,r);let l=a.instanceNodes;if(l!=null)for(let h in l)(l[h].isLoaded==null||l[h].isLoaded==!1)&&(l[h].isLoaded=!0,l[h].forEach(c=>{if(i.glbs[h]!=null){let d=i.glbs[h][c.mesh];Ec(e.url,c.mesh,o,d,c.children)}}))}});function n(i,s,r){let a=[];if(r.status!=!0){if(!o.engineStatus.isFree)return a;let l=new S.Vector3(r.min.X,r.min.Z,-r.min.Y),h=new S.Vector3(r.max.X,r.max.Z,-r.max.Y);h.distanceTo(l);let c=o.camera.position,d=new S.Vector3(l.x+h.x/2,l.y+h.y/2,l.z+h.z/2);c.distanceTo(d),r.elements.forEach(m=>{a.push(m)}),r.children.forEach(m=>{a.push(...n(i,s,m))}),r.children.findIndex(m=>m.status!=!0)==-1&&(r.status=!0),r.children.length==0&&(r.status=!0)}return a}}function Lc(o,e,t){let n=[];t.forEach(i=>{n.findIndex(r=>r.glb==i.glb)==-1?n.push({glb:i.glb,meshes:[i],currentIndex:i.geometry.index.count,indexes:new Map}):(n.find(r=>r.glb==i.glb).meshes.push(i),n.find(r=>r.glb==i.glb).currentIndex+=i.geometry.index.count);let s=n.find(r=>r.glb==i.glb);s.indexes.has(Number(i.name))?s.indexes.get(Number(i.name)).push([s.currentIndex-i.geometry.index.count,s.currentIndex]):s.indexes.set(Number(i.name),[[s.currentIndex-i.geometry.index.count,s.currentIndex]])}),n.forEach(i=>{let s=e.scene.children.find(r=>r instanceof S.Mesh&&r.url==o&&r.glb==i.glb);if(s!=null)s.castShadow=!0,s.receiveShadow=!0;else{let r=new S.BufferGeometry,a=Bc(i.meshes[0].material);r=kr(i.meshes.map(c=>c.geometry),!1);let l=new S.Mesh(r,a);l.castShadow=!0,l.receiveShadow=!0,e.scene.add(l),l.index=e.scene.children.length-1,l.url=o,l.glb=i.glb,l.indexes=i.indexes,l.materialClone=a,l.geometrys=i.meshes.map(c=>c.geometry);let h=e.models.find(c=>c.url==o);if(h!=null){let c=0;i.indexes.forEach(d=>{d.forEach(m=>{h.nodesMap.get(Number(i.meshes[c].name)).indexes==null&&(h.nodesMap.get(Number(i.meshes[c].name)).indexes=[]),h.nodesMap.get(Number(i.meshes[c].name)).indexes.push([l.index,c++,m[0],m[1]])})})}}})}function Ec(o,e,t,n,i){if(n==null)return;let s=new S.InstancedMesh(n.geometry,n.material,i.length);t.scene.add(s);const r=new Float32Array(i.length*3);for(let l=0;l<i.length;l++)r[l*3]=1,r[l*3+1]=1,r[l*3+2]=1;s.instanceColor=new S.InstancedBufferAttribute(r,3);let a=[];for(let l=0;l<i.length;l++){let h=i[l],c=new S.Matrix4;c.elements=h.matrix,s.setMatrixAt(l,c),s.matrixs||(s.matrixs=[]),s.matrixs.push(c.clone()),a.push(c.clone()),t.models.find(d=>d.url==o).nodesMap.has(h.id)?(t.models.find(d=>d.url==o).nodesMap.get(h.id).indexes==null&&(t.models.find(d=>d.url==o).nodesMap.get(h.id).indexes=[]),t.models.find(d=>d.url==o).nodesMap.get(h.id).indexes.push([t.scene.children.length-1,l,0,0])):t.models.find(d=>d.url==o).nodesMap.set(h.id,{instance:!0,info:h,indexes:[[t.scene.children.length-1,l,0,0]]})}s.index=t.scene.children.length-1,s.materialClone=n.material,s.url=o,s.glb=n.glb,s.ids=i.map(l=>l.id),s.matrixsClone=a}function Bc(o){return o.map!=null&&(o.map.colorSpace=S.SRGBColorSpace,o.map.needsUpdate=!0),o.shadowSide=S.FrontSide,o.side=o.side,o}class Oc{engine;constructor(e){this.engine=e}async loadModels(e,t){console.log("待加载模型",e);for(const i of e)n(i)==="light"&&Dc(this.engine,i);function n(i){const s=i.split(".").pop();return s==="glb"||s==="gltf"?"gltf":"light"}}}class zc{engine;isFree;highlightModels;hideModels;translucentModels;models;constructor(e){this.engine=e,this.isFree=!0,this.highlightModels=[],this.hideModels=[],this.translucentModels=[],this.models=[]}init(){this.engine.events.on(ut.EngineFree,e=>{this.updateFree(!0),kc(this.engine,e)}),this.engine.events.on(ut.EngineBusy,()=>{this.updateFree(!1)})}updateFree(e){this.isFree=e}closeAllFunction=()=>{}}class Nc{listeners=new Map;debugMode=!1;setDebugMode(e){this.debugMode=e}on(e,t){const n=String(e);this.listeners.has(n)||this.listeners.set(n,[]),this.listeners.get(n).push(t),this.debugMode&&console.debug(`[EventModule] 注册事件监听器: ${n}, 当前监听器数量: ${this.listeners.get(n).length}`)}off(e,t){const n=String(e);if(!this.listeners.has(n)){this.debugMode&&console.warn(`[EventModule] 尝试移除不存在的事件监听器: ${n}`);return}const i=this.listeners.get(n),s=i.indexOf(t);s!==-1?(i.splice(s,1),this.debugMode&&console.debug(`[EventModule] 移除事件监听器: ${n}, 剩余监听器数量: ${i.length}`)):this.debugMode&&console.warn(`[EventModule] 尝试移除的回调函数未找到: ${n}`)}trigger(e,t){const n=String(e);if(!this.listeners.has(n)){this.debugMode&&(console.warn(`[EventModule] 触发事件但未找到监听器: ${n}`),console.debug("[EventModule] 当前已注册的事件类型:",Array.from(this.listeners.keys())));return}const i=this.listeners.get(n);this.debugMode&&console.debug(`[EventModule] 触发事件: ${n}, 监听器数量: ${i.length}`,t),i.forEach((s,r)=>{try{s(t)}catch(a){console.error(`[EventModule] 事件监听器执行错误 [${n}] #${r}:`,a)}})}}class Rc{engine;constructor(e){this.engine=e}init(){const e=new S.DirectionalLight(16777215,1);e.position.set(100,200,100),e.castShadow=!0,e.shadow.mapSize.width=2048,e.shadow.mapSize.height=2048,e.shadow.camera.near=.1,e.shadow.camera.far=5e3,e.shadow.bias=-5e-5,e.shadow.normalBias=.02;const t=50;e.shadow.camera.left=-t,e.shadow.camera.right=t,e.shadow.camera.top=t,e.shadow.camera.bottom=-t,e.shadow.radius=2;const n=new S.DirectionalLight(16777215,2);this.engine.scene.add(e),this.engine.scene.add(n),this.engine.scene.dirLight=n;const i=new S.AmbientLight(16777215,1);this.engine.scene.add(i)}}var _e=(o=>(o.ModelLoadStart="model-load-start",o.ModelLoadProgress="model-load-progress",o.ModelLoaded="model-loaded",o.ModelError="model-error",o.SelectionChanged="selection-changed",o.HoverChanged="hover-changed",o.Click="click",o.MouseMove="mouse-move",o.CameraChanged="camera-changed",o.CameraIdle="camera-idle",o.EngineFree="engine-free",o.EngineBusy="engine-busy",o.MeasureChanged="measure-changed",o.MeasureClick="measure-click",o.SectionMove="section-move",o))(_e||{});class Fc{engine;behavior;isCtrlDown=!1;highlightedInstances=[];highlightColor=new S.Color(43775);constructor(e){this.engine=e}init(){this.behavior=this.engine.handelBehaved,this.behavior.init(this)}active(){this.behavior.active()}disActive(){this.behavior.disActive()}handelKeyCtrlUp(){this.isCtrlDown=!1}handelKeyCtrlDown(){this.isCtrlDown=!0}hoverOldId=null;handleMouseMove(e){if(!this.engine.engineStatus.isFree){this.engine.hoverHighLight.clearHighlight();return}let t=this.getCatchMeshs(e);t!=null?t.length>0&&this.engine.hoverHighLight.hightMesh(t):this.engine.hoverHighLight.clearHighlight()}getCatchMeshs(e){if(e.catch==null)return this.hoverOldId=null,null;if(e.catch.object.isInstance){let t=e.catch.object,n=e.catch.object.id,i=this.engine.models.find(a=>a.url==t.url).nodesMap.get(n),s=new Map;i?.indexes.forEach(a=>{this.engine.scene.children[a[0]]instanceof S.InstancedMesh&&(s.has(a[0])?s.get(a[0])?.push(a[1]):s.set(a[0],[a[1]]))});let r=[];return s.forEach((a,l)=>{let h=this.engine.scene.children[l];a.forEach(c=>{let d=h.geometry.clone();d.applyMatrix4(h.matrixs[c]),r.push(new S.Mesh(d,h.material))})}),this.hoverOldId==n?[]:(this.hoverOldId=n,this.engine.hoverHighLight.clearHighlight(),r)}else{const t=e.catch;t.object;let n=t.object,i=n.name,a=this.engine.models.find(l=>l.url===n.url).nodesMap.get(i).infos.map(l=>l.mesh);return this.hoverOldId==i?[]:(this.hoverOldId=i,this.engine.hoverHighLight.clearHighlight(),a)}}handleMouseClick(e){if(e.catch!=null){const t=e.catch;let n=t.object;this.isCtrlDown||this.engine.modelToolModule.unhighlightAllModels(),console.log([{url:n.url,ids:[n.name]}]),this.engine.controlModule.orbitControls.origin.set(t.point.x,t.point.y,t.point.z),this.engine.modelToolModule.highlightModel([{url:n.url,ids:[n.name]}]),this.engine.events.trigger(_e.Click,[{url:n.url,ids:[n.name]}])}else this.engine.modelToolModule.unhighlightAllModels()}handleMouseDoubleClick(e){if(e.catch){const n=e.catch;n.object;let i=n.object,r=this.engine.models.find(a=>a.url===i.url).nodesMap.get(i.name);if(n.object.isInstance){let a=n.matrix,l=[];r.indexes.forEach(c=>{let d=c[0],m=this.engine.scene.children[d].geometry.boundingSphere;const p=new S.Box3,f=m.center.clone().applyMatrix4(a),u=m.radius,g=new S.Vector3;g.setFromMatrixScale(a);const y=Math.max(g.x,g.y,g.z),w=u*y;p.min.set(f.x-w,f.y-w,f.z-w),p.max.set(f.x+w,f.y+w,f.z+w),l.push(p)});let h=t(l);this.engine.viewCube.zoomToModel(h)}else{let a=r.infos.map(h=>h.box),l=t(a);this.engine.viewCube.zoomToModel(l)}}function t(n){let i=new S.Vector3(1e8,1e9,1e10),s=new S.Vector3(-1e8,-1e9,-1e10);return n.forEach(r=>{r.min.x<i.x&&(i.x=r.min.x),r.min.y<i.y&&(i.y=r.min.y),r.min.z<i.z&&(i.z=r.min.z),r.max.x>s.x&&(s.x=r.max.x),r.max.y>s.y&&(s.y=r.max.y),r.max.z>s.z&&(s.z=r.max.z)}),new S.Box3(i,s)}}handleMouseClickInstance(e){return e.intersectObjects(this.engine.scene.children.filter(n=>n instanceof S.InstancedMesh),!0)}}class Uc{engine;highlightMaterial;hideMaterial;translucentMaterial;constructor(e){this.engine=e,this.highlightMaterial=new S.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:S.DoubleSide}),this.hideMaterial=new S.MeshBasicMaterial({color:0,transparent:!0,opacity:0,side:S.DoubleSide}),this.translucentMaterial=new S.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:S.DoubleSide}),this.highlightMaterial.clippingPlanes=this.engine.sectionPlane,this.hideMaterial.clippingPlanes=this.engine.sectionPlane,this.translucentMaterial.clippingPlanes=this.engine.sectionPlane}split_merge_model(e){if(e.isSplit||e instanceof S.InstancedMesh)return;let t=e.materialClone.clone(),n=kr(e.geometrys,!0);n.groups.forEach(i=>{i.materialIndex=0}),e.geometry=n,e.material=[t,this.highlightMaterial,this.translucentMaterial],e.needsUpdate=!0,e.isSplit=!0}un_split_merge_model(e){}highlightModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{this.engine.scene.children[a[0]]instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(console.log(this.engine.scene.children[a[0]].materialClone.color),this.split_merge_model(this.engine.scene.children[a[0]]),this.engine.scene.children[a[0]].geometry.groups[a[1]].materialIndex=1)})}),Vc(n,this.engine);let i=this.engine.engineStatus.highlightModels.find(s=>s.url==t.url);i!=null?i.ids.push(...t.ids):this.engine.engineStatus.highlightModels.push(t)})}unhighlightModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(i=>{let s=this.engine.models.find(r=>r.url==t.url).nodesMap.get(i);s!=null&&s.indexes!=null&&s.indexes.forEach(r=>{this.engine.scene.children[r[0]]instanceof S.InstancedMesh?n.has(r[0])?n.get(r[0])?.push(r[1]):n.set(r[0],[r[1]]):this.engine.scene.children[r[0]].geometry.groups[r[1]].materialIndex=0})}),Fr(n,this.engine,"highlightModel")})}unhighlightAllModels(e=!0){this.engine.engineStatus.highlightModels.forEach(t=>{this.unhighlightModel([t])}),e&&(this.engine.engineStatus.highlightModels=[])}hideModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);this.engine.modelEdge.hideModelEdge(t.url,s),r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(this.split_merge_model(this.engine.scene.children[a[0]]),l.geometry.groups[a[1]].materialIndex=-1,l.geometry.groups[a[1]].visible=!1)})}),n.size>0&&Gc(n,this.engine);let i=this.engine.engineStatus.hideModels.find(s=>s.url==t.url);i!=null?i.ids.push(...t.ids):this.engine.engineStatus.hideModels.push({url:t.url,ids:t.ids}),this.engine.engineStatus.highlightModels=[]})}showModel(e){e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);this.engine.modelEdge.showModelEdge(t.url,s),r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(l.geometry.groups[a[1]].materialIndex=0,l.geometry.groups[a[1]].visible=!0)})}),n.size>0&&Ur(n,this.engine);let i=this.engine.engineStatus.hideModels.find(s=>s.url==t.url);i&&(t.ids.forEach(s=>{const r=i.ids.indexOf(s);r!==-1&&i.ids.splice(r,1)}),i.ids.length===0&&(this.engine.engineStatus.hideModels=this.engine.engineStatus.hideModels.filter(s=>s!==i)))})}isolateModel(e){let t=[];this.engine.models.forEach(n=>{let i={url:n.url,ids:[]},s=e.find(r=>r.url==n.url);for(let r of n.nodesMap)s==null?i.ids.push(r[0]):s.ids.includes(r[0])||i.ids.push(r[0]);t.push(i)}),this.unhighlightAllModels(),this.hideModel(t)}translucentOtherModel(e){let t=[];this.engine.models.forEach(n=>{let i={url:n.url,ids:[]},s=e.find(r=>r.url==n.url);for(let r of n.nodesMap)s==null?i.ids.push(r[0]):s.ids.includes(r[0])||i.ids.push(r[0]);t.push(i)}),this.translucentModel(t)}setModelColor(e,t){e.material.color.set(t)}setAllModelsColor(e){this.engine.scene.children.forEach(t=>{t.isMesh})}restoreAllModelsColor(){this.engine.scene.children.forEach(e=>{e.isMesh})}translucentModel(e){this.unhighlightAllModels(),e.forEach(t=>{let n=new Map;t.ids.forEach(s=>{let r=this.engine.models.find(a=>a.url==t.url).nodesMap.get(s);r!=null&&r.indexes!=null&&r.indexes.forEach(a=>{const l=this.engine.scene.children[a[0]];l instanceof S.InstancedMesh?n.has(a[0])?n.get(a[0])?.push(a[1]):n.set(a[0],[a[1]]):(this.split_merge_model(this.engine.scene.children[a[0]]),l.geometry.groups[a[1]].materialIndex=2)})}),jc(n,this.engine);let i=this.engine.engineStatus.translucentModels.find(s=>s.url==t.url);i!=null?i.ids.push(...t.ids):this.engine.engineStatus.translucentModels.push({url:t.url,ids:t.ids})}),this.engine.engineStatus.highlightModels=[]}unTranslucentModel(){this.engine.engineStatus.translucentModels.forEach(t=>{let n=new Map;t.ids.forEach(i=>{let s=this.engine.models.find(r=>r.url==t.url).nodesMap.get(i);s!=null&&s.indexes!=null&&s.indexes.forEach(r=>{const a=this.engine.scene.children[r[0]];a instanceof S.InstancedMesh?n.has(r[0])?n.get(r[0])?.push(r[1]):n.set(r[0],[r[1]]):(this.split_merge_model(this.engine.scene.children[r[0]]),a.geometry.groups[r[1]].materialIndex=0)})}),n.size>0&&Ur(n,this.engine),Fr(n,this.engine,"translucentModel")}),this.engine.engineStatus.translucentModels=[]}showAllModels(){this.engine.engineStatus.hideModels&&this.engine.engineStatus.hideModels.length>0&&this.showModel(this.engine.engineStatus.hideModels),this.engine.engineStatus.hideModels=[],this.unhighlightAllModels()}batchSelectSameLevelTypeModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevelType(n.levelName,n.typeName,i=>{this.engine.modelToolModule.highlightModel(i)})}batchSelectSameLevelModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithLevel(n.levelName,i=>{this.engine.modelToolModule.highlightModel(i)})}batchSelectSameTypeModel(e){if(e.length==0)return;let t=e[0],n=this.engine.modelMapperBatch.getModelMapper(t.url,t.ids[0]);this.engine.modelMapperBatch.getModelsWithType(n.typeName,i=>{this.engine.modelToolModule.highlightModel(i)})}}function Vc(o,e){o.forEach((t,n)=>{const i=e.scene.children[n];if(!(i instanceof S.InstancedMesh))return;const s=i.geometry,r=new S.MeshBasicMaterial({color:43775,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.5,side:S.DoubleSide}),a=new S.InstancedMesh(s,r,t.length);a.name="highlightModel",a.key=n;const l=new Map,h=new S.Matrix4,c=new S.Matrix4;c.makeScale(0,0,0),t.forEach((d,m)=>{i.getMatrixAt(d,h),l.set(d,h.clone()),i.setMatrixAt(d,c),a.setMatrixAt(m,h)}),i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function Fr(o,e,t){o.forEach((n,i)=>{const s=e.scene.children[i];if(!(s instanceof S.InstancedMesh))return;n.forEach(a=>{const l=s.matrixsClone[a];l&&s.setMatrixAt(a,l)}),s.instanceMatrix.needsUpdate=!0,e.scene.children.filter(a=>a.key==i&&a.name==t).forEach(a=>{e.scene.remove(a)})})}function jc(o,e){o.forEach((t,n)=>{const i=e.scene.children[n];if(!(i instanceof S.InstancedMesh))return;const s=i.geometry,r=new S.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.05,side:S.DoubleSide}),a=new S.InstancedMesh(s,r,t.length);a.name="translucentModel",a.key=n;const l=new Map,h=new S.Matrix4,c=new S.Matrix4;c.makeScale(0,0,0),t.forEach((d,m)=>{i.getMatrixAt(d,h),l.set(d,h.clone()),i.setMatrixAt(d,c),a.setMatrixAt(m,h)}),i.instanceMatrix.needsUpdate=!0,a.instanceMatrix.needsUpdate=!0,e.scene.add(a)})}function Gc(o,e){e.scene.children.filter(t=>t.name=="highlightModel").forEach(t=>{e.scene.remove(t)}),o.forEach((t,n)=>{const i=e.scene.children[n];if(!(i instanceof S.InstancedMesh))return;const s=new Map,r=new S.Matrix4,a=new S.Matrix4;a.makeScale(0,0,0),t.forEach((l,h)=>{i.getMatrixAt(l,r),s.set(l,r.clone()),i.setMatrixAt(l,a)}),i.instanceMatrix.needsUpdate=!0})}function Ur(o,e){o.forEach((t,n)=>{const i=e.scene.children[n];i instanceof S.InstancedMesh&&(t.forEach(s=>{const r=i.matrixs[s];r&&i.setMatrixAt(s,r)}),i.instanceMatrix.needsUpdate=!0)})}class Wc{engine;currentMode="";isManualMode=!1;gtaoPass=null;ssaoPass=null;saturationPass=null;outputPass=null;fxaaPass=null;constructor(e){this.engine=e}init(){this.cachePassReferences(),this.autoSwitch("advanced")}switchModel(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}autoSwitch(e){this.isManualMode||(this.currentMode=e,this.applyMode(e))}enableAutoMode(){this.isManualMode=!1}get isManual(){return this.isManualMode}setMode(e){this.isManualMode=!0,this.currentMode=e,this.applyMode(e)}getCurrentMode(){return this.currentMode}cachePassReferences(){this.engine.composerModule?.composer&&(this.engine.composerModule.gtaoPass&&(this.gtaoPass=this.engine.composerModule.gtaoPass),this.engine.composerModule.ssaoPass&&(this.ssaoPass=this.engine.composerModule.ssaoPass),this.engine.composerModule.saturationPass&&(this.saturationPass=this.engine.composerModule.saturationPass),this.engine.composerModule.outputPass&&(this.outputPass=this.engine.composerModule.outputPass),this.engine.composerModule.fxaaPass&&(this.fxaaPass=this.engine.composerModule.fxaaPass))}applyMode(e){switch(e){case"simple":this.setShadows(!1),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!1);break;case"balance":this.setShadows(!0),this.setGTAO(!1),this.setSSAO(!1),this.setSaturation(!1),this.setOutputPass(!1),this.setFXAA(!1);break;case"advanced":this.setShadows(!0),this.setSSAO(!1),this.setGTAO(!0),this.setSaturation(!0),this.setOutputPass(!0),this.setFXAA(!0);break;default:console.warn(`[EngineModelModule] Unknown mode: ${e}`)}this.engine.updateVersionDisplay?.()}setShadows(e){this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e);const t=this.engine.scene?.children.find(n=>n instanceof S.DirectionalLight);t&&(t.castShadow=e),this.engine.scene?.traverse(n=>{n.material&&(n.castShadow!==void 0&&(n.castShadow=e),n.receiveShadow!==void 0&&(n.receiveShadow=e))})}setGTAO(e){this.engine.composerModule?.composer&&this.gtaoPass&&(this.gtaoPass.enabled=e)}setSSAO(e){this.engine.composerModule?.composer&&this.ssaoPass&&(this.ssaoPass.enabled=e)}setSaturation(e){this.saturationPass&&(this.saturationPass.enabled=e)}setOutputPass(e){this.outputPass&&(this.outputPass.enabled=e)}setFXAA(e){this.fxaaPass&&(this.fxaaPass.enabled=e)}setPerformanceMode(){this.setMode("simple")}setBalancedMode(){this.setMode("balance")}setQualityMode(){this.setMode("advanced")}setSuperQualityMode(){this.setMode("superAdvanced")}setShadowQuality(e){const t=this.engine.scene?.children.find(s=>s instanceof S.DirectionalLight),i={low:1024,medium:2048,high:2048}[e];t?.shadow&&i&&(t.shadow.mapSize.width=i,t.shadow.mapSize.height=i,t.shadow.map?.dispose(),t.shadow.map=null)}setSaturationValue(e){this.saturationPass&&(this.saturationPass.uniforms.saturation.value=e)}setContrastValue(e){this.saturationPass&&(this.saturationPass.uniforms.contrast.value=e)}setGTAOIntensity(e){this.gtaoPass&&(this.gtaoPass.blendIntensity=e)}}class qn{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;constructor(e){this.engine=e,this.init()}init(){this.overlayMaterial=new S.MeshBasicMaterial({color:16777215,transparent:!0,opacity:0,blending:S.AdditiveBlending,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,n=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const i=(Array.isArray(e)?e:e?[e]:[]).filter(s=>s?.geometry);if(i.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=n;for(const s of i){const r=new S.Mesh(s.geometry,this.overlayMaterial);s.updateWorldMatrix(!0,!1),r.matrix.copy(s.matrixWorld),r.matrixAutoUpdate=!1,this.engine.scene.add(r),this.overlayMeshes.push(r)}this.animState="fadeIn",this.animStartTime=performance.now()}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now())}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const n=Math.min(e/qn.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(n)*t,n>=1&&(this.animState="idle")}else if(this.animState==="fadeOut"){const n=Math.min(e/qn.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(n))*t,n>=1&&(this.removeOverlayMeshes(),this.animState="idle")}}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e);this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.animState="idle"}}var Kn={exports:{}},Xc=Kn.exports,Vr;function Zc(){return Vr||(Vr=1,(function(o,e){(function(t,n){o.exports=n()})(Xc,function(){var t=function(){function n(p){return r.appendChild(p.dom),p}function i(p){for(var f=0;f<r.children.length;f++)r.children[f].style.display=f===p?"block":"none";s=p}var s=0,r=document.createElement("div");r.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",r.addEventListener("click",function(p){p.preventDefault(),i(++s%r.children.length)},!1);var a=(performance||Date).now(),l=a,h=0,c=n(new t.Panel("FPS","#0ff","#002")),d=n(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var m=n(new t.Panel("MB","#f08","#201"));return i(0),{REVISION:16,dom:r,addPanel:n,showPanel:i,begin:function(){a=(performance||Date).now()},end:function(){h++;var p=(performance||Date).now();if(d.update(p-a,200),p>l+1e3&&(c.update(1e3*h/(p-l),100),l=p,h=0,m)){var f=performance.memory;m.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return p},update:function(){a=this.end()},domElement:r,setMode:i}};return t.Panel=function(n,i,s){var r=1/0,a=0,l=Math.round,h=l(window.devicePixelRatio||1),c=80*h,d=48*h,m=3*h,p=2*h,f=3*h,u=15*h,g=74*h,y=30*h,w=document.createElement("canvas");w.width=c,w.height=d,w.style.cssText="width:80px;height:48px";var x=w.getContext("2d");return x.font="bold "+9*h+"px Helvetica,Arial,sans-serif",x.textBaseline="top",x.fillStyle=s,x.fillRect(0,0,c,d),x.fillStyle=i,x.fillText(n,m,p),x.fillRect(f,u,g,y),x.fillStyle=s,x.globalAlpha=.9,x.fillRect(f,u,g,y),{dom:w,update:function(v,b){r=Math.min(r,v),a=Math.max(a,v),x.fillStyle=s,x.globalAlpha=1,x.fillRect(0,0,c,u),x.fillStyle=i,x.fillText(l(v)+" "+n+" ("+l(r)+"-"+l(a)+")",m,p),x.drawImage(w,f+h,u,g-h,y,f,u,g-h,y),x.fillRect(f+g-h,u,h,y),x.fillStyle=s,x.globalAlpha=.9,x.fillRect(f+g-h,u,h,l((1-v/b)*y))}}},t})})(Kn)),Kn.exports}var qc=Zc();const Kc=Us(qc);var Zt=Object.freeze({Linear:Object.freeze({None:function(o){return o},In:function(o){return o},Out:function(o){return o},InOut:function(o){return o}}),Quadratic:Object.freeze({In:function(o){return o*o},Out:function(o){return o*(2-o)},InOut:function(o){return(o*=2)<1?.5*o*o:-.5*(--o*(o-2)-1)}}),Cubic:Object.freeze({In:function(o){return o*o*o},Out:function(o){return--o*o*o+1},InOut:function(o){return(o*=2)<1?.5*o*o*o:.5*((o-=2)*o*o+2)}}),Quartic:Object.freeze({In:function(o){return o*o*o*o},Out:function(o){return 1- --o*o*o*o},InOut:function(o){return(o*=2)<1?.5*o*o*o*o:-.5*((o-=2)*o*o*o-2)}}),Quintic:Object.freeze({In:function(o){return o*o*o*o*o},Out:function(o){return--o*o*o*o*o+1},InOut:function(o){return(o*=2)<1?.5*o*o*o*o*o:.5*((o-=2)*o*o*o*o+2)}}),Sinusoidal:Object.freeze({In:function(o){return 1-Math.sin((1-o)*Math.PI/2)},Out:function(o){return Math.sin(o*Math.PI/2)},InOut:function(o){return .5*(1-Math.sin(Math.PI*(.5-o)))}}),Exponential:Object.freeze({In:function(o){return o===0?0:Math.pow(1024,o-1)},Out:function(o){return o===1?1:1-Math.pow(2,-10*o)},InOut:function(o){return o===0?0:o===1?1:(o*=2)<1?.5*Math.pow(1024,o-1):.5*(-Math.pow(2,-10*(o-1))+2)}}),Circular:Object.freeze({In:function(o){return 1-Math.sqrt(1-o*o)},Out:function(o){return Math.sqrt(1- --o*o)},InOut:function(o){return(o*=2)<1?-.5*(Math.sqrt(1-o*o)-1):.5*(Math.sqrt(1-(o-=2)*o)+1)}}),Elastic:Object.freeze({In:function(o){return o===0?0:o===1?1:-Math.pow(2,10*(o-1))*Math.sin((o-1.1)*5*Math.PI)},Out:function(o){return o===0?0:o===1?1:Math.pow(2,-10*o)*Math.sin((o-.1)*5*Math.PI)+1},InOut:function(o){return o===0?0:o===1?1:(o*=2,o<1?-.5*Math.pow(2,10*(o-1))*Math.sin((o-1.1)*5*Math.PI):.5*Math.pow(2,-10*(o-1))*Math.sin((o-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(o){var e=1.70158;return o===1?1:o*o*((e+1)*o-e)},Out:function(o){var e=1.70158;return o===0?0:--o*o*((e+1)*o+e)+1},InOut:function(o){var e=2.5949095;return(o*=2)<1?.5*(o*o*((e+1)*o-e)):.5*((o-=2)*o*((e+1)*o+e)+2)}}),Bounce:Object.freeze({In:function(o){return 1-Zt.Bounce.Out(1-o)},Out:function(o){return o<1/2.75?7.5625*o*o:o<2/2.75?7.5625*(o-=1.5/2.75)*o+.75:o<2.5/2.75?7.5625*(o-=2.25/2.75)*o+.9375:7.5625*(o-=2.625/2.75)*o+.984375},InOut:function(o){return o<.5?Zt.Bounce.In(o*2)*.5:Zt.Bounce.Out(o*2-1)*.5+.5}}),generatePow:function(o){return o===void 0&&(o=4),o=o<Number.EPSILON?Number.EPSILON:o,o=o>1e4?1e4:o,{In:function(e){return Math.pow(e,o)},Out:function(e){return 1-Math.pow(1-e,o)},InOut:function(e){return e<.5?Math.pow(e*2,o)/2:(1-Math.pow(2-e*2,o))/2+.5}}}}),cn=function(){return performance.now()},Yc=(function(){function o(){this._tweens={},this._tweensAddedDuringUpdate={}}return o.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},o.prototype.removeAll=function(){this._tweens={}},o.prototype.add=function(e){this._tweens[e.getId()]=e,this._tweensAddedDuringUpdate[e.getId()]=e},o.prototype.remove=function(e){delete this._tweens[e.getId()],delete this._tweensAddedDuringUpdate[e.getId()]},o.prototype.update=function(e,t){e===void 0&&(e=cn()),t===void 0&&(t=!1);var n=Object.keys(this._tweens);if(n.length===0)return!1;for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<n.length;i++){var s=this._tweens[n[i]],r=!t;s&&s.update(e,r)===!1&&!t&&delete this._tweens[n[i]]}n=Object.keys(this._tweensAddedDuringUpdate)}return!0},o})(),Zi={Linear:function(o,e){var t=o.length-1,n=t*e,i=Math.floor(n),s=Zi.Utils.Linear;return e<0?s(o[0],o[1],n):e>1?s(o[t],o[t-1],t-n):s(o[i],o[i+1>t?t:i+1],n-i)},Utils:{Linear:function(o,e,t){return(e-o)*t+o}}},jr=(function(){function o(){}return o.nextId=function(){return o._nextId++},o._nextId=0,o})(),qi=new Yc,$c=(function(){function o(e,t){t===void 0&&(t=qi),this._object=e,this._group=t,this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=Zt.Linear.None,this._interpolationFunction=Zi.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=jr.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return o.prototype.getId=function(){return this._id},o.prototype.isPlaying=function(){return this._isPlaying},o.prototype.isPaused=function(){return this._isPaused},o.prototype.getDuration=function(){return this._duration},o.prototype.to=function(e,t){if(t===void 0&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},o.prototype.duration=function(e){return e===void 0&&(e=1e3),this._duration=e<0?0:e,this},o.prototype.dynamic=function(e){return e===void 0&&(e=!1),this._isDynamic=e,this},o.prototype.start=function(e,t){if(e===void 0&&(e=cn()),t===void 0&&(t=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var n in this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},o.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},o.prototype._setupProperties=function(e,t,n,i,s){for(var r in n){var a=e[r],l=Array.isArray(a),h=l?"array":typeof a,c=!l&&Array.isArray(n[r]);if(!(h==="undefined"||h==="function")){if(c){var d=n[r];if(d.length===0)continue;for(var m=[a],p=0,f=d.length;p<f;p+=1){var u=this._handleRelativeValue(a,d[p]);if(isNaN(u)){c=!1,console.warn("Found invalid interpolation list. Skipping.");break}m.push(u)}c&&(n[r]=m)}if((h==="object"||l)&&a&&!c){t[r]=l?[]:{};var g=a;for(var y in g)t[r][y]=g[y];i[r]=l?[]:{};var d=n[r];if(!this._isDynamic){var w={};for(var y in d)w[y]=d[y];n[r]=d=w}this._setupProperties(g,t[r],d,i[r],s)}else(typeof t[r]>"u"||s)&&(t[r]=a),l||(t[r]*=1),c?i[r]=n[r].slice().reverse():i[r]=t[r]||0}}},o.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},o.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},o.prototype.pause=function(e){return e===void 0&&(e=cn()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=e,this._group&&this._group.remove(this),this)},o.prototype.resume=function(e){return e===void 0&&(e=cn()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},o.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},o.prototype.group=function(e){return e===void 0&&(e=qi),this._group=e,this},o.prototype.delay=function(e){return e===void 0&&(e=0),this._delayTime=e,this},o.prototype.repeat=function(e){return e===void 0&&(e=0),this._initialRepeat=e,this._repeat=e,this},o.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},o.prototype.yoyo=function(e){return e===void 0&&(e=!1),this._yoyo=e,this},o.prototype.easing=function(e){return e===void 0&&(e=Zt.Linear.None),this._easingFunction=e,this},o.prototype.interpolation=function(e){return e===void 0&&(e=Zi.Linear),this._interpolationFunction=e,this},o.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},o.prototype.onStart=function(e){return this._onStartCallback=e,this},o.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},o.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},o.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},o.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},o.prototype.onStop=function(e){return this._onStopCallback=e,this},o.prototype.update=function(e,t){var n=this,i;if(e===void 0&&(e=cn()),t===void 0&&(t=!0),this._isPaused)return!0;var s,r=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(e>r)return!1;t&&this.start(e,!0)}if(this._goToEnd=!1,e<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=e-this._startTime,l=this._duration+((i=this._repeatDelayTime)!==null&&i!==void 0?i:this._delayTime),h=this._duration+this._repeat*l,c=function(){if(n._duration===0||a>h)return 1;var g=Math.trunc(a/l),y=a-g*l,w=Math.min(y/n._duration,1);return w===0&&a===n._duration?1:w},d=c(),m=this._easingFunction(d);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,m),this._onUpdateCallback&&this._onUpdateCallback(this._object,d),this._duration===0||a>=this._duration)if(this._repeat>0){var p=Math.min(Math.trunc((a-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=p);for(s in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[s]=="string"&&(this._valuesStartRepeat[s]=this._valuesStartRepeat[s]+parseFloat(this._valuesEnd[s])),this._yoyo&&this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=l*p,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var f=0,u=this._chainedTweens.length;f<u;f++)this._chainedTweens[f].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},o.prototype._updateProperties=function(e,t,n,i){for(var s in n)if(t[s]!==void 0){var r=t[s]||0,a=n[s],l=Array.isArray(e[s]),h=Array.isArray(a),c=!l&&h;c?e[s]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(e[s],r,a,i):(a=this._handleRelativeValue(r,a),typeof a=="number"&&(e[s]=r+(a-r)*i))}},o.prototype._handleRelativeValue=function(e,t){return typeof t!="string"?t:t.charAt(0)==="+"||t.charAt(0)==="-"?e+parseFloat(t):parseFloat(t)},o.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];typeof n=="string"?this._valuesStartRepeat[e]=this._valuesStartRepeat[e]+parseFloat(n):this._valuesStartRepeat[e]=this._valuesEnd[e],this._valuesEnd[e]=t},o})();jr.nextId;var et=qi;et.getAll.bind(et),et.removeAll.bind(et),et.add.bind(et),et.remove.bind(et),et.update.bind(et);var hn={Easing:Zt,Tween:$c};class Hc extends _.DataTextureLoader{constructor(e){super(e),this.type=_.HalfFloatType}parse(e){const r=function(k,P){switch(k){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(P||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(P||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(P||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(P||""))}},d=function(k,P,I){P=P||1024;let C=k.pos,E=-1,M=0,B="",V=String.fromCharCode.apply(null,new Uint16Array(k.subarray(C,C+128)));for(;0>(E=V.indexOf(`
968
968
  `))&&M<P&&C<k.byteLength;)B+=V,M+=V.length,C+=128,V+=String.fromCharCode.apply(null,new Uint16Array(k.subarray(C,C+128)));return-1<E?(k.pos+=M+E+1,B+V.slice(0,E)):!1},m=function(k){const P=/^#\?(\S+)/,I=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,z=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,C=/^\s*FORMAT=(\S+)\s*$/,E=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,M={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let B,V;for((k.pos>=k.byteLength||!(B=d(k)))&&r(1,"no header found"),(V=B.match(P))||r(3,"bad initial token"),M.valid|=1,M.programtype=V[1],M.string+=B+`
969
969
  `;B=d(k),B!==!1;){if(M.string+=B+`
970
970
  `,B.charAt(0)==="#"){M.comments+=B+`
971
- `;continue}if((V=B.match(I))&&(M.gamma=parseFloat(V[1])),(V=B.match(z))&&(M.exposure=parseFloat(V[1])),(V=B.match(C))&&(M.valid|=2,M.format=V[1]),(V=B.match(E))&&(M.valid|=4,M.height=parseInt(V[1],10),M.width=parseInt(V[2],10)),M.valid&2&&M.valid&4)break}return M.valid&2||r(3,"missing format specifier"),M.valid&4||r(3,"missing image size specifier"),M},p=function(k,P,I){const z=P;if(z<8||z>32767||k[0]!==2||k[1]!==2||k[2]&128)return new Uint8Array(k);z!==(k[2]<<8|k[3])&&r(3,"wrong scanline width");const C=new Uint8Array(4*P*I);C.length||r(4,"unable to allocate buffer space");let E=0,M=0;const B=4*z,V=new Uint8Array(4),U=new Uint8Array(B);let H=I;for(;H>0&&M<k.byteLength;){M+4>k.byteLength&&r(1),V[0]=k[M++],V[1]=k[M++],V[2]=k[M++],V[3]=k[M++],(V[0]!=2||V[1]!=2||(V[2]<<8|V[3])!=z)&&r(3,"bad rgbe scanline format");let G=0,$;for(;G<B&&M<k.byteLength;){$=k[M++];const N=$>128;if(N&&($-=128),($===0||G+$>B)&&r(3,"bad scanline data"),N){const te=k[M++];for(let ee=0;ee<$;ee++)U[G++]=te}else U.set(k.subarray(M,M+$),G),G+=$,M+=$}const F=z;for(let N=0;N<F;N++){let te=0;C[E]=U[N+te],te+=z,C[E+1]=U[N+te],te+=z,C[E+2]=U[N+te],te+=z,C[E+3]=U[N+te],E+=4}H--}return C},f=function(k,P,I,z){const C=k[P+3],E=Math.pow(2,C-128)/255;I[z+0]=k[P+0]*E,I[z+1]=k[P+1]*E,I[z+2]=k[P+2]*E,I[z+3]=1},u=function(k,P,I,z){const C=k[P+3],E=Math.pow(2,C-128)/255;I[z+0]=_.DataUtils.toHalfFloat(Math.min(k[P+0]*E,65504)),I[z+1]=_.DataUtils.toHalfFloat(Math.min(k[P+1]*E,65504)),I[z+2]=_.DataUtils.toHalfFloat(Math.min(k[P+2]*E,65504)),I[z+3]=_.DataUtils.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const y=m(g),w=y.width,x=y.height,v=p(g.subarray(g.pos),w,x);let b,D,T;switch(this.type){case _.FloatType:T=v.length/4;const k=new Float32Array(T*4);for(let I=0;I<T;I++)f(v,I*4,k,I*4);b=k,D=_.FloatType;break;case _.HalfFloatType:T=v.length/4;const P=new Uint16Array(T*4);for(let I=0;I<T;I++)u(v,I*4,P,I*4);b=P,D=_.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:w,height:x,data:b,header:y.string,gamma:y.gamma,exposure:y.exposure,type:D}}setDataType(e){return this.type=e,this}load(e,t,n,i){function s(r,a){switch(r.type){case _.FloatType:case _.HalfFloatType:r.colorSpace=_.LinearSRGBColorSpace,r.minFilter=_.LinearFilter,r.magFilter=_.LinearFilter,r.generateMipmaps=!1,r.flipY=!0;break}t&&t(r,a)}return super.load(e,s,n,i)}}function Jc(){return new S.Scene}function Qc(o,e){o.appendChild(e.domElement)}function eh(o,e,t){var n=new Object;n.visible=!0;let i=null,s,r,a=[];n.init=function(){s||(h(),c(),d())},n.Hide=function(){s.style.display="none",n.visible=!1},n.Show=function(){s.style.display="block",n.visible=!0},n.RenderScene=function(){n.camera.quaternion.copy(e.camera.quaternion);const f=new S.Vector3(0,0,1).applyQuaternion(e.camera.quaternion);n.camera.position.copy(f.multiplyScalar(100)),n.sceneOrtho.renderer.render(n.sceneOrtho,n.camera)},n.ToggleDirectionView=function(f){var u=new S.Vector3(0,0,0);f=="top"?u=new S.Vector3(0,1,1e-5):f=="down"?u=new S.Vector3(0,-1,1e-5):f=="front"?u=new S.Vector3(0,0,1):f=="left"?u=new S.Vector3(-1,0,0):f=="back"?u=new S.Vector3(0,0,-1):f=="right"?u=new S.Vector3(1,0,0):f=="top_front"?u=new S.Vector3(1,1,0):f=="top_left"?u=new S.Vector3(0,1,-1):f=="top_back"?u=new S.Vector3(-1,1,0):f=="top_right"?u=new S.Vector3(0,1,1):f=="down_front"?u=new S.Vector3(1,-1,0):f=="down_left"?u=new S.Vector3(0,-1,-1):f=="down_back"?u=new S.Vector3(-1,-1,0):f=="down_right"?u=new S.Vector3(0,-1,1):f=="front_right"?u=new S.Vector3(1,0,1):f=="right_back"?u=new S.Vector3(-1,0,1):f=="back_left"?u=new S.Vector3(-1,0,-1):f=="left_front"?u=new S.Vector3(1,0,-1):f=="top_left_front"?u=new S.Vector3(1,1,-1):f=="top_front_right"?u=new S.Vector3(1,1,1):f=="top_right_back"?u=new S.Vector3(-1,1,1):f=="top_back_left"?u=new S.Vector3(-1,1,-1):f=="button_left_front"?u=new S.Vector3(1,-1,-1):f=="button_front_right"?u=new S.Vector3(1,-1,1):f=="button_right_back"?u=new S.Vector3(-1,1,1):f=="button_back_left"&&(u=new S.Vector3(-1,-1,-1));var g=o.octreeBox.getBoundingBox(),y=g.min,w=g.max,x=y.clone().add(w.clone()).multiplyScalar(.5),v=x.clone().add(u.multiplyScalar(1*w.distanceTo(y)));l(e.camera.position,v,o.controls.target.clone(),x)},n.GetCameraPose=function(){var f=e.camera.quaternion,u=e.camera.position,g=o.controls.target,y={quaternion:f,position:u,target:g};return y},n.ReductionCameraPose=function(f,u=1e3,g){var y=new S.Quaternion(f.quaternion._x,f.quaternion._y,f.quaternion._z,f.quaternion._w),w=new S.Vector3(f.position.x,f.position.y,f.position.z),x=new S.Vector3(f.target.x,f.target.y,f.target.z);let v=!1;l(e.camera.position,w,o.controls.target.clone(),x,e.camera.quaternion,y,u,b=>{g&&(v||(g(b),v=!0))}),g&&setTimeout(()=>{v||(g(!0),v=!0)},u+10)},n.CameraGoHome=function(){var f=o.octreeBox.getBoundingBox(),u=f.min.clone().add(f.max.clone()).multiplyScalar(.5);let g=new S.Vector3(1,1,1);var y=f.max.distanceTo(f.min),w=u.clone().add(g.multiplyScalar(y*.5));if(e.camera.isOrthographicCamera){var x=o.container.clientWidth/o.container.clientHeight,v=y*.6;e.camera.left=-v*x,e.camera.right=v*x,e.camera.top=v,e.camera.bottom=-v,e.camera.zoom=1,e.camera.updateProjectionMatrix()}l(e.camera.position,w,o.controls.target.clone(),u)},n.zoomToBox=function(f){if(e.camera.isOrthographicCamera){let N=function(){i=requestAnimationFrame(N),F.update()};var u=f.min.clone().add(f.max.clone()).multiplyScalar(.5),g=e.camera.position.clone().sub(o.controls.target.clone()).normalize(),y=e.camera.position.distanceTo(o.controls.target),w=u.clone().add(g.multiplyScalar(y)),x=e.camera.zoom,v=new S.Vector3(1,0,0).applyQuaternion(e.camera.quaternion),b=new S.Vector3(0,1,0).applyQuaternion(e.camera.quaternion),D=[new S.Vector3(f.min.x,f.min.y,f.min.z),new S.Vector3(f.max.x,f.min.y,f.min.z),new S.Vector3(f.min.x,f.max.y,f.min.z),new S.Vector3(f.max.x,f.max.y,f.min.z),new S.Vector3(f.min.x,f.min.y,f.max.z),new S.Vector3(f.max.x,f.min.y,f.max.z),new S.Vector3(f.min.x,f.max.y,f.max.z),new S.Vector3(f.max.x,f.max.y,f.max.z)],T=1/0,k=-1/0,P=1/0,I=-1/0;for(var z of D){var C=z.dot(v),E=z.dot(b);T=Math.min(T,C),k=Math.max(k,C),P=Math.min(P,E),I=Math.max(I,E)}var M=(k-T)/2,B=(I-P)/2,V=(e.camera.right-e.camera.left)/2,U=(e.camera.top-e.camera.bottom)/2;x=Math.min(V/M,U/B)*.75;var H=e.camera.position.clone(),G=o.controls.target.clone(),$=e.camera.zoom,F=new hn.Tween({x1:H.x,y1:H.y,z1:H.z,x2:G.x,y2:G.y,z2:G.z,zoom:$}).to({x1:w.x,y1:w.y,z1:w.z,x2:u.x,y2:u.y,z2:u.z,zoom:x},1e3);F.onUpdate(function(te){o.controls&&(e.camera.position.set(te.x1,te.y1,te.z1),o.controls.target.set(te.x2,te.y2,te.z2),e.camera.isOrthographicCamera&&(e.camera.zoom=te.zoom,e.camera.updateProjectionMatrix()),o.controls.auto=!0,o.controls.update(),n.RenderScene())}),F.onComplete(function(){o.controls&&(o.controls.auto=!1,n.RenderScene(),cancelAnimationFrame(i),i=null)}),F.easing(hn.Easing.Cubic.InOut),F.start(),N()}else{var u=f.min.clone().add(f.max.clone()).multiplyScalar(.5);let ee=e.camera.position.clone().sub(o.controls.target.clone()).normalize();var w=u.clone().add(ee.multiplyScalar(2*f.max.distanceTo(f.min)));l(e.camera.position,w,o.controls.target.clone(),u)}};function l(f,u,g,y,w,x,v=1e3,b){var D;w&&x?(D=new hn.Tween({x1:f.x,y1:f.y,z1:f.z,x2:g.x,y2:g.y,z2:g.z,_x:w._x,_y:w._y,_z:w._z,_w:w._w}),D.to({x1:u.x,y1:u.y,z1:u.z,x2:y.x,y2:y.y,z2:y.z,_x:x._x,_y:x._y,_z:x._z,_w:x._w},v)):(D=new hn.Tween({x1:f.x,y1:f.y,z1:f.z,x2:g.x,y2:g.y,z2:g.z}),D.to({x1:u.x,y1:u.y,z1:u.z,x2:y.x,y2:y.y,z2:y.z},v)),D.onUpdate(function(k){o.controls&&(w&&x?(e.camera.quaternion._x=k._x,e.camera.quaternion._y=k._y,e.camera.quaternion._z=k._z,e.camera.quaternion._w=k._w):o.controls.auto=!0,e.camera.position.x=k.x1,e.camera.position.y=k.y1,e.camera.position.z=k.z1,o.controls.target.x=k.x2,o.controls.target.y=k.y2,o.controls.target.z=k.z2,o.controls.update(),n.RenderScene())}),D.onComplete(function(k){o.controls&&(o.controls.auto=!1,n.RenderScene(),b&&b(!0),cancelAnimationFrame(i),i=null)}),D.easing(hn.Easing.Cubic.InOut);function T(k){i=requestAnimationFrame(T),D.update()}D.start(),T()}function h(){s=document.createElement("div"),s.className="ViewCube",t.appendChild(s),r=document.createElement("div"),r.className="viewSettingWrapper",r.innerHTML="...",s.appendChild(r);var f=document.createElement("div");f.className="homeViewWrapper",f.addEventListener("mousedown",function(){console.log("归位"),n.CameraGoHome()}),s.appendChild(f);const u=document.createElement("div");u.className="cameraToggleWrapper",u.title="切换正交/透视视图",u.innerHTML="⊞",u.addEventListener("mousedown",function(v){v.stopPropagation(),console.log("切换视图"),n.ToggleCameraType(),w()}),s.appendChild(u);const g=document.createElement("div");g.className="screenshotWrapper",g.title="截图",g.innerHTML="📷",g.addEventListener("mousedown",function(v){v.stopPropagation(),console.log("截图"),n.TakeScreenshot(),w()}),s.appendChild(g);const y=document.createElement("div");y.className="fullscreenWrapper",y.title="全屏",y.innerHTML="⛶",y.addEventListener("mousedown",function(v){v.stopPropagation(),console.log("全屏"),n.ToggleFullscreen(),w()}),s.appendChild(y),r.addEventListener("mousedown",function(v){v.stopPropagation(),u.classList.contains("show")?(w(),console.log("隐藏功能按钮")):(x(),console.log("显示功能按钮"))});function w(){u.classList.remove("show"),g.classList.remove("show"),y.classList.remove("show")}function x(){u.classList.add("show"),g.classList.add("show"),y.classList.add("show")}}function c(){n.sceneOrtho=Jc();var g=t.clientWidth,y=t.clientWidth,f=g>y?g/y:y/g,u=300;n.camera=new S.OrthographicCamera(u*f/-2,u*f/2,u/2,u/-2,.01,1e4);var g=s.clientWidth,y=s.clientHeight,w=new S.WebGLRenderer({alpha:!0});w.setSize(g,y),w.setClearAlpha(0),n.sceneOrtho.renderer=w;let x=new S.AmbientLight(16777215,.8);n.sceneOrtho.add(x),Qc(s,w)}function d(){const f="/assets/viewcube/";let u=[{label:"右",icon:f+"cn_right.png"},{label:"左",icon:f+"cn_left.png"},{label:"顶",icon:f+"cn_top.png"},{label:"底",icon:f+"cn_bottom.png"},{label:"前",icon:f+"cn_front.png"},{label:"后",icon:f+"cn_back.png"}];var g=[];for(const w of u)g.push(new S.MeshBasicMaterial({color:16777215,map:new S.TextureLoader().load(w.icon)}));new S.MeshLambertMaterial({color:255});var y=new S.Mesh(new S.BoxGeometry(110,110,110),g);n.sceneOrtho.add(y),m(122),s.addEventListener("mousedown",w=>{var x={};x.x=w.offsetX/s.clientWidth*2-1,x.y=-(w.offsetY/s.clientHeight)*2+1;var v=new S.Raycaster;v.setFromCamera(x,n.camera);const b=v.intersectObjects(a,!1);b.length>0&&n.ToggleDirectionView(b[0].object.name)}),s.addEventListener("mousemove",w=>{var x={};x.x=w.offsetX/s.clientWidth*2-1,x.y=-(w.offsetY/s.clientHeight)*2+1;var v=new S.Raycaster;v.setFromCamera(x,n.camera);const b=v.intersectObjects(a,!1);for(var D of a)D.material.opacity=.01;b.length>0&&(b[0].object.material.opacity=.2)})}function m(f){for(var u=f*.5-20,g=[{name:"right",a:30,b:75,c:75,point:new S.Vector3(u,0,0)},{name:"back",a:75,b:75,c:30,point:new S.Vector3(0,0,-u)},{name:"left",a:30,b:75,c:75,point:new S.Vector3(-u,0,0)},{name:"front",a:75,b:75,c:30,point:new S.Vector3(0,0,u)},{name:"top",a:75,b:30,c:75,point:new S.Vector3(0,u,0)},{name:"button",a:75,b:30,c:75,point:new S.Vector3(0,-u,0)}],y=[{name:"top_right_back",a:30,b:30,c:30,point:new S.Vector3(-u,u,u)},{name:"button_front_right",a:30,b:30,c:30,point:new S.Vector3(-u,-u,u)},{name:"top_front_right",a:30,b:30,c:30,point:new S.Vector3(u,u,u)},{name:"button_right_back",a:30,b:30,c:30,point:new S.Vector3(u,-u,u)},{name:"top_back_left",a:30,b:30,c:30,point:new S.Vector3(-u,u,-u)},{name:"button_back_left",a:30,b:30,c:30,point:new S.Vector3(-u,-u,-u)},{name:"top_left_front",a:30,b:30,c:30,point:new S.Vector3(u,u,-u)},{name:"button_left_front",a:30,b:30,c:30,point:new S.Vector3(u,-u,-u)}],w=[{name:"top_front",a:30,b:30,c:75,point:new S.Vector3(u,u,0)},{name:"top_right",a:75,b:30,c:30,point:new S.Vector3(0,u,u)},{name:"top_back",a:30,b:30,c:75,point:new S.Vector3(-u,u,0)},{name:"top_left",a:75,b:30,c:30,point:new S.Vector3(0,u,-u)},{name:"button_front",a:30,b:30,c:75,point:new S.Vector3(u,-u,0)},{name:"button_right",a:75,b:30,c:30,point:new S.Vector3(0,-u,u)},{name:"button_back",a:30,b:30,c:75,point:new S.Vector3(-u,-u,0)},{name:"button_left",a:75,b:30,c:30,point:new S.Vector3(0,-u,-u)},{name:"front_right",a:30,b:75,c:30,point:new S.Vector3(u,0,u)},{name:"right_back",a:30,b:75,c:30,point:new S.Vector3(-u,0,u)},{name:"back_left",a:30,b:75,c:30,point:new S.Vector3(-u,0,-u)},{name:"left_front",a:30,b:75,c:30,point:new S.Vector3(u,0,-u)}],x=0;x<g.length;x++)a.push(p(g[x]));for(var x=0;x<y.length;x++)a.push(p(y[x]));for(var x=0;x<w.length;x++)a.push(p(w[x]))}function p(f){const u=new S.BoxGeometry(f.a,f.b,f.c),g=new S.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.01}),y=new S.Matrix4().makeTranslation(f.point.x,f.point.y,f.point.z);let w=u.applyMatrix4(y),x=new S.Mesh(w,g);return x.name=f.name,n.sceneOrtho.add(x),x}return n.ToggleCameraType=function(){o.cameraModule.switchCurrentCamera()},n.TakeScreenshot=function(){try{if(!o.renderer){console.error("渲染器未初始化");return}o.renderer.render(e,e.camera);const u=o.renderer.domElement.toDataURL("image/png"),g=document.createElement("a"),y=new Date().toISOString().replaceAll(/[:.]/g,"-");g.download=`screenshot_${y}.png`,g.href=u,g.click(),console.log("截图已保存")}catch(f){console.error("截图失败:",f)}},n.ToggleFullscreen=function(){const f=t||document.documentElement;!document.fullscreenElement&&!document.webkitFullscreenElement&&!document.mozFullScreenElement&&!document.msFullscreenElement?(f.requestFullscreen?f.requestFullscreen():f.webkitRequestFullscreen?f.webkitRequestFullscreen():f.mozRequestFullScreen?f.mozRequestFullScreen():f.msRequestFullscreen&&f.msRequestFullscreen(),console.log("已进入全屏模式")):(document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen(),console.log("已退出全屏模式"))},n}class th{engine;cubeTool;constructor(e){this.engine=e}init(){this.cubeTool=eh(this.engine,this.engine.scene,this.engine.container),this.cubeTool.init()}CameraGoHome(){this.cubeTool.CameraGoHome()}zoomToModel(e){this.cubeTool.zoomToBox(e)}hide(){}}function nh(o){let e=new Object;return e.getBoundingBox=function(){let t=o.models,n=new S.Vector3(1e8,1e9,1e10),i=new S.Vector3(-1e8,-1e9,-1e10);t.forEach(d=>{let m=d.boundingBox.min,p=d.boundingBox.max;m.x<n.x&&(n.x=m.x),m.y<n.y&&(n.y=m.y),m.z<n.z&&(n.z=m.z),p.x>i.x&&(i.x=p.x),p.y>i.y&&(i.y=p.y),p.z>i.z&&(i.z=p.z)});let s=Math.min(n.x,i.x),r=Math.min(n.y,i.y),a=Math.min(n.z,i.z),l=Math.max(n.x,i.x),h=Math.max(n.y,i.y),c=Math.max(n.z,i.z);return{min:new S.Vector3(s,r,a),max:new S.Vector3(l,h,c)}},e.rayInterationModel=function(t){let n=[];return o.engineStatus.models.forEach(r=>{r.info.lods.forEach(a=>{let l=a.octreeBox;s(t,l,r)})}),n=n.filter(r=>r instanceof S.Mesh),t.intersectObjects(n,!1);function s(r,a,l){if(a==null)return;let h=new S.Vector3(a.min.X*.3048,a.min.Z*.3048,-a.min.Y*.3048),c=new S.Vector3(a.max.X*.3048,a.max.Z*.3048,-a.max.Y*.3048),d=new S.Vector3(Math.min(h.x,c.X),Math.min(h.y,c.y),Math.min(h.z,c.z)),m=new S.Vector3(Math.max(c.x,h.x),Math.max(c.y,h.y),Math.max(c.z,h.z)),p=new S.Box3(d,m),f=r.ray.intersectsBox(p);if(!(f==null||f==!1))if(a.children==null||a.children.length==0){if(a.elements!=null)for(var u of a.elements){let g=o.engineStatus.hideModels.find(v=>v.url==l.url)?.ids;if(g!=null&&g.includes(u))continue;let y=o.engineStatus.translucentModels.find(v=>v.url==l.url)?.ids;if(y!=null&&y.includes(u))continue;let x=o.models.find(v=>v.url==l.url).nodesMap.get(u);x!=null&&!x.instance&&x.infos.map(b=>b.mesh).forEach(b=>{n.push(b)})}}else{if(a.elements!=null)for(var u of a.elements){let y=o.engineStatus.hideModels.find(b=>b.url==l.url)?.ids;if(y!=null&&y.includes(u))continue;let w=o.engineStatus.translucentModels.find(b=>b.url==l.url)?.ids;if(w!=null&&w.includes(u))continue;let v=o.models.find(b=>b.url==l.url).nodesMap.get(u);v!=null&&!v.instance&&v.infos.map(D=>D.mesh).forEach(D=>{n.push(D)})}for(let g of a.children)s(r,g,l)}}},e}class ih{engine;isDrawing=!1;startPoint=new S.Vector2;endPoint=new S.Vector2;selectionBox=null;worldToScreen=null;boundMouseDown;boundMouseMove;boundMouseUp;boundKeyDown;constructor(e){this.engine=e,this.boundMouseDown=this.onMouseDown.bind(this),this.boundMouseMove=this.onMouseMove.bind(this),this.boundMouseUp=this.onMouseUp.bind(this),this.boundKeyDown=this.onKeyDown.bind(this)}init(){this.createSelectionBoxElement(),this.engine.scene&&this.engine.camera&&this.engine.renderer&&(this.worldToScreen=new ze(this.engine.camera,this.engine.renderer,this.engine.scene))}active(){this.engine.controlModule.disActive();const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.boundMouseDown),e.addEventListener("mousemove",this.boundMouseMove),e.addEventListener("mouseup",this.boundMouseUp),e.style.cursor="crosshair"),window.addEventListener("keydown",this.boundKeyDown)}disActive(){this.engine.controlModule.active();const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.boundMouseDown),e.removeEventListener("mousemove",this.boundMouseMove),e.removeEventListener("mouseup",this.boundMouseUp),e.style.cursor="default"),window.removeEventListener("keydown",this.boundKeyDown),this.isDrawing&&this.endDrawing()}createSelectionBoxElement(){this.selectionBox=document.createElement("div"),this.selectionBox.style.position="absolute",this.selectionBox.style.border="2px dashed #00aaff",this.selectionBox.style.backgroundColor="rgba(0, 170, 255, 0.1)",this.selectionBox.style.pointerEvents="none",this.selectionBox.style.display="none",this.selectionBox.style.zIndex="1000",this.selectionBox.style.boxSizing="border-box";const e=this.engine.renderer?.domElement;e&&e.parentElement&&e.parentElement.appendChild(this.selectionBox)}onMouseDown(e){e.button!==0||!this.engine.renderer?.domElement||(this.startPoint.set(e.offsetX,e.offsetY),this.endPoint.copy(this.startPoint),this.isDrawing=!0,this.selectionBox&&(this.selectionBox.style.display="block",this.updateSelectionBoxUI()),e.preventDefault(),e.stopPropagation())}onMouseMove(e){!this.isDrawing||!this.engine.renderer?.domElement||(this.endPoint.set(e.offsetX,e.offsetY),this.updateSelectionBoxUI(),e.preventDefault(),e.stopPropagation())}onMouseUp(e){this.isDrawing&&(this.endDrawing(),this.performZoom(),e.preventDefault(),e.stopPropagation(),this.disActive())}onKeyDown(e){e.key==="Escape"&&(this.disActive(),e.preventDefault(),e.stopPropagation())}endDrawing(){this.isDrawing&&(this.isDrawing=!1,this.selectionBox&&(this.selectionBox.style.display="none"))}updateSelectionBoxUI(){if(!this.selectionBox||!this.engine.renderer?.domElement)return;const t=Math.min(this.startPoint.x,this.endPoint.x),n=Math.min(this.startPoint.y,this.endPoint.y),i=Math.abs(this.endPoint.x-this.startPoint.x),s=Math.abs(this.endPoint.y-this.startPoint.y);this.selectionBox.style.left=`${t}px`,this.selectionBox.style.top=`${n}px`,this.selectionBox.style.width=`${i}px`,this.selectionBox.style.height=`${s}px`}performZoom(){const e=Math.abs(this.endPoint.x-this.startPoint.x),t=Math.abs(this.endPoint.y-this.startPoint.y);if(e<5||t<5)return;if(!this.worldToScreen){console.warn("RangeScale: 坐标转换工具未初始化");return}const n=Math.min(this.startPoint.x,this.endPoint.x),i=Math.max(this.startPoint.x,this.endPoint.x),s=Math.min(this.startPoint.y,this.endPoint.y),r=Math.max(this.startPoint.y,this.endPoint.y),a=[],l=[{x:n,y:s},{x:i,y:s},{x:i,y:r},{x:n,y:r}];for(const c of l){const d=this.worldToScreen.screenToWorld(c.x,c.y);d&&a.push(d)}if(a.length<3){console.warn("RangeScale: 框选区域未命中模型,无法执行缩放操作");return}if(a.length<3){console.warn("RangeScale: 无法将屏幕区域转换为世界坐标");return}const h=new S.Box3;for(const c of a)h.expandByPoint(c);if(h.isEmpty()){console.warn("RangeScale: 计算得到的包围盒无效");return}this.fitCameraToBoundingBox(h)}fitCameraToBoundingBox(e){const t=this.engine.camera,n=this.engine.controls;if(!t||!n){console.warn("RangeScale: 相机或控制器未初始化");return}const i=new S.Vector3;e.getCenter(i);const s=new S.Vector3;e.getSize(s);const r=Math.max(s.x,s.y,s.z);if(t instanceof S.PerspectiveCamera){const a=t.fov*(Math.PI/180),h=r/(2*Math.tan(a/2))*1.2,c=new S.Vector3;t.getWorldDirection(c);const d=i.clone().sub(t.position);c.dot(d.normalize())<0&&c.negate();const p=i.clone().sub(c.multiplyScalar(h));t.position.copy(p),n.target&&n.target.copy(i),t.lookAt(i),n.update()}else if(t instanceof S.OrthographicCamera){const l=r*1.2,h=this.engine.renderer?.domElement,c=h?h.width/h.height:1;t.left=-l*c/2,t.right=l*c/2,t.top=l/2,t.bottom=-l/2,t.updateProjectionMatrix();const d=new S.Vector3;t.getWorldDirection(d);const m=r*1.5,p=i.clone().sub(d.multiplyScalar(m));t.position.copy(p),n.target&&n.target.copy(i),t.lookAt(i),n.update()}}}class sh{engine;ground=null;constructor(e){this.engine=e}init(){}setStatsVisible(e){this.engine.stats?.dom&&(this.engine.stats.dom.style.display=e?"block":"none")}setAmbientLightIntensity(e){const t=this.engine.scene.children.find(n=>n instanceof S.AmbientLight);t&&(t.intensity=e)}setAmbientLightColor(e){const t=this.engine.scene.children.find(n=>n instanceof S.AmbientLight);t&&t.color.set(e)}setDirectionalLightIntensity(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);t&&(t.intensity=e)}setDirectionalLightColor(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);t&&t.color.set(e)}setShadowQuality(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);if(t?.shadow){const i={low:1024,medium:2048,high:4096,ultra:8192}[e];t.shadow.mapSize.width=i,t.shadow.mapSize.height=i,t.shadow.map?.dispose(),t.shadow.map=null}}setDirectionalLightShadow(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);t&&(t.castShadow=e),this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e)}setGTAOEnabled(e){if(!this.engine.composerModule?.composer){console.warn("Composer not initialized");return}const t=this.engine.composerModule.composer,n=t.passes.find(i=>i instanceof Ne);if(e)if(n)n.enabled=!0;else{const{width:i,height:s}=this.engine.deviceModule.getContainerSize(),r=new Ne(this.engine.scene,this.engine.camera,i,s);r.output=Ne.OUTPUT.Default,r.blendIntensity=.5,r.updateGtaoMaterial&&r.updateGtaoMaterial({radius:1,distanceExponent:1,thickness:1,scale:1,distanceFallOff:1,screenSpaceRadius:!0});const a=t.passes.findIndex(l=>l.constructor.name==="RenderPass");t.passes.splice(a+1,0,r)}else n&&(n.enabled=!1)}setSceneSaturation(e){if(!this.engine.composerModule?.saturationPass){console.warn("Saturation pass not initialized");return}this.engine.composerModule.saturationPass.uniforms.saturation.value=e}setSceneContrast(e){if(!this.engine.composerModule?.saturationPass){console.warn("Saturation pass not initialized");return}this.engine.composerModule.saturationPass.uniforms.contrast.value=e}setGroundEnabled(e,t){if(e)if(this.ground)this.ground.visible=!0;else{const n=t?.size??100,i=t?.color??8421504,s=t?.opacity??.3,r=new S.PlaneGeometry(n,n),a=new S.MeshStandardMaterial({color:i,transparent:!0,opacity:s,side:S.DoubleSide});this.ground=new S.Mesh(r,a),this.ground.rotation.x=-Math.PI/2,this.ground.position.y=0,this.ground.receiveShadow=!0,this.ground.name="ground",this.engine.scene.add(this.ground)}else this.ground&&(this.ground.visible=!1)}setHDRBackground(e){e?(this.engine.scene.background=e,this.engine.scene.environment=e):(this.engine.scene.background=null,this.engine.scene.environment=null)}}function it(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(o){var e=Math.random()*16|0,t=o=="x"?e:e&3|8;return t.toString(16)})}class st{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Ci(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let n=this.setting.unit,i=n;return t==1?n=="mm"?e=e*1e3:n=="cm"?e=e*100:n=="dm"?e=e*10:n=="m"?e=e*1:n=="km"&&(e=e*.001):t==2&&(n=="mm"?e=e*1e3*1e3:n=="cm"?e=e*100*100:n=="dm"?e=e*10*10:n=="m"?e=e*1*1:n=="km"&&(e=e*.001*.001),i=i+"²"),e.toFixed(this.setting.precision)+" "+i}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight==!0&&(n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let i=e[t][n];i.isSelect==!0&&(i.container.remove(),e[t].splice(n,1))}this.engine.measure.clearAllPoints()}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let i=e[t][n];i.highlight==!0&&(i.container.remove(),e[t].splice(n,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(f=>{p(f)}),this.engine.measure.annotationData.elevationAnnotation.forEach(f=>{m(f)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(f=>{d(f)}),this.engine.measure.annotationData.angleAnnotation.forEach(f=>{l(f)}),this.engine.measure.annotationData.areaAnnotation.forEach(f=>{h(f)}),this.engine.measure.annotationData.slopeAnnotation.forEach(f=>{c(f)});function l(f){if(f.container==null){let T=['<svg class="measureSvg">','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+f.text+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="angle-annotation",f.container.id=f.id,f.container.style.pointerEvents="none",f.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point1),g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point2),y=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point3),w=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;u.x+=w,u.y+=x,g.x+=w,g.y+=x,y.x+=w,y.y+=x;let v=f.container;v.getElementsByTagName("circle")[0].setAttribute("cx",u.x),v.getElementsByTagName("circle")[0].setAttribute("cy",u.y),v.getElementsByTagName("circle")[1].setAttribute("cx",g.x),v.getElementsByTagName("circle")[1].setAttribute("cy",g.y),v.getElementsByTagName("circle")[2].setAttribute("cx",y.x),v.getElementsByTagName("circle")[2].setAttribute("cy",y.y),v.getElementsByTagName("polyline")[0].setAttribute("points",u.x+","+u.y+" "+g.x+","+g.y),v.getElementsByTagName("polyline")[1].setAttribute("points",g.x+","+g.y+" "+y.x+","+y.y);let b=g.x,D=g.y-30;v.getElementsByTagName("rect")[0].setAttribute("x",b-40),v.getElementsByTagName("rect")[0].setAttribute("y",D-12.5),v.getElementsByTagName("text")[0].setAttribute("x",b),v.getElementsByTagName("text")[0].setAttribute("y",D+4),v.getElementsByTagName("text")[0].innerHTML=f.text,v.style.top="0px",v.style.left="0px"}function h(f){if(f.container==null){let k=['<svg class="measureSvg">','<polygon fill="rgba(255, 165, 0, 0.3)" stroke="orange" stroke-width="2" points="" style="opacity: 0.3;"/>','<polyline stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+e.getMeasureText(f.text,2)+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="area-annotation",f.container.id=f.id,f.container.innerHTML=k,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}if(!f.points||f.points.length<3)return;let u=e.engine.reactBoundingClientRect.left,g=e.engine.reactBoundingClientRect.top,y=[],w=0,x=0;for(let k=0;k<f.points.length;k++){let P=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.points[k]);P.x+=u,P.y+=g,y.push(P),w+=P.x,x+=P.y}w=w/y.length,x=x/y.length;let v=y.map(k=>k.x+","+k.y).join(" "),b=f.container;b.getElementsByTagName("polygon")[0].setAttribute("points",v),b.getElementsByTagName("polyline")[0].setAttribute("points",v);let D=w,T=x;b.getElementsByTagName("rect")[0].setAttribute("x",D-40),b.getElementsByTagName("rect")[0].setAttribute("y",T-12.5),b.getElementsByTagName("text")[0].setAttribute("x",D),b.getElementsByTagName("text")[0].setAttribute("y",T+4),b.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(f.text,2),b.style.top="0px",b.style.left="0px"}function c(f){if(f.container==null){let D=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+f.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path d="M0,0 L0,6 L9,3 z" fill="orange" stroke="orange" />',"</marker>","</defs>",'<polyline stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+f.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+f.text+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="slope-annotation",f.container.id=f.id,f.container.innerHTML=D,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point1),g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point2),y=e.engine.reactBoundingClientRect.left,w=e.engine.reactBoundingClientRect.top;u.x+=y,u.y+=w,g.x+=y,g.y+=w;let x=f.container;x.getElementsByTagName("polyline")[0].setAttribute("points",u.x+","+u.y+" "+g.x+","+g.y);let v=(u.x+g.x)/2,b=(u.y+g.y)/2-30;x.getElementsByTagName("rect")[0].setAttribute("x",v-50),x.getElementsByTagName("rect")[0].setAttribute("y",b-12.5),x.getElementsByTagName("text")[0].setAttribute("x",v),x.getElementsByTagName("text")[0].setAttribute("y",b+4),x.getElementsByTagName("text")[0].innerHTML=f.text,x.style.top="0px",x.style.left="0px"}function d(f){if(f.container==null){let T=['<svg class="measureSvg">','<circle cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="40" y="-11" text-anchor="middle" class="measureLabel">X: '+e.getMeasureText(f.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="40" y="25" text-anchor="middle" class="measureLabel">Y: '+e.getMeasureText(-f.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="40" y="51" text-anchor="middle" class="measureLabel">Z: '+e.getMeasureText(f.textY,1)+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="coordinate-annotation",f.container.id=f.id,f.container.style.position="absolute",f.container.style.pointerEvents="none",f.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=f.container,g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point),y=e.engine.reactBoundingClientRect.left,w=e.engine.reactBoundingClientRect.top;g.x+=y,g.y+=w,u.style.top="0px",u.style.left="0px";let x=u.getElementsByTagName("circle")[0];x&&(x.setAttribute("cx",g.x),x.setAttribute("cy",g.y));let v=u.getElementsByTagName("rect"),b=u.getElementsByTagName("text"),D=-55;v[0]&&(v[0].setAttribute("x",g.x+10),v[0].setAttribute("y",g.y+10+D)),b[0]&&(b[0].setAttribute("x",g.x+10+40),b[0].setAttribute("y",g.y+10+16+D)),v[1]&&(v[1].setAttribute("x",g.x+10),v[1].setAttribute("y",g.y+10+30+D)),b[1]&&(b[1].setAttribute("x",g.x+10+40),b[1].setAttribute("y",g.y+10+46+D)),v[2]&&(v[2].setAttribute("x",g.x+10),v[2].setAttribute("y",g.y+10+60+D)),b[2]&&(b[2].setAttribute("x",g.x+10+40),b[2].setAttribute("y",g.y+10+76+D)),b[0]&&(b[0].innerHTML="X: "+e.getMeasureText(f.textX,1)),b[1]&&(b[1].innerHTML="Y: "+e.getMeasureText(-f.textZ,1)),b[2]&&(b[2].innerHTML="Z: "+e.getMeasureText(f.textY,1))}function m(f){if(f.container==null){let x=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+e.getMeasureText(f.text,1)+"</text>",'<polyline stroke="#f99d0b" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");f.container=document.createElement("div"),f.container.className="elevation-annotation",f.container.id=f.id,f.container.style.position="absolute",f.container.style.pointerEvents="none",f.container.innerHTML=x,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=f.container,g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point),y=e.engine.reactBoundingClientRect.left,w=e.engine.reactBoundingClientRect.top;u.style.top=g.y+w-48+"px",u.style.left=g.x+y-16+"px",u.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(f.text,1)}function p(f){if(f.container==null){let v=['<svg class="measureSvg">','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+e.getMeasureText(f.text,1)+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="normal-annotation",f.container.id=f.id,f.container.innerHTML=v,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=f.container;if(f.point1==null||f.point2==null){u.style.display="none";return}else u.style.display="block";let g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point1),y=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point2),w=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;g.x+=w,g.y+=x,y.x+=w,y.y+=x,u.getElementsByTagName("polyline")[0].setAttribute("points",g.x+","+g.y+" "+y.x+","+y.y),u.getElementsByTagName("circle")[0].setAttribute("cx",g.x),u.getElementsByTagName("circle")[0].setAttribute("cy",g.y),u.getElementsByTagName("circle")[1].setAttribute("cx",y.x),u.getElementsByTagName("circle")[1].setAttribute("cy",y.y),u.getElementsByTagName("rect")[0].setAttribute("x",g.x*.5+y.x*.5-40),u.getElementsByTagName("rect")[0].setAttribute("y",g.y*.5+y.y*.5-12.5),u.getElementsByTagName("text")[0].setAttribute("x",g.x*.5+y.x*.5+40-40),u.getElementsByTagName("text")[0].setAttribute("y",g.y*.5+y.y*.5+16-12.5),u.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(f.text,1),u.style.top="0px",u.style.left="0px"}}}class rh{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let i=0;i<e.length;i++){const s=e[i];if(!s)continue;typeof s.updateMatrixWorld=="function"&&s.updateMatrixWorld(!0);const r=new S.Box3().setFromObject(s);!Number.isFinite(r.min.y)||!Number.isFinite(r.max.y)||(r.min.y<t&&(t=r.min.y),r.max.y>n&&(n=r.max.y))}return!Number.isFinite(t)||!Number.isFinite(n)?null:{minY:t,maxY:n}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let s=this.engine.interactionModule.getCatchMeshs(e);var n=this.getMeshesMinMaxY(s);this.catchDir==0?t.set(t.x,n?.minY,t.z):t.set(t.x,n?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.points.push(t);return}let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);i!=null&&(i.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);t==null&&(t={text:null,id:it(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=e.catch;if(this.type=="element"){let i=e.catch.point.clone();i.set(i.x,this.points[0].y,i.z);let s=new S.Raycaster(i.add(new S.Vector3(0,.01,0)),new S.Vector3(0,this.catchDir==0?-1:1,0));n.point=this.points[0];const r=this.engine.octreeBox.rayInterationModel(s);if(r.length===0){t.point2=null;return}t.point1=i,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(_e.MeasureChanged,t)}else{let i=new S.Raycaster(e.catch.point.clone().add(new S.Vector3(0,.01,0)),new S.Vector3(0,this.catchDir==0?-1:1,0));const s=this.engine.octreeBox.rayInterationModel(i);if(s.length===0){t.point2=null;return}t.point1=n.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(_e.MeasureChanged,t)}}}class oh{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);if(n==null)return;n.point2=t.point,n.isSelect=!1,this.points=[],this.engine.events.trigger(_e.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);n==null&&(n={id:it(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(n)),n.point2=t.point,n.text=n.point1.clone().distanceTo(n.point2.clone())}}}class ah{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);t==null&&(t={text:null,id:it(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=new S.Raycaster(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const i=this.engine.octreeBox.rayInterationModel(n);if(i.length==0){t.point2=null;return}let s=e.catch;t.point1=s.point,t.point2=i[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(_e.MeasureChanged,t)}}class lh{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active(),this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:it(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),t.point=e.catch.point.clone(),t.text=e.catch.point.y}handleMouseClick(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(_e.MeasureChanged,t))}}class ch{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active(),this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:it(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t)),t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,console.log("有在移动")}handleMouseClick(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,this.engine.events.trigger(_e.MeasureChanged,t))}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(_e.MeasureChanged,e))}}class hh{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,n){const i=new S.Vector3().subVectors(e,t),s=new S.Vector3().subVectors(n,t),r=i.length(),a=s.length();if(r===0||a===0)return 0;const h=i.dot(s)/(r*a),c=Math.max(-1,Math.min(1,h));return Math.acos(c)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);if(n==null)return;n.point3=t.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",n.isSelect=!1,n.type="angle",this.points=[],this.engine.events.trigger(_e.MeasureChanged,n)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:it(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}}class uh{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;let t=0;const n=e.length;for(let i=0;i<n;i++){const s=(i+1)%n;t+=e[i].x*e[s].z,t-=e[s].x*e[i].z}return t=Math.abs(t)/2,t}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.push(t.point.clone()),this.points.length>=3){let n=this.engine.measure.annotationData.areaAnnotation.find(i=>i.isSelect==!0);n==null?(n={id:it(),points:this.points.map(i=>i.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n)):(this.points.push(t.point.clone()),n.points=this.points.map(i=>i.clone())),n.area=this.calculateArea(n.points),n.text=n.area,console.log("面积",n.text)}}handleMouseMove(e){if(e.catch!=null&&this.points.length>=2){let t=this.engine.measure.annotationData.areaAnnotation.find(n=>n.isSelect==!0);if(t==null){if(this.points.length>=2){let n=this.points.map(i=>i.clone());n.push(e.catch.point.clone()),n.length>=3&&(t={id:it(),points:n,area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t))}}else if(t.points.length>0){const n=t.points.length-1;t.points[n]=e.catch.point.clone()}else t.points=this.points.map(n=>n.clone()),t.points.push(e.catch.point.clone());t&&t.points.length>=3&&(t.area=this.calculateArea(t.points),t.text=t.area)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){this.points=this.points.slice(0,this.points.length-1);let e=this.engine.measure.annotationData.areaAnnotation.find(t=>t.isSelect==!0);e!=null&&e.points.length>=3&&(e.points.length>this.points.length&&(e.points=this.points.map(t=>t.clone())),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(_e.MeasureChanged,e))}}class dh{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const n=t.y-e.y,i=t.x-e.x,s=t.z-e.z,r=Math.sqrt(i*i+s*s);if(r===0)return{percentage:0,angle:0,heightDiff:n,horizontalDist:0,type:"slope"};const a=n/r*100,h=Math.atan(n/r)*(180/Math.PI);return{percentage:a,angle:h,heightDiff:n,horizontalDist:r,type:"slope"}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);if(n==null)return;console.log("进来了"),n.point2=t.point.clone();const i=this.calculateSlope(n.point1,n.point2);n.slopePercentage=i.percentage,n.slopeAngle=i.angle,n.heightDiff=i.heightDiff,n.horizontalDist=i.horizontalDist,n.text=i.percentage.toFixed(2)+"% ("+i.angle.toFixed(2)+"°)",n.isSelect=!1,this.points=[],this.engine.events.trigger(_e.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);n==null&&(n={id:it(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00% (0.00°)",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(n)),n.point2=t.point.clone();const i=this.calculateSlope(n.point1,n.point2);n.slopePercentage=i.percentage,n.slopeAngle=i.angle,n.heightDiff=i.heightDiff,n.horizontalDist=i.horizontalDist,n.text=i.percentage.toFixed(2)+"% ("+i.angle.toFixed(2)+"°)"}}}class fh{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new rh(e),this.distanceMeasure=new oh(e),this.clearDistanceMeasure=new ah(e),this.elevationMeasure=new lh(e),this.pointMeasure=new ch(e),this.angleMeasure=new hh(e),this.areaMeasure=new uh(e),this.slopeMeasure=new dh(e),this.tools=new st(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let n=0;n<t.length;n++)t[n].container.remove();t=[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}}const Gr=0,ph=1,mh=2,Wr=2,Ki=1.25,Xr=1,Ie=32,Me=Ie/4,Zr=65535,gh=Math.pow(2,-24),Yi=Symbol("SKIP_GENERATION");function yh(o){return o.index?o.index.count:o.attributes.position.count}function Dt(o){return yh(o)/3}function wh(o,e=ArrayBuffer){return o>65535?new Uint32Array(new e(4*o)):new Uint16Array(new e(2*o))}function xh(o,e){if(!o.index){const t=o.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=wh(t,n);o.setIndex(new _.BufferAttribute(i,1));for(let s=0;s<t;s++)i[s]=s}}function qr(o,e){const t=Dt(o),n=e||o.drawRange,i=n.start/3,s=(n.start+n.count)/3,r=Math.max(0,i),a=Math.min(t,s)-r;return[{offset:Math.floor(r),count:Math.floor(a)}]}function Kr(o,e){if(!o.groups||!o.groups.length)return qr(o,e);const t=[],n=e||o.drawRange,i=n.start/3,s=(n.start+n.count)/3,r=Dt(o),a=[];for(const c of o.groups){const{start:d,count:m}=c,p=d/3,f=isFinite(m)?m:r*3-d,u=(d+f)/3;p<s&&u>i&&(a.push({pos:Math.max(i,p),isStart:!0}),a.push({pos:Math.min(s,u),isStart:!1}))}a.sort((c,d)=>c.pos!==d.pos?c.pos-d.pos:c.type==="end"?-1:1);let l=0,h=null;for(const c of a){const d=c.pos;l!==0&&d!==h&&t.push({offset:h,count:d-h}),l+=c.isStart?1:-1,h=d}return t}function $i(o,e,t,n,i){let s=1/0,r=1/0,a=1/0,l=-1/0,h=-1/0,c=-1/0,d=1/0,m=1/0,p=1/0,f=-1/0,u=-1/0,g=-1/0;const y=o.offset||0;for(let w=(e-y)*6,x=(e+t-y)*6;w<x;w+=6){const v=o[w+0],b=o[w+1],D=v-b,T=v+b;D<s&&(s=D),T>l&&(l=T),v<d&&(d=v),v>f&&(f=v);const k=o[w+2],P=o[w+3],I=k-P,z=k+P;I<r&&(r=I),z>h&&(h=z),k<m&&(m=k),k>u&&(u=k);const C=o[w+4],E=o[w+5],M=C-E,B=C+E;M<a&&(a=M),B>c&&(c=B),C<p&&(p=C),C>g&&(g=C)}n[0]=s,n[1]=r,n[2]=a,n[3]=l,n[4]=h,n[5]=c,i[0]=d,i[1]=m,i[2]=p,i[3]=f,i[4]=u,i[5]=g}function Yr(o,e,t=null,n=null,i=null){const s=o.attributes.position,r=o.index?o.index.array:null,a=s.normalized;if(i===null)i=new Float32Array(t*6),i.offset=e;else if(e<0||t+e>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=s.array,h=s.offset||0;let c=3;s.isInterleavedBufferAttribute&&(c=s.data.stride);const d=["getX","getY","getZ"],m=i.offset;for(let p=e,f=e+t;p<f;p++){const g=(n?n[p]:p)*3,y=(p-m)*6;let w=g+0,x=g+1,v=g+2;r&&(w=r[w],x=r[x],v=r[v]),a||(w=w*c+h,x=x*c+h,v=v*c+h);for(let b=0;b<3;b++){let D,T,k;a?(D=s[d[b]](w),T=s[d[b]](x),k=s[d[b]](v)):(D=l[w+b],T=l[x+b],k=l[v+b]);let P=D;T<P&&(P=T),k<P&&(P=k);let I=D;T>I&&(I=T),k>I&&(I=k);const z=(I-P)/2,C=b*2;i[y+C+0]=P+z,i[y+C+1]=z+(Math.abs(P)+z)*gh}}return i}function we(o,e,t){return t.min.x=e[o],t.min.y=e[o+1],t.min.z=e[o+2],t.max.x=e[o+3],t.max.y=e[o+4],t.max.z=e[o+5],t}function $r(o){let e=-1,t=-1/0;for(let n=0;n<3;n++){const i=o[n+3]-o[n];i>t&&(t=i,e=n)}return e}function Hr(o,e){e.set(o)}function Jr(o,e,t){let n,i;for(let s=0;s<3;s++){const r=s+3;n=o[s],i=e[s],t[s]=n<i?n:i,n=o[r],i=e[r],t[r]=n>i?n:i}}function Yn(o,e,t){for(let n=0;n<3;n++){const i=e[o+2*n],s=e[o+2*n+1],r=i-s,a=i+s;r<t[n]&&(t[n]=r),a>t[n+3]&&(t[n+3]=a)}}function un(o){const e=o[3]-o[0],t=o[4]-o[1],n=o[5]-o[2];return 2*(e*t+t*n+n*e)}const rt=32,vh=(o,e)=>o.candidate-e.candidate,ft=new Array(rt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),$n=new Float32Array(6);function bh(o,e,t,n,i,s){let r=-1,a=0;if(s===Gr)r=$r(e),r!==-1&&(a=(e[r]+e[r+3])/2);else if(s===ph)r=$r(o),r!==-1&&(a=_h(t,n,i,r));else if(s===mh){const l=un(o);let h=Ki*i;const c=t.offset||0,d=(n-c)*6,m=(n+i-c)*6;for(let p=0;p<3;p++){const f=e[p],y=(e[p+3]-f)/rt;if(i<rt/4){const w=[...ft];w.length=i;let x=0;for(let b=d;b<m;b+=6,x++){const D=w[x];D.candidate=t[b+2*p],D.count=0;const{bounds:T,leftCacheBounds:k,rightCacheBounds:P}=D;for(let I=0;I<3;I++)P[I]=1/0,P[I+3]=-1/0,k[I]=1/0,k[I+3]=-1/0,T[I]=1/0,T[I+3]=-1/0;Yn(b,t,T)}w.sort(vh);let v=i;for(let b=0;b<v;b++){const D=w[b];for(;b+1<v&&w[b+1].candidate===D.candidate;)w.splice(b+1,1),v--}for(let b=d;b<m;b+=6){const D=t[b+2*p];for(let T=0;T<v;T++){const k=w[T];D>=k.candidate?Yn(b,t,k.rightCacheBounds):(Yn(b,t,k.leftCacheBounds),k.count++)}}for(let b=0;b<v;b++){const D=w[b],T=D.count,k=i-D.count,P=D.leftCacheBounds,I=D.rightCacheBounds;let z=0;T!==0&&(z=un(P)/l);let C=0;k!==0&&(C=un(I)/l);const E=Xr+Ki*(z*T+C*k);E<h&&(r=p,h=E,a=D.candidate)}}else{for(let v=0;v<rt;v++){const b=ft[v];b.count=0,b.candidate=f+y+v*y;const D=b.bounds;for(let T=0;T<3;T++)D[T]=1/0,D[T+3]=-1/0}for(let v=d;v<m;v+=6){let T=~~((t[v+2*p]-f)/y);T>=rt&&(T=rt-1);const k=ft[T];k.count++,Yn(v,t,k.bounds)}const w=ft[rt-1];Hr(w.bounds,w.rightCacheBounds);for(let v=rt-2;v>=0;v--){const b=ft[v],D=ft[v+1];Jr(b.bounds,D.rightCacheBounds,b.rightCacheBounds)}let x=0;for(let v=0;v<rt-1;v++){const b=ft[v],D=b.count,T=b.bounds,P=ft[v+1].rightCacheBounds;D!==0&&(x===0?Hr(T,$n):Jr(T,$n,$n)),x+=D;let I=0,z=0;x!==0&&(I=un($n)/l);const C=i-x;C!==0&&(z=un(P)/l);const E=Xr+Ki*(I*x+z*C);E<h&&(r=p,h=E,a=b.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function _h(o,e,t,n){let i=0;const s=o.offset;for(let r=e,a=e+t;r<a;r++)i+=o[(r-s)*6+n*2];return i/t}class Hi{constructor(){this.boundingData=new Float32Array(6)}}function Mh(o,e,t,n,i,s){let r=n,a=n+i-1;const l=s.pos,h=s.axis*2,c=t.offset||0;for(;;){for(;r<=a&&t[(r-c)*6+h]<l;)r++;for(;r<=a&&t[(a-c)*6+h]>=l;)a--;if(r<a){for(let d=0;d<3;d++){let m=e[r*3+d];e[r*3+d]=e[a*3+d],e[a*3+d]=m}for(let d=0;d<6;d++){const m=r-c,p=a-c,f=t[m*6+d];t[m*6+d]=t[p*6+d],t[p*6+d]=f}r++,a--}else return r}}function Sh(o,e,t,n,i,s){let r=n,a=n+i-1;const l=s.pos,h=s.axis*2,c=t.offset||0;for(;;){for(;r<=a&&t[(r-c)*6+h]<l;)r++;for(;r<=a&&t[(a-c)*6+h]>=l;)a--;if(r<a){let d=o[r];o[r]=o[a],o[a]=d;for(let m=0;m<6;m++){const p=r-c,f=a-c,u=t[p*6+m];t[p*6+m]=t[f*6+m],t[f*6+m]=u}r++,a--}else return r}}let Qr,Hn,Ji,eo;const Ah=Math.pow(2,32);function Qi(o){return"count"in o?1:1+Qi(o.left)+Qi(o.right)}function Ch(o,e,t){return Qr=new Float32Array(t),Hn=new Uint32Array(t),Ji=new Uint16Array(t),eo=new Uint8Array(t),es(o,e)}function es(o,e){const t=o/4,n=o/2,i="count"in e,s=e.boundingData;for(let r=0;r<6;r++)Qr[t+r]=s[r];if(i)return e.buffer?(eo.set(new Uint8Array(e.buffer),o),o+e.buffer.byteLength):(Hn[t+6]=e.offset,Ji[n+14]=e.count,Ji[n+15]=Zr,o+Ie);{const{left:r,right:a,splitAxis:l}=e,h=o+Ie;let c=es(h,r);const d=o/Ie,p=c/Ie-d;if(p>Ah)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Hn[t+6]=p,Hn[t+7]=l,es(c,a)}}function Th(o,e,t){const i=(o.index?o.index.count:o.attributes.position.count)/3>2**16,s=t.reduce((c,d)=>c+d.count,0),r=i?4:2,a=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),l=i?new Uint32Array(a):new Uint16Array(a);let h=0;for(let c=0;c<t.length;c++){const{offset:d,count:m}=t[c];for(let p=0;p<m;p++)l[h+p]=d+p;h+=m}return l}function Ph(o,e,t,n,i){const{maxDepth:s,verbose:r,maxLeafTris:a,strategy:l,onProgress:h,indirect:c}=i,d=o._indirectBuffer,m=o.geometry,p=m.index?m.index.array:null,f=c?Sh:Mh,u=Dt(m),g=new Float32Array(6);let y=!1;const w=new Hi;return $i(e,t,n,w.boundingData,g),v(w,t,n,g),w;function x(b){h&&h(b/u)}function v(b,D,T,k=null,P=0){if(!y&&P>=s&&(y=!0,r&&(console.warn(`MeshBVH: Max depth of ${s} reached when generating BVH. Consider increasing maxDepth.`),console.warn(m))),T<=a||P>=s)return x(D+T),b.offset=D,b.count=T,b;const I=bh(b.boundingData,k,e,D,T,l);if(I.axis===-1)return x(D+T),b.offset=D,b.count=T,b;const z=f(d,p,e,D,T,I);if(z===D||z===D+T)x(D+T),b.offset=D,b.count=T;else{b.splitAxis=I.axis;const C=new Hi,E=D,M=z-D;b.left=C,$i(e,E,M,C.boundingData,g),v(C,E,M,g,P+1);const B=new Hi,V=z,U=T-M;b.right=B,$i(e,V,U,B.boundingData,g),v(B,V,U,g,P+1)}return b}}function Dh(o,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=o.geometry;let i,s;if(e.indirect){const r=Kr(n,e.range),a=Th(n,e.useSharedArrayBuffer,r);o._indirectBuffer=a,i=Yr(n,0,a.length,a),s=[{offset:0,count:a.length}]}else{xh(n,e);const r=qr(n,e.range)[0];i=Yr(n,r.offset,r.count),s=Kr(n,e.range)}o._roots=s.map(r=>{const a=Ph(o,i,r.offset,r.count,e),l=Qi(a),h=new t(Ie*l);return Ch(0,a,h),h})}class ot{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,i=-1/0;for(let s=0,r=e.length;s<r;s++){const l=e[s][t];n=l<n?l:n,i=l>i?l:i}this.min=n,this.max=i}setFromPoints(e,t){let n=1/0,i=-1/0;for(let s=0,r=t.length;s<r;s++){const a=t[s],l=e.dot(a);n=l<n?l:n,i=l>i?l:i}this.min=n,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}ot.prototype.setFromBox=(function(){const o=new _.Vector3;return function(t,n){const i=n.min,s=n.max;let r=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let c=0;c<=1;c++){o.x=i.x*l+s.x*(1-l),o.y=i.y*h+s.y*(1-h),o.z=i.z*c+s.z*(1-c);const d=t.dot(o);r=Math.min(d,r),a=Math.max(d,a)}this.min=r,this.max=a}})();const kh=(function(){const o=new _.Vector3,e=new _.Vector3,t=new _.Vector3;return function(i,s,r){const a=i.start,l=o,h=s.start,c=e;t.subVectors(a,h),o.subVectors(i.end,i.start),e.subVectors(s.end,s.start);const d=t.dot(c),m=c.dot(l),p=c.dot(c),f=t.dot(l),g=l.dot(l)*p-m*m;let y,w;g!==0?y=(d*m-f*p)/g:y=0,w=(d+y*m)/p,r.x=y,r.y=w}})(),ts=(function(){const o=new _.Vector2,e=new _.Vector3,t=new _.Vector3;return function(i,s,r,a){kh(i,s,o);let l=o.x,h=o.y;if(l>=0&&l<=1&&h>=0&&h<=1){i.at(l,r),s.at(h,a);return}else if(l>=0&&l<=1){h<0?s.at(0,a):s.at(1,a),i.closestPointToPoint(a,!0,r);return}else if(h>=0&&h<=1){l<0?i.at(0,r):i.at(1,r),s.closestPointToPoint(r,!0,a);return}else{let c;l<0?c=i.start:c=i.end;let d;h<0?d=s.start:d=s.end;const m=e,p=t;if(i.closestPointToPoint(d,!0,e),s.closestPointToPoint(c,!0,t),m.distanceToSquared(d)<=p.distanceToSquared(c)){r.copy(m),a.copy(d);return}else{r.copy(c),a.copy(p);return}}}})(),Ih=(function(){const o=new _.Vector3,e=new _.Vector3,t=new _.Plane,n=new _.Line3;return function(s,r){const{radius:a,center:l}=s,{a:h,b:c,c:d}=r;if(n.start=h,n.end=c,n.closestPointToPoint(l,!0,o).distanceTo(l)<=a||(n.start=h,n.end=d,n.closestPointToPoint(l,!0,o).distanceTo(l)<=a)||(n.start=c,n.end=d,n.closestPointToPoint(l,!0,o).distanceTo(l)<=a))return!0;const u=r.getPlane(t);if(Math.abs(u.distanceToPoint(l))<=a){const y=u.projectPoint(l,e);if(r.containsPoint(y))return!0}return!1}})(),Lh=["x","y","z"],at=1e-15,to=at*at;function je(o){return Math.abs(o)<at}class Ge extends _.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new _.Vector3),this.satBounds=new Array(4).fill().map(()=>new ot),this.points=[this.a,this.b,this.c],this.plane=new _.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new _.Line3,this.needsUpdate=!0}intersectsSphere(e){return Ih(e,this)}update(){const e=this.a,t=this.b,n=this.c,i=this.points,s=this.satAxes,r=this.satBounds,a=s[0],l=r[0];this.getNormal(a),l.setFromPoints(a,i);const h=s[1],c=r[1];h.subVectors(e,t),c.setFromPoints(h,i);const d=s[2],m=r[2];d.subVectors(t,n),m.setFromPoints(d,i);const p=s[3],f=r[3];p.subVectors(n,e),f.setFromPoints(p,i);const u=h.length(),g=d.length(),y=p.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,u<at?g<at||y<at?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):g<at?y<at?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):y<at&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Ge.prototype.closestPointToSegment=(function(){const o=new _.Vector3,e=new _.Vector3,t=new _.Line3;return function(i,s=null,r=null){const{start:a,end:l}=i,h=this.points;let c,d=1/0;for(let m=0;m<3;m++){const p=(m+1)%3;t.start.copy(h[m]),t.end.copy(h[p]),ts(t,i,o,e),c=o.distanceToSquared(e),c<d&&(d=c,s&&s.copy(o),r&&r.copy(e))}return this.closestPointToPoint(a,o),c=a.distanceToSquared(o),c<d&&(d=c,s&&s.copy(o),r&&r.copy(a)),this.closestPointToPoint(l,o),c=l.distanceToSquared(o),c<d&&(d=c,s&&s.copy(o),r&&r.copy(l)),Math.sqrt(d)}})(),Ge.prototype.intersectsTriangle=(function(){const o=new Ge,e=new ot,t=new ot,n=new _.Vector3,i=new _.Vector3,s=new _.Vector3,r=new _.Vector3,a=new _.Line3,l=new _.Line3,h=new _.Vector3,c=new _.Vector2,d=new _.Vector2;function m(x,v,b,D){const T=n;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?T.copy(x.plane.normal):T.copy(v.plane.normal);const k=x.satBounds,P=x.satAxes;for(let C=1;C<4;C++){const E=k[C],M=P[C];if(e.setFromPoints(M,v.points),E.isSeparated(e)||(r.copy(T).cross(M),e.setFromPoints(r,x.points),t.setFromPoints(r,v.points),e.isSeparated(t)))return!1}const I=v.satBounds,z=v.satAxes;for(let C=1;C<4;C++){const E=I[C],M=z[C];if(e.setFromPoints(M,x.points),E.isSeparated(e)||(r.crossVectors(T,M),e.setFromPoints(r,x.points),t.setFromPoints(r,v.points),e.isSeparated(t)))return!1}return b&&(D||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),b.start.set(0,0,0),b.end.set(0,0,0)),!0}function p(x,v,b,D,T,k,P,I,z,C,E){let M=P/(P-I);C.x=D+(T-D)*M,E.start.subVectors(v,x).multiplyScalar(M).add(x),M=P/(P-z),C.y=D+(k-D)*M,E.end.subVectors(b,x).multiplyScalar(M).add(x)}function f(x,v,b,D,T,k,P,I,z,C,E){if(T>0)p(x.c,x.a,x.b,D,v,b,z,P,I,C,E);else if(k>0)p(x.b,x.a,x.c,b,v,D,I,P,z,C,E);else if(I*z>0||P!=0)p(x.a,x.b,x.c,v,b,D,P,I,z,C,E);else if(I!=0)p(x.b,x.a,x.c,b,v,D,I,P,z,C,E);else if(z!=0)p(x.c,x.a,x.b,D,v,b,z,P,I,C,E);else return!0;return!1}function u(x,v,b,D){const T=v.degenerateSegment,k=x.plane.distanceToPoint(T.start),P=x.plane.distanceToPoint(T.end);return je(k)?je(P)?m(x,v,b,D):(b&&(b.start.copy(T.start),b.end.copy(T.start)),x.containsPoint(T.start)):je(P)?(b&&(b.start.copy(T.end),b.end.copy(T.end)),x.containsPoint(T.end)):x.plane.intersectLine(T,n)!=null?(b&&(b.start.copy(n),b.end.copy(n)),x.containsPoint(n)):!1}function g(x,v,b){const D=v.a;return je(x.plane.distanceToPoint(D))&&x.containsPoint(D)?(b&&(b.start.copy(D),b.end.copy(D)),!0):!1}function y(x,v,b){const D=x.degenerateSegment,T=v.a;return D.closestPointToPoint(T,!0,n),T.distanceToSquared(n)<to?(b&&(b.start.copy(T),b.end.copy(T)),!0):!1}function w(x,v,b,D){if(x.isDegenerateIntoSegment)if(v.isDegenerateIntoSegment){const T=x.degenerateSegment,k=v.degenerateSegment,P=i,I=s;T.delta(P),k.delta(I);const z=n.subVectors(k.start,T.start),C=P.x*I.y-P.y*I.x;if(je(C))return!1;const E=(z.x*I.y-z.y*I.x)/C,M=-(P.x*z.y-P.y*z.x)/C;if(E<0||E>1||M<0||M>1)return!1;const B=T.start.z+P.z*E,V=k.start.z+I.z*M;return je(B-V)?(b&&(b.start.copy(T.start).addScaledVector(P,E),b.end.copy(T.start).addScaledVector(P,E)),!0):!1}else return v.isDegenerateIntoPoint?y(x,v,b):u(v,x,b,D);else{if(x.isDegenerateIntoPoint)return v.isDegenerateIntoPoint?v.a.distanceToSquared(x.a)<to?(b&&(b.start.copy(x.a),b.end.copy(x.a)),!0):!1:v.isDegenerateIntoSegment?y(v,x,b):g(v,x,b);if(v.isDegenerateIntoPoint)return g(x,v,b);if(v.isDegenerateIntoSegment)return u(x,v,b,D)}}return function(v,b=null,D=!1){this.needsUpdate&&this.update(),v.isExtendedTriangle?v.needsUpdate&&v.update():(o.copy(v),o.update(),v=o);const T=w(this,v,b,D);if(T!==void 0)return T;const k=this.plane,P=v.plane;let I=P.distanceToPoint(this.a),z=P.distanceToPoint(this.b),C=P.distanceToPoint(this.c);je(I)&&(I=0),je(z)&&(z=0),je(C)&&(C=0);const E=I*z,M=I*C;if(E>0&&M>0)return!1;let B=k.distanceToPoint(v.a),V=k.distanceToPoint(v.b),U=k.distanceToPoint(v.c);je(B)&&(B=0),je(V)&&(V=0),je(U)&&(U=0);const H=B*V,G=B*U;if(H>0&&G>0)return!1;i.copy(k.normal),s.copy(P.normal);const $=i.cross(s);let F=0,N=Math.abs($.x);const te=Math.abs($.y);te>N&&(N=te,F=1),Math.abs($.z)>N&&(F=2);const Y=Lh[F],ce=this.a[Y],fe=this.b[Y],se=this.c[Y],oe=v.a[Y],ue=v.b[Y],pe=v.c[Y];if(f(this,ce,fe,se,E,M,I,z,C,c,a))return m(this,v,b,D);if(f(v,oe,ue,pe,H,G,B,V,U,d,l))return m(this,v,b,D);if(c.y<c.x){const Ae=c.y;c.y=c.x,c.x=Ae,h.copy(a.start),a.start.copy(a.end),a.end.copy(h)}if(d.y<d.x){const Ae=d.y;d.y=d.x,d.x=Ae,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}return c.y<d.x||d.y<c.x?!1:(b&&(d.x>c.x?b.start.copy(l.start):b.start.copy(a.start),d.y<c.y?b.end.copy(l.end):b.end.copy(a.end)),!0)}})(),Ge.prototype.distanceToPoint=(function(){const o=new _.Vector3;return function(t){return this.closestPointToPoint(t,o),t.distanceTo(o)}})(),Ge.prototype.distanceToTriangle=(function(){const o=new _.Vector3,e=new _.Vector3,t=["a","b","c"],n=new _.Line3,i=new _.Line3;return function(r,a=null,l=null){const h=a||l?n:null;if(this.intersectsTriangle(r,h))return(a||l)&&(a&&h.getCenter(a),l&&h.getCenter(l)),0;let c=1/0;for(let d=0;d<3;d++){let m;const p=t[d],f=r[p];this.closestPointToPoint(f,o),m=f.distanceToSquared(o),m<c&&(c=m,a&&a.copy(o),l&&l.copy(f));const u=this[p];r.closestPointToPoint(u,o),m=u.distanceToSquared(o),m<c&&(c=m,a&&a.copy(u),l&&l.copy(o))}for(let d=0;d<3;d++){const m=t[d],p=t[(d+1)%3];n.set(this[m],this[p]);for(let f=0;f<3;f++){const u=t[f],g=t[(f+1)%3];i.set(r[u],r[g]),ts(n,i,o,e);const y=o.distanceToSquared(e);y<c&&(c=y,a&&a.copy(o),l&&l.copy(e))}}return Math.sqrt(c)}})();class Le{constructor(e,t,n){this.isOrientedBox=!0,this.min=new _.Vector3,this.max=new _.Vector3,this.matrix=new _.Matrix4,this.invMatrix=new _.Matrix4,this.points=new Array(8).fill().map(()=>new _.Vector3),this.satAxes=new Array(3).fill().map(()=>new _.Vector3),this.satBounds=new Array(3).fill().map(()=>new ot),this.alignedSatBounds=new Array(3).fill().map(()=>new ot),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Le.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,i=this.points;for(let h=0;h<=1;h++)for(let c=0;c<=1;c++)for(let d=0;d<=1;d++){const m=1*h|2*c|4*d,p=i[m];p.x=h?n.x:t.x,p.y=c?n.y:t.y,p.z=d?n.z:t.z,p.applyMatrix4(e)}const s=this.satBounds,r=this.satAxes,a=i[0];for(let h=0;h<3;h++){const c=r[h],d=s[h],m=1<<h,p=i[m];c.subVectors(a,p),d.setFromPoints(c,i)}const l=this.alignedSatBounds;l[0].setFromPointsField(i,"x"),l[1].setFromPointsField(i,"y"),l[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),Le.prototype.intersectsBox=(function(){const o=new ot;return function(t){this.needsUpdate&&this.update();const n=t.min,i=t.max,s=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(o.min=n.x,o.max=i.x,a[0].isSeparated(o)||(o.min=n.y,o.max=i.y,a[1].isSeparated(o))||(o.min=n.z,o.max=i.z,a[2].isSeparated(o)))return!1;for(let l=0;l<3;l++){const h=r[l],c=s[l];if(o.setFromBox(h,t),c.isSeparated(o))return!1}return!0}})(),Le.prototype.intersectsTriangle=(function(){const o=new Ge,e=new Array(3),t=new ot,n=new ot,i=new _.Vector3;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(o.copy(r),o.update(),r=o);const a=this.satBounds,l=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let m=0;m<3;m++){const p=a[m],f=l[m];if(t.setFromPoints(f,e),p.isSeparated(t))return!1}const h=r.satBounds,c=r.satAxes,d=this.points;for(let m=0;m<3;m++){const p=h[m],f=c[m];if(t.setFromPoints(f,d),p.isSeparated(t))return!1}for(let m=0;m<3;m++){const p=l[m];for(let f=0;f<4;f++){const u=c[f];if(i.crossVectors(p,u),t.setFromPoints(i,e),n.setFromPoints(i,d),t.isSeparated(n))return!1}}return!0}})(),Le.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})(),Le.prototype.distanceToPoint=(function(){const o=new _.Vector3;return function(t){return this.closestPointToPoint(t,o),t.distanceTo(o)}})(),Le.prototype.distanceToBox=(function(){const o=["x","y","z"],e=new Array(12).fill().map(()=>new _.Line3),t=new Array(12).fill().map(()=>new _.Line3),n=new _.Vector3,i=new _.Vector3;return function(r,a=0,l=null,h=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(l||h)&&(r.getCenter(i),this.closestPointToPoint(i,n),r.closestPointToPoint(n,i),l&&l.copy(n),h&&h.copy(i)),0;const c=a*a,d=r.min,m=r.max,p=this.points;let f=1/0;for(let g=0;g<8;g++){const y=p[g];i.copy(y).clamp(d,m);const w=y.distanceToSquared(i);if(w<f&&(f=w,l&&l.copy(y),h&&h.copy(i),w<c))return Math.sqrt(w)}let u=0;for(let g=0;g<3;g++)for(let y=0;y<=1;y++)for(let w=0;w<=1;w++){const x=(g+1)%3,v=(g+2)%3,b=y<<x|w<<v,D=1<<g|y<<x|w<<v,T=p[b],k=p[D];e[u].set(T,k);const I=o[g],z=o[x],C=o[v],E=t[u],M=E.start,B=E.end;M[I]=d[I],M[z]=y?d[z]:m[z],M[C]=w?d[C]:m[z],B[I]=m[I],B[z]=y?d[z]:m[z],B[C]=w?d[C]:m[z],u++}for(let g=0;g<=1;g++)for(let y=0;y<=1;y++)for(let w=0;w<=1;w++){i.x=g?m.x:d.x,i.y=y?m.y:d.y,i.z=w?m.z:d.z,this.closestPointToPoint(i,n);const x=i.distanceToSquared(n);if(x<f&&(f=x,l&&l.copy(n),h&&h.copy(i),x<c))return Math.sqrt(x)}for(let g=0;g<12;g++){const y=e[g];for(let w=0;w<12;w++){const x=t[w];ts(y,x,n,i);const v=n.distanceToSquared(i);if(v<f&&(f=v,l&&l.copy(n),h&&h.copy(i),v<c))return Math.sqrt(v)}}return Math.sqrt(f)}})();class ns{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Eh extends ns{constructor(){super(()=>new Ge)}}const We=new Eh;function Se(o,e){return e[o+15]===Zr}function Ue(o,e){return e[o+6]}function Xe(o,e){return e[o+14]}function Te(o){return o+Me}function Pe(o,e){const t=e[o+6];return o+t*Me}function is(o,e){return e[o+7]}function Qd(o){return o}class Bh{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=n=>{t&&e.push(t),t=n,this.float32Array=new Float32Array(n),this.uint16Array=new Uint16Array(n),this.uint32Array=new Uint32Array(n)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const me=new Bh;let pt,qt;const Kt=[],Jn=new ns(()=>new _.Box3);function Oh(o,e,t,n,i,s){pt=Jn.getPrimitive(),qt=Jn.getPrimitive(),Kt.push(pt,qt),me.setBuffer(o._roots[e]);const r=ss(0,o.geometry,t,n,i,s);me.clearBuffer(),Jn.releasePrimitive(pt),Jn.releasePrimitive(qt),Kt.pop(),Kt.pop();const a=Kt.length;return a>0&&(qt=Kt[a-1],pt=Kt[a-2]),r}function ss(o,e,t,n,i=null,s=0,r=0){const{float32Array:a,uint16Array:l,uint32Array:h}=me;let c=o*2;if(Se(c,l)){const m=Ue(o,h),p=Xe(c,l);return we(o,a,pt),n(m,p,!1,r,s+o/Me,pt)}else{let I=function(C){const{uint16Array:E,uint32Array:M}=me;let B=C*2;for(;!Se(B,E);)C=Te(C),B=C*2;return Ue(C,M)},z=function(C){const{uint16Array:E,uint32Array:M}=me;let B=C*2;for(;!Se(B,E);)C=Pe(C,M),B=C*2;return Ue(C,M)+Xe(B,E)};const m=Te(o),p=Pe(o,h);let f=m,u=p,g,y,w,x;if(i&&(w=pt,x=qt,we(f,a,w),we(u,a,x),g=i(w),y=i(x),y<g)){f=p,u=m;const C=g;g=y,y=C,w=x}w||(w=pt,we(f,a,w));const v=Se(f*2,l),b=t(w,v,g,r+1,s+f/Me);let D;if(b===Wr){const C=I(f),M=z(f)-C;D=n(C,M,!0,r+1,s+f/Me,w)}else D=b&&ss(f,e,t,n,i,s,r+1);if(D)return!0;x=qt,we(u,a,x);const T=Se(u*2,l),k=t(x,T,y,r+1,s+u/Me);let P;if(k===Wr){const C=I(u),M=z(u)-C;P=n(C,M,!0,r+1,s+u/Me,x)}else P=k&&ss(u,e,t,n,i,s,r+1);return!!P}}const dn=new _.Vector3,rs=new _.Vector3;function zh(o,e,t={},n=0,i=1/0){const s=n*n,r=i*i;let a=1/0,l=null;if(o.shapecast({boundsTraverseOrder:c=>(dn.copy(e).clamp(c.min,c.max),dn.distanceToSquared(e)),intersectsBounds:(c,d,m)=>m<a&&m<r,intersectsTriangle:(c,d)=>{c.closestPointToPoint(e,dn);const m=e.distanceToSquared(dn);return m<a&&(rs.copy(dn),a=m,l=d),m<s}}),a===1/0)return null;const h=Math.sqrt(a);return t.point?t.point.copy(rs):t.point=rs.clone(),t.distance=h,t.faceIndex=l,t}const Qn=parseInt(_.REVISION)>=169,Nh=parseInt(_.REVISION)<=161,kt=new _.Vector3,It=new _.Vector3,Lt=new _.Vector3,ei=new _.Vector2,ti=new _.Vector2,ni=new _.Vector2,no=new _.Vector3,io=new _.Vector3,so=new _.Vector3,fn=new _.Vector3;function Rh(o,e,t,n,i,s,r,a){let l;if(s===_.BackSide?l=o.intersectTriangle(n,t,e,!0,i):l=o.intersectTriangle(e,t,n,s!==_.DoubleSide,i),l===null)return null;const h=o.origin.distanceTo(i);return h<r||h>a?null:{distance:h,point:i.clone()}}function ro(o,e,t,n,i,s,r,a,l,h,c){kt.fromBufferAttribute(e,s),It.fromBufferAttribute(e,r),Lt.fromBufferAttribute(e,a);const d=Rh(o,kt,It,Lt,fn,l,h,c);if(d){if(n){ei.fromBufferAttribute(n,s),ti.fromBufferAttribute(n,r),ni.fromBufferAttribute(n,a),d.uv=new _.Vector2;const p=_.Triangle.getInterpolation(fn,kt,It,Lt,ei,ti,ni,d.uv);Qn||(d.uv=p)}if(i){ei.fromBufferAttribute(i,s),ti.fromBufferAttribute(i,r),ni.fromBufferAttribute(i,a),d.uv1=new _.Vector2;const p=_.Triangle.getInterpolation(fn,kt,It,Lt,ei,ti,ni,d.uv1);Qn||(d.uv1=p),Nh&&(d.uv2=d.uv1)}if(t){no.fromBufferAttribute(t,s),io.fromBufferAttribute(t,r),so.fromBufferAttribute(t,a),d.normal=new _.Vector3;const p=_.Triangle.getInterpolation(fn,kt,It,Lt,no,io,so,d.normal);d.normal.dot(o.direction)>0&&d.normal.multiplyScalar(-1),Qn||(d.normal=p)}const m={a:s,b:r,c:a,normal:new _.Vector3,materialIndex:0};if(_.Triangle.getNormal(kt,It,Lt,m.normal),d.face=m,d.faceIndex=s,Qn){const p=new _.Vector3;_.Triangle.getBarycoord(fn,kt,It,Lt,p),d.barycoord=p}}return d}function oo(o){return o&&o.isMaterial?o.side:o}function ii(o,e,t,n,i,s,r){const a=n*3;let l=a+0,h=a+1,c=a+2;const{index:d,groups:m}=o;o.index&&(l=d.getX(l),h=d.getX(h),c=d.getX(c));const{position:p,normal:f,uv:u,uv1:g}=o.attributes;if(Array.isArray(e)){const y=n*3;for(let w=0,x=m.length;w<x;w++){const{start:v,count:b,materialIndex:D}=m[w];if(y>=v&&y<v+b){const T=oo(e[D]),k=ro(t,p,f,u,g,l,h,c,T,s,r);if(k)if(k.faceIndex=n,k.face.materialIndex=D,i)i.push(k);else return k}}}else{const y=oo(e),w=ro(t,p,f,u,g,l,h,c,y,s,r);if(w)if(w.faceIndex=n,w.face.materialIndex=0,i)i.push(w);else return w}return null}function be(o,e,t,n){const i=o.a,s=o.b,r=o.c;let a=e,l=e+1,h=e+2;t&&(a=t.getX(a),l=t.getX(l),h=t.getX(h)),i.x=n.getX(a),i.y=n.getY(a),i.z=n.getZ(a),s.x=n.getX(l),s.y=n.getY(l),s.z=n.getZ(l),r.x=n.getX(h),r.y=n.getY(h),r.z=n.getZ(h)}function Fh(o,e,t,n,i,s,r,a){const{geometry:l,_indirectBuffer:h}=o;for(let c=n,d=n+i;c<d;c++)ii(l,e,t,c,s,r,a)}function Uh(o,e,t,n,i,s,r){const{geometry:a,_indirectBuffer:l}=o;let h=1/0,c=null;for(let d=n,m=n+i;d<m;d++){let p;p=ii(a,e,t,d,null,s,r),p&&p.distance<h&&(c=p,h=p.distance)}return c}function Vh(o,e,t,n,i,s,r){const{geometry:a}=t,{index:l}=a,h=a.attributes.position;for(let c=o,d=e+o;c<d;c++){let m;if(m=c,be(r,m*3,l,h),r.needsUpdate=!0,n(r,m,i,s))return!0}return!1}function jh(o,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=o.geometry,n=t.index?t.index.array:null,i=t.attributes.position;let s,r,a,l,h=0;const c=o._roots;for(let m=0,p=c.length;m<p;m++)s=c[m],r=new Uint32Array(s),a=new Uint16Array(s),l=new Float32Array(s),d(0,h),h+=s.byteLength;function d(m,p,f=!1){const u=m*2;if(Se(u,a)){const g=r[m+6],y=a[u+14];let w=1/0,x=1/0,v=1/0,b=-1/0,D=-1/0,T=-1/0;for(let k=3*g,P=3*(g+y);k<P;k++){let I=n[k];const z=i.getX(I),C=i.getY(I),E=i.getZ(I);z<w&&(w=z),z>b&&(b=z),C<x&&(x=C),C>D&&(D=C),E<v&&(v=E),E>T&&(T=E)}return l[m+0]!==w||l[m+1]!==x||l[m+2]!==v||l[m+3]!==b||l[m+4]!==D||l[m+5]!==T?(l[m+0]=w,l[m+1]=x,l[m+2]=v,l[m+3]=b,l[m+4]=D,l[m+5]=T,!0):!1}else{const g=Te(m),y=Pe(m,r);let w=f,x=!1,v=!1;if(e){if(!w){const I=g/Me+p/Ie,z=y/Me+p/Ie;x=e.has(I),v=e.has(z),w=!x&&!v}}else x=!0,v=!0;const b=w||x,D=w||v;let T=!1;b&&(T=d(g,p,w));let k=!1;D&&(k=d(y,p,w));const P=T||k;if(P)for(let I=0;I<3;I++){const z=g+I,C=y+I,E=l[z],M=l[z+3],B=l[C],V=l[C+3];l[m+I]=E<B?E:B,l[m+I+3]=M>V?M:V}return P}}}function mt(o,e,t,n,i){let s,r,a,l,h,c;const d=1/t.direction.x,m=1/t.direction.y,p=1/t.direction.z,f=t.origin.x,u=t.origin.y,g=t.origin.z;let y=e[o],w=e[o+3],x=e[o+1],v=e[o+3+1],b=e[o+2],D=e[o+3+2];return d>=0?(s=(y-f)*d,r=(w-f)*d):(s=(w-f)*d,r=(y-f)*d),m>=0?(a=(x-u)*m,l=(v-u)*m):(a=(v-u)*m,l=(x-u)*m),s>l||a>r||((a>s||isNaN(s))&&(s=a),(l<r||isNaN(r))&&(r=l),p>=0?(h=(b-g)*p,c=(D-g)*p):(h=(D-g)*p,c=(b-g)*p),s>c||h>r)?!1:((h>s||s!==s)&&(s=h),(c<r||r!==r)&&(r=c),s<=i&&r>=n)}function Gh(o,e,t,n,i,s,r,a){const{geometry:l,_indirectBuffer:h}=o;for(let c=n,d=n+i;c<d;c++){let m=h?h[c]:c;ii(l,e,t,m,s,r,a)}}function Wh(o,e,t,n,i,s,r){const{geometry:a,_indirectBuffer:l}=o;let h=1/0,c=null;for(let d=n,m=n+i;d<m;d++){let p;p=ii(a,e,t,l?l[d]:d,null,s,r),p&&p.distance<h&&(c=p,h=p.distance)}return c}function Xh(o,e,t,n,i,s,r){const{geometry:a}=t,{index:l}=a,h=a.attributes.position;for(let c=o,d=e+o;c<d;c++){let m;if(m=t.resolveTriangleIndex(c),be(r,m*3,l,h),r.needsUpdate=!0,n(r,m,i,s))return!0}return!1}function Zh(o,e,t,n,i,s,r){me.setBuffer(o._roots[e]),os(0,o,t,n,i,s,r),me.clearBuffer()}function os(o,e,t,n,i,s,r){const{float32Array:a,uint16Array:l,uint32Array:h}=me,c=o*2;if(Se(c,l)){const m=Ue(o,h),p=Xe(c,l);Fh(e,t,n,m,p,i,s,r)}else{const m=Te(o);mt(m,a,n,s,r)&&os(m,e,t,n,i,s,r);const p=Pe(o,h);mt(p,a,n,s,r)&&os(p,e,t,n,i,s,r)}}const qh=["x","y","z"];function Kh(o,e,t,n,i,s){me.setBuffer(o._roots[e]);const r=as(0,o,t,n,i,s);return me.clearBuffer(),r}function as(o,e,t,n,i,s){const{float32Array:r,uint16Array:a,uint32Array:l}=me;let h=o*2;if(Se(h,a)){const d=Ue(o,l),m=Xe(h,a);return Uh(e,t,n,d,m,i,s)}else{const d=is(o,l),m=qh[d],f=n.direction[m]>=0;let u,g;f?(u=Te(o),g=Pe(o,l)):(u=Pe(o,l),g=Te(o));const w=mt(u,r,n,i,s)?as(u,e,t,n,i,s):null;if(w){const b=w.point[m];if(f?b<=r[g+d]:b>=r[g+d+3])return w}const v=mt(g,r,n,i,s)?as(g,e,t,n,i,s):null;return w&&v?w.distance<=v.distance?w:v:w||v||null}}const si=new _.Box3,Yt=new Ge,$t=new Ge,pn=new _.Matrix4,ao=new Le,ri=new Le;function Yh(o,e,t,n){me.setBuffer(o._roots[e]);const i=ls(0,o,t,n);return me.clearBuffer(),i}function ls(o,e,t,n,i=null){const{float32Array:s,uint16Array:r,uint32Array:a}=me;let l=o*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),ao.set(t.boundingBox.min,t.boundingBox.max,n),i=ao),Se(l,r)){const c=e.geometry,d=c.index,m=c.attributes.position,p=t.index,f=t.attributes.position,u=Ue(o,a),g=Xe(l,r);if(pn.copy(n).invert(),t.boundsTree)return we(o,s,ri),ri.matrix.copy(pn),ri.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>ri.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(n),w.b.applyMatrix4(n),w.c.applyMatrix4(n),w.needsUpdate=!0;for(let x=u*3,v=(g+u)*3;x<v;x+=3)if(be($t,x,d,m),$t.needsUpdate=!0,w.intersectsTriangle($t))return!0;return!1}});{const y=Dt(t);for(let w=u*3,x=(g+u)*3;w<x;w+=3){be(Yt,w,d,m),Yt.a.applyMatrix4(pn),Yt.b.applyMatrix4(pn),Yt.c.applyMatrix4(pn),Yt.needsUpdate=!0;for(let v=0,b=y*3;v<b;v+=3)if(be($t,v,p,f),$t.needsUpdate=!0,Yt.intersectsTriangle($t))return!0}}}else{const c=Te(o),d=Pe(o,a);return we(c,s,si),!!(i.intersectsBox(si)&&ls(c,e,t,n,i)||(we(d,s,si),i.intersectsBox(si)&&ls(d,e,t,n,i)))}}const oi=new _.Matrix4,cs=new Le,mn=new Le,$h=new _.Vector3,Hh=new _.Vector3,Jh=new _.Vector3,Qh=new _.Vector3;function eu(o,e,t,n={},i={},s=0,r=1/0){e.boundingBox||e.computeBoundingBox(),cs.set(e.boundingBox.min,e.boundingBox.max,t),cs.needsUpdate=!0;const a=o.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,m=We.getPrimitive(),p=We.getPrimitive();let f=$h,u=Hh,g=null,y=null;i&&(g=Jh,y=Qh);let w=1/0,x=null,v=null;return oi.copy(t).invert(),mn.matrix.copy(oi),o.shapecast({boundsTraverseOrder:b=>cs.distanceToBox(b),intersectsBounds:(b,D,T)=>T<w&&T<r?(D&&(mn.min.copy(b.min),mn.max.copy(b.max),mn.needsUpdate=!0),!0):!1,intersectsRange:(b,D)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:k=>mn.distanceToBox(k),intersectsBounds:(k,P,I)=>I<w&&I<r,intersectsRange:(k,P)=>{for(let I=k,z=k+P;I<z;I++){be(p,3*I,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let C=b,E=b+D;C<E;C++){be(m,3*C,h,l),m.needsUpdate=!0;const M=m.distanceToTriangle(p,f,g);if(M<w&&(u.copy(f),y&&y.copy(g),w=M,x=C,v=I),M<s)return!0}}}});{const T=Dt(e);for(let k=0,P=T;k<P;k++){be(p,3*k,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let I=b,z=b+D;I<z;I++){be(m,3*I,h,l),m.needsUpdate=!0;const C=m.distanceToTriangle(p,f,g);if(C<w&&(u.copy(f),y&&y.copy(g),w=C,x=I,v=k),C<s)return!0}}}}}),We.releasePrimitive(m),We.releasePrimitive(p),w===1/0?null:(n.point?n.point.copy(u):n.point=u.clone(),n.distance=w,n.faceIndex=x,i&&(i.point?i.point.copy(y):i.point=y.clone(),i.point.applyMatrix4(oi),u.applyMatrix4(oi),i.distance=u.sub(i.point).length(),i.faceIndex=v),n)}function tu(o,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=o.geometry,n=t.index?t.index.array:null,i=t.attributes.position;let s,r,a,l,h=0;const c=o._roots;for(let m=0,p=c.length;m<p;m++)s=c[m],r=new Uint32Array(s),a=new Uint16Array(s),l=new Float32Array(s),d(0,h),h+=s.byteLength;function d(m,p,f=!1){const u=m*2;if(Se(u,a)){const g=r[m+6],y=a[u+14];let w=1/0,x=1/0,v=1/0,b=-1/0,D=-1/0,T=-1/0;for(let k=g,P=g+y;k<P;k++){const I=3*o.resolveTriangleIndex(k);for(let z=0;z<3;z++){let C=I+z;C=n?n[C]:C;const E=i.getX(C),M=i.getY(C),B=i.getZ(C);E<w&&(w=E),E>b&&(b=E),M<x&&(x=M),M>D&&(D=M),B<v&&(v=B),B>T&&(T=B)}}return l[m+0]!==w||l[m+1]!==x||l[m+2]!==v||l[m+3]!==b||l[m+4]!==D||l[m+5]!==T?(l[m+0]=w,l[m+1]=x,l[m+2]=v,l[m+3]=b,l[m+4]=D,l[m+5]=T,!0):!1}else{const g=Te(m),y=Pe(m,r);let w=f,x=!1,v=!1;if(e){if(!w){const I=g/Me+p/Ie,z=y/Me+p/Ie;x=e.has(I),v=e.has(z),w=!x&&!v}}else x=!0,v=!0;const b=w||x,D=w||v;let T=!1;b&&(T=d(g,p,w));let k=!1;D&&(k=d(y,p,w));const P=T||k;if(P)for(let I=0;I<3;I++){const z=g+I,C=y+I,E=l[z],M=l[z+3],B=l[C],V=l[C+3];l[m+I]=E<B?E:B,l[m+I+3]=M>V?M:V}return P}}}function nu(o,e,t,n,i,s,r){me.setBuffer(o._roots[e]),hs(0,o,t,n,i,s,r),me.clearBuffer()}function hs(o,e,t,n,i,s,r){const{float32Array:a,uint16Array:l,uint32Array:h}=me,c=o*2;if(Se(c,l)){const m=Ue(o,h),p=Xe(c,l);Gh(e,t,n,m,p,i,s,r)}else{const m=Te(o);mt(m,a,n,s,r)&&hs(m,e,t,n,i,s,r);const p=Pe(o,h);mt(p,a,n,s,r)&&hs(p,e,t,n,i,s,r)}}const iu=["x","y","z"];function su(o,e,t,n,i,s){me.setBuffer(o._roots[e]);const r=us(0,o,t,n,i,s);return me.clearBuffer(),r}function us(o,e,t,n,i,s){const{float32Array:r,uint16Array:a,uint32Array:l}=me;let h=o*2;if(Se(h,a)){const d=Ue(o,l),m=Xe(h,a);return Wh(e,t,n,d,m,i,s)}else{const d=is(o,l),m=iu[d],f=n.direction[m]>=0;let u,g;f?(u=Te(o),g=Pe(o,l)):(u=Pe(o,l),g=Te(o));const w=mt(u,r,n,i,s)?us(u,e,t,n,i,s):null;if(w){const b=w.point[m];if(f?b<=r[g+d]:b>=r[g+d+3])return w}const v=mt(g,r,n,i,s)?us(g,e,t,n,i,s):null;return w&&v?w.distance<=v.distance?w:v:w||v||null}}const ai=new _.Box3,Ht=new Ge,Jt=new Ge,gn=new _.Matrix4,lo=new Le,li=new Le;function ru(o,e,t,n){me.setBuffer(o._roots[e]);const i=ds(0,o,t,n);return me.clearBuffer(),i}function ds(o,e,t,n,i=null){const{float32Array:s,uint16Array:r,uint32Array:a}=me;let l=o*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),lo.set(t.boundingBox.min,t.boundingBox.max,n),i=lo),Se(l,r)){const c=e.geometry,d=c.index,m=c.attributes.position,p=t.index,f=t.attributes.position,u=Ue(o,a),g=Xe(l,r);if(gn.copy(n).invert(),t.boundsTree)return we(o,s,li),li.matrix.copy(gn),li.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>li.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(n),w.b.applyMatrix4(n),w.c.applyMatrix4(n),w.needsUpdate=!0;for(let x=u,v=g+u;x<v;x++)if(be(Jt,3*e.resolveTriangleIndex(x),d,m),Jt.needsUpdate=!0,w.intersectsTriangle(Jt))return!0;return!1}});{const y=Dt(t);for(let w=u,x=g+u;w<x;w++){const v=e.resolveTriangleIndex(w);be(Ht,3*v,d,m),Ht.a.applyMatrix4(gn),Ht.b.applyMatrix4(gn),Ht.c.applyMatrix4(gn),Ht.needsUpdate=!0;for(let b=0,D=y*3;b<D;b+=3)if(be(Jt,b,p,f),Jt.needsUpdate=!0,Ht.intersectsTriangle(Jt))return!0}}}else{const c=Te(o),d=Pe(o,a);return we(c,s,ai),!!(i.intersectsBox(ai)&&ds(c,e,t,n,i)||(we(d,s,ai),i.intersectsBox(ai)&&ds(d,e,t,n,i)))}}const ci=new _.Matrix4,fs=new Le,yn=new Le,ou=new _.Vector3,au=new _.Vector3,lu=new _.Vector3,cu=new _.Vector3;function hu(o,e,t,n={},i={},s=0,r=1/0){e.boundingBox||e.computeBoundingBox(),fs.set(e.boundingBox.min,e.boundingBox.max,t),fs.needsUpdate=!0;const a=o.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,m=We.getPrimitive(),p=We.getPrimitive();let f=ou,u=au,g=null,y=null;i&&(g=lu,y=cu);let w=1/0,x=null,v=null;return ci.copy(t).invert(),yn.matrix.copy(ci),o.shapecast({boundsTraverseOrder:b=>fs.distanceToBox(b),intersectsBounds:(b,D,T)=>T<w&&T<r?(D&&(yn.min.copy(b.min),yn.max.copy(b.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(b,D)=>{if(e.boundsTree){const T=e.boundsTree;return T.shapecast({boundsTraverseOrder:k=>yn.distanceToBox(k),intersectsBounds:(k,P,I)=>I<w&&I<r,intersectsRange:(k,P)=>{for(let I=k,z=k+P;I<z;I++){const C=T.resolveTriangleIndex(I);be(p,3*C,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let E=b,M=b+D;E<M;E++){const B=o.resolveTriangleIndex(E);be(m,3*B,h,l),m.needsUpdate=!0;const V=m.distanceToTriangle(p,f,g);if(V<w&&(u.copy(f),y&&y.copy(g),w=V,x=E,v=I),V<s)return!0}}}})}else{const T=Dt(e);for(let k=0,P=T;k<P;k++){be(p,3*k,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let I=b,z=b+D;I<z;I++){const C=o.resolveTriangleIndex(I);be(m,3*C,h,l),m.needsUpdate=!0;const E=m.distanceToTriangle(p,f,g);if(E<w&&(u.copy(f),y&&y.copy(g),w=E,x=I,v=k),E<s)return!0}}}}}),We.releasePrimitive(m),We.releasePrimitive(p),w===1/0?null:(n.point?n.point.copy(u):n.point=u.clone(),n.distance=w,n.faceIndex=x,i&&(i.point?i.point.copy(y):i.point=y.clone(),i.point.applyMatrix4(ci),u.applyMatrix4(ci),i.distance=u.sub(i.point).length(),i.faceIndex=v),n)}function uu(){return typeof SharedArrayBuffer<"u"}const wn=new me.constructor,hi=new me.constructor,gt=new ns(()=>new _.Box3),Qt=new _.Box3,en=new _.Box3,ps=new _.Box3,ms=new _.Box3;let gs=!1;function du(o,e,t,n){if(gs)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");gs=!0;const i=o._roots,s=e._roots;let r,a=0,l=0;const h=new _.Matrix4().copy(t).invert();for(let c=0,d=i.length;c<d;c++){wn.setBuffer(i[c]),l=0;const m=gt.getPrimitive();we(0,wn.float32Array,m),m.applyMatrix4(h);for(let p=0,f=s.length;p<f&&(hi.setBuffer(s[p]),r=Ke(0,0,t,h,n,a,l,0,0,m),hi.clearBuffer(),l+=s[p].byteLength/Ie,!r);p++);if(gt.releasePrimitive(m),wn.clearBuffer(),a+=i[c].byteLength/Ie,r)break}return gs=!1,r}function Ke(o,e,t,n,i,s=0,r=0,a=0,l=0,h=null,c=!1){let d,m;c?(d=hi,m=wn):(d=wn,m=hi);const p=d.float32Array,f=d.uint32Array,u=d.uint16Array,g=m.float32Array,y=m.uint32Array,w=m.uint16Array,x=o*2,v=e*2,b=Se(x,u),D=Se(v,w);let T=!1;if(D&&b)c?T=i(Ue(e,y),Xe(e*2,w),Ue(o,f),Xe(o*2,u),l,r+e/Me,a,s+o/Me):T=i(Ue(o,f),Xe(o*2,u),Ue(e,y),Xe(e*2,w),a,s+o/Me,l,r+e/Me);else if(D){const k=gt.getPrimitive();we(e,g,k),k.applyMatrix4(t);const P=Te(o),I=Pe(o,f);we(P,p,Qt),we(I,p,en);const z=k.intersectsBox(Qt),C=k.intersectsBox(en);T=z&&Ke(e,P,n,t,i,r,s,l,a+1,k,!c)||C&&Ke(e,I,n,t,i,r,s,l,a+1,k,!c),gt.releasePrimitive(k)}else{const k=Te(e),P=Pe(e,y);we(k,g,ps),we(P,g,ms);const I=h.intersectsBox(ps),z=h.intersectsBox(ms);if(I&&z)T=Ke(o,k,t,n,i,s,r,a,l+1,h,c)||Ke(o,P,t,n,i,s,r,a,l+1,h,c);else if(I)if(b)T=Ke(o,k,t,n,i,s,r,a,l+1,h,c);else{const C=gt.getPrimitive();C.copy(ps).applyMatrix4(t);const E=Te(o),M=Pe(o,f);we(E,p,Qt),we(M,p,en);const B=C.intersectsBox(Qt),V=C.intersectsBox(en);T=B&&Ke(k,E,n,t,i,r,s,l,a+1,C,!c)||V&&Ke(k,M,n,t,i,r,s,l,a+1,C,!c),gt.releasePrimitive(C)}else if(z)if(b)T=Ke(o,P,t,n,i,s,r,a,l+1,h,c);else{const C=gt.getPrimitive();C.copy(ms).applyMatrix4(t);const E=Te(o),M=Pe(o,f);we(E,p,Qt),we(M,p,en);const B=C.intersectsBox(Qt),V=C.intersectsBox(en);T=B&&Ke(P,E,n,t,i,r,s,l,a+1,C,!c)||V&&Ke(P,M,n,t,i,r,s,l,a+1,C,!c),gt.releasePrimitive(C)}}return T}const ui=new Le,co=new _.Box3,fu={strategy:Gr,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class ys{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,i=e._roots,s=e._indirectBuffer,r=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=i.map(l=>l.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=s?s.slice():null):(a.roots=i,a.index=r?r.array:null,a.indirectBuffer=s),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:i,roots:s,indirectBuffer:r}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(s));const a=new ys(t,{...n,[Yi]:!0});if(a._roots=s,a._indirectBuffer=r||null,n.setIndex){const h=t.getIndex();if(h===null){const c=new _.BufferAttribute(e.index,1,!1);t.setIndex(c)}else h.array!==i&&(h.array.set(i),h.needsUpdate=!0)}return a;function l(h){for(let c=0;c<h.length;c++){const d=h[c],m=new Uint32Array(d),p=new Uint16Array(d);for(let f=0,u=d.byteLength/Ie;f<u;f++){const g=Me*f,y=2*g;Se(y,p)||(m[g+6]=m[g+6]/Me-f)}}}}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...fu,[Yi]:!1},t),t.useSharedArrayBuffer&&!uu())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[Yi]||(Dh(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new _.Box3))),this.resolveTriangleIndex=t.indirect?n=>this._indirectBuffer[n]:n=>n}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,i=t.length;n<i;n++)t[n]+=e;else{const n=this._roots;for(let i=0;i<n.length;i++){const s=n[i],r=new Uint32Array(s),a=new Uint16Array(s),l=s.byteLength/Ie;for(let h=0;h<l;h++){const c=Me*h,d=2*c;Se(d,a)&&(r[c+6]+=e)}}}}refit(e=null){return(this.indirect?tu:jh)(this,e)}traverse(e,t=0){const n=this._roots[t],i=new Uint32Array(n),s=new Uint16Array(n);r(0);function r(a,l=0){const h=a*2,c=Se(h,s);if(c){const d=i[a+6],m=s[h+14];e(l,c,new Float32Array(n,a*4,6),d,m)}else{const d=Te(a),m=Pe(a,i),p=is(a,i);e(l,c,new Float32Array(n,a*4,6),p)||(r(d,l+1),r(m,l+1))}}}raycast(e,t=_.FrontSide,n=0,i=1/0){const s=this._roots,r=[],a=this.indirect?nu:Zh;for(let l=0,h=s.length;l<h;l++)a(this,l,t,e,r,n,i);return r}raycastFirst(e,t=_.FrontSide,n=0,i=1/0){const s=this._roots;let r=null;const a=this.indirect?su:Kh;for(let l=0,h=s.length;l<h;l++){const c=a(this,l,t,e,n,i);c!=null&&(r==null||c.distance<r.distance)&&(r=c)}return r}intersectsGeometry(e,t){let n=!1;const i=this._roots,s=this.indirect?ru:Yh;for(let r=0,a=i.length;r<a&&(n=s(this,r,e,t),!n);r++);return n}shapecast(e){const t=We.getPrimitive(),n=this.indirect?Xh:Vh;let{boundsTraverseOrder:i,intersectsBounds:s,intersectsRange:r,intersectsTriangle:a}=e;if(r&&a){const d=r;r=(m,p,f,u,g)=>d(m,p,f,u,g)?!0:n(m,p,this,a,f,u,t)}else r||(a?r=(d,m,p,f)=>n(d,m,this,a,p,f,t):r=(d,m,p)=>p);let l=!1,h=0;const c=this._roots;for(let d=0,m=c.length;d<m;d++){const p=c[d];if(l=Oh(this,d,s,r,i,h),l)break;h+=p.byteLength/Ie}return We.releasePrimitive(t),l}bvhcast(e,t,n){let{intersectsRanges:i,intersectsTriangles:s}=n;const r=We.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,h=this.indirect?f=>{const u=this.resolveTriangleIndex(f);be(r,u*3,a,l)}:f=>{be(r,f*3,a,l)},c=We.getPrimitive(),d=e.geometry.index,m=e.geometry.attributes.position,p=e.indirect?f=>{const u=e.resolveTriangleIndex(f);be(c,u*3,d,m)}:f=>{be(c,f*3,d,m)};if(s){const f=(u,g,y,w,x,v,b,D)=>{for(let T=y,k=y+w;T<k;T++){p(T),c.a.applyMatrix4(t),c.b.applyMatrix4(t),c.c.applyMatrix4(t),c.needsUpdate=!0;for(let P=u,I=u+g;P<I;P++)if(h(P),r.needsUpdate=!0,s(r,c,P,T,x,v,b,D))return!0}return!1};if(i){const u=i;i=function(g,y,w,x,v,b,D,T){return u(g,y,w,x,v,b,D,T)?!0:f(g,y,w,x,v,b,D,T)}}else i=f}return du(this,e,t,i)}intersectsBox(e,t){return ui.set(e.min,e.max,t),ui.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ui.intersectsBox(n),intersectsTriangle:n=>ui.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},i={},s=0,r=1/0){return(this.indirect?hu:eu)(this,e,t,n,i,s,r)}closestPointToPoint(e,t={},n=0,i=1/0){return zh(this,e,t,n,i)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{we(0,new Float32Array(n),co),e.union(co)}),e}}const ho=1e-6,pu=ho*.5,uo=Math.pow(10,-Math.log10(ho)),mu=pu*uo;function tt(o){return~~(o*uo+mu)}function gu(o){return`${tt(o.x)},${tt(o.y)}`}function fo(o){return`${tt(o.x)},${tt(o.y)},${tt(o.z)}`}function yu(o){return`${tt(o.x)},${tt(o.y)},${tt(o.z)},${tt(o.w)}`}function wu(o,e,t){t.direction.subVectors(e,o).normalize();const n=o.dot(t.direction);return t.origin.copy(o).addScaledVector(t.direction,-n),t}function po(){return typeof SharedArrayBuffer<"u"}function xu(o){if(o.buffer instanceof SharedArrayBuffer)return o;const e=o.constructor,t=o.buffer,n=new SharedArrayBuffer(t.byteLength),i=new Uint8Array(t);return new Uint8Array(n).set(i,0),new e(n)}function vu(o,e=ArrayBuffer){return o>65535?new Uint32Array(new e(4*o)):new Uint16Array(new e(2*o))}function bu(o,e){if(!o.index){const t=o.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=vu(t,n);o.setIndex(new _.BufferAttribute(i,1));for(let s=0;s<t;s++)i[s]=s}}function _u(o){return o.index?o.index.count:o.attributes.position.count}function ws(o){return _u(o)/3}const Mu=1e-8,Su=new _.Vector3;function Au(o){return~~(o/3)}function Cu(o){return o%3}function mo(o,e){return o.start-e.start}function go(o,e){return Su.subVectors(e,o.origin).dot(o.direction)}function Tu(o,e,t,n=Mu){o.sort(mo),e.sort(mo);for(let a=0;a<o.length;a++){const l=o[a];for(let h=0;h<e.length;h++){const c=e[h];if(!(c.start>l.end)){if(l.end<c.start||c.end<l.start)continue;if(l.start<=c.start&&l.end>=c.end)s(c.end,l.end)||o.splice(a+1,0,{start:c.end,end:l.end,index:l.index}),l.end=c.start,c.start=0,c.end=0;else if(l.start>=c.start&&l.end<=c.end)s(l.end,c.end)||e.splice(h+1,0,{start:l.end,end:c.end,index:c.index}),c.end=l.start,l.start=0,l.end=0;else if(l.start<=c.start&&l.end<=c.end){const d=l.end;l.end=c.start,c.start=d}else if(l.start>=c.start&&l.end>=c.end){const d=c.end;c.end=l.start,l.start=d}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(c.index)||t.set(c.index,[]),t.get(l.index).push(c.index),t.get(c.index).push(l.index),r(c)&&(e.splice(h,1),h--),r(l)){o.splice(a,1),a--;break}}}i(o),i(e);function i(a){for(let l=0;l<a.length;l++)r(a[l])&&(a.splice(l,1),l--)}function s(a,l){return Math.abs(l-a)<n}function r(a){return Math.abs(a.end-a.start)<n}}const yo=1e-5,wo=1e-4;class Pu{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const t=this._rays,n=e.clone();n.direction.multiplyScalar(-1);let i=1/0,s=null;for(let l=0,h=t.length;l<h;l++){const c=t[l];if(r(c,e)&&r(c,n))continue;const d=a(c,e),m=a(c,n),p=Math.min(d,m);p<i&&(i=p,s=c)}return s;function r(l,h){const c=l.origin.distanceTo(h.origin)>yo;return l.direction.angleTo(h.direction)>wo||c}function a(l,h){const c=l.origin.distanceTo(h.origin),d=l.direction.angleTo(h.direction);return c/yo+d/wo}}}const xs=new _.Vector3,vs=new _.Vector3,di=new _.Ray;function Du(o,e,t){const n=o.attributes,i=o.index,s=n.position,r=new Map,a=new Map,l=Array.from(e),h=new Pu;for(let c=0,d=l.length;c<d;c++){const m=l[c],p=Au(m),f=Cu(m);let u=3*p+f,g=3*p+(f+1)%3;i&&(u=i.getX(u),g=i.getX(g)),xs.fromBufferAttribute(s,u),vs.fromBufferAttribute(s,g),wu(xs,vs,di);let y,w=h.findClosestRay(di);w===null&&(w=di.clone(),h.addRay(w)),a.has(w)||a.set(w,{forward:[],reverse:[],ray:w}),y=a.get(w);let x=go(w,xs),v=go(w,vs);x>v&&([x,v]=[v,x]),di.direction.dot(w.direction)<0?y.reverse.push({start:x,end:v,index:m}):y.forward.push({start:x,end:v,index:m})}return a.forEach(({forward:c,reverse:d},m)=>{Tu(c,d,r,t),c.length===0&&d.length===0&&a.delete(m)}),{disjointConnectivityMap:r,fragmentMap:a}}const ku=new _.Vector2,bs=new _.Vector3,Iu=new _.Vector4,_s=["","",""];class Lu{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const n=this.data[e*3+t];return n===-1?-1:~~(n/3)}getSiblingEdgeIndex(e,t){const n=this.data[e*3+t];return n===-1?-1:n%3}getDisjointSiblingTriangleIndices(e,t){const n=e*3+t,i=this.disjointConnections.get(n);return i?i.map(s=>~~(s/3)):[]}getDisjointSiblingEdgeIndices(e,t){const n=e*3+t,i=this.disjointConnections.get(n);return i?i.map(s=>s%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:n,matchDisjointEdges:i,degenerateEpsilon:s}=this,r=t?x:w,a=new Map,{attributes:l}=e,h=t?Object.keys(l):null,c=e.index,d=l.position;let m=ws(e);const p=m;let f=0;n&&(f=e.drawRange.start,e.drawRange.count!==1/0&&(m=~~(e.drawRange.count/3)));let u=this.data;(!u||u.length<3*p)&&(u=new Int32Array(3*p)),u.fill(-1);let g=0,y=new Set;for(let v=f,b=m*3+f;v<b;v+=3){const D=v;for(let T=0;T<3;T++){let k=D+T;c&&(k=c.getX(k)),_s[T]=r(k)}for(let T=0;T<3;T++){const k=(T+1)%3,P=_s[T],I=_s[k],z=`${I}_${P}`;if(a.has(z)){const C=D+T,E=a.get(z);u[C]=E,u[E]=C,a.delete(z),g+=2,y.delete(E)}else{const C=`${P}_${I}`,E=D+T;a.set(C,E),y.add(E)}}}if(i){const{fragmentMap:v,disjointConnectivityMap:b}=Du(e,y,s);y.clear(),v.forEach(({forward:D,reverse:T})=>{D.forEach(({index:k})=>y.add(k)),T.forEach(({index:k})=>y.add(k))}),this.unmatchedDisjointEdges=v,this.disjointConnections=b,g=m*3-y.size}this.matchedEdges=g,this.unmatchedEdges=y.size,this.data=u;function w(v){return bs.fromBufferAttribute(d,v),fo(bs)}function x(v){let b="";for(let D=0,T=h.length;D<T;D++){const k=l[h[D]];let P;switch(k.itemSize){case 1:P=tt(k.getX(v));break;case 2:P=gu(ku.fromBufferAttribute(k,v));break;case 3:P=fo(bs.fromBufferAttribute(k,v));break;case 4:P=yu(Iu.fromBufferAttribute(k,v));break}b!==""&&(b+="|"),b+=P}return b}}}class fi extends _.Mesh{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new _.Matrix4,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:t}=this,n=e.elements,i=t.elements;for(let s=0;s<16;s++)if(n[s]!==i[s])return!0;return!1}prepareGeometry(){const e=this.geometry,t=e.attributes,n=po();if(n)for(const i in t){const s=t[i];if(s.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");s.array=xu(s.array)}if(e.boundsTree||(bu(e,{useSharedArrayBuffer:n}),e.boundsTree=new ys(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:n})),e.halfEdges||(e.halfEdges=new Lu(e)),!e.groupIndices){const i=ws(e),s=new Uint16Array(i),r=e.groups;for(let a=0,l=r.length;a<l;a++){const{start:h,count:c}=r[a];for(let d=h/3,m=(h+c)/3;d<m;d++)s[d]=a}e.groupIndices=s}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const Eu=1e-14,Ms=new _.Vector3,xo=new _.Vector3,vo=new _.Vector3;function yt(o,e=Eu){Ms.subVectors(o.b,o.a),xo.subVectors(o.c,o.a),vo.subVectors(o.b,o.c);const t=Ms.angleTo(xo),n=Ms.angleTo(vo),i=Math.PI-t-n;return Math.abs(t)<e||Math.abs(n)<e||Math.abs(i)<e||o.a.distanceToSquared(o.b)<e||o.a.distanceToSquared(o.c)<e||o.b.distanceToSquared(o.c)<e}const Ss=1e-10,xn=1e-10,Bu=1e-10,lt=new _.Line3,xe=new _.Line3,ct=new _.Vector3,As=new _.Vector3,bo=new _.Vector3,pi=new _.Plane,Cs=new Ge;class Ou{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new _.Triangle),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class zu{constructor(){this.trianglePool=new Ou,this.triangles=[],this.normal=new _.Vector3,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:n,normal:i}=this;if(Array.isArray(e))for(let s=0,r=e.length;s<r;s++){const a=e[s];if(s===0)a.getNormal(i);else if(Math.abs(1-a.getNormal(ct).dot(i))>Ss)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=n.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(i);const s=n.getTriangle();s.copy(e),t.push(s)}}splitByTriangle(e){const{normal:t,triangles:n}=this;if(e.getNormal(As).normalize(),Math.abs(1-Math.abs(As.dot(t)))<Bu){this.coplanarTriangleUsed=!0;for(let s=0,r=n.length;s<r;s++){const a=n[s];a.coplanarCount=0}const i=[e.a,e.b,e.c];for(let s=0;s<3;s++){const r=(s+1)%3,a=i[s],l=i[r];ct.subVectors(l,a).normalize(),bo.crossVectors(As,ct),pi.setFromNormalAndCoplanarPoint(bo,a),this.splitByPlane(pi,e)}}else e.getPlane(pi),this.splitByPlane(pi,e)}splitByPlane(e,t){const{triangles:n,trianglePool:i}=this;Cs.copy(t),Cs.needsUpdate=!0;for(let s=0,r=n.length;s<r;s++){const a=n[s];if(!Cs.intersectsTriangle(a,lt,!0))continue;const{a:l,b:h,c}=a;let d=0,m=-1,p=!1,f=[],u=[];const g=[l,h,c];for(let y=0;y<3;y++){const w=(y+1)%3;lt.start.copy(g[y]),lt.end.copy(g[w]);const x=e.distanceToPoint(lt.start),v=e.distanceToPoint(lt.end);if(Math.abs(x)<xn&&Math.abs(v)<xn){p=!0;break}if(x>0?f.push(y):u.push(y),Math.abs(x)<xn)continue;let b=!!e.intersectLine(lt,ct);!b&&Math.abs(v)<xn&&(ct.copy(lt.end),b=!0),b&&!(ct.distanceTo(lt.start)<Ss)&&(ct.distanceTo(lt.end)<Ss&&(m=y),d===0?xe.start.copy(ct):xe.end.copy(ct),d++)}if(!p&&d===2&&xe.distance()>xn)if(m!==-1){m=(m+1)%3;let y=0;y===m&&(y=(y+1)%3);let w=y+1;w===m&&(w=(w+1)%3);const x=i.getTriangle();x.a.copy(g[w]),x.b.copy(xe.end),x.c.copy(xe.start),yt(x)||n.push(x),a.a.copy(g[y]),a.b.copy(xe.start),a.c.copy(xe.end),yt(a)&&(n.splice(s,1),s--,r--)}else{const y=f.length>=2?u[0]:f[0];if(y===0){let D=xe.start;xe.start=xe.end,xe.end=D}const w=(y+1)%3,x=(y+2)%3,v=i.getTriangle(),b=i.getTriangle();g[w].distanceToSquared(xe.start)<g[x].distanceToSquared(xe.end)?(v.a.copy(g[w]),v.b.copy(xe.start),v.c.copy(xe.end),b.a.copy(g[w]),b.b.copy(g[x]),b.c.copy(xe.start)):(v.a.copy(g[x]),v.b.copy(xe.start),v.c.copy(xe.end),b.a.copy(g[w]),b.b.copy(g[x]),b.c.copy(xe.end)),a.a.copy(g[y]),a.b.copy(xe.end),a.c.copy(xe.start),yt(v)||n.push(v),yt(b)||n.push(b),yt(a)&&(n.splice(s,1),s--,r--)}else d===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function Nu(o){return o=~~o,o+4-o%4}class _o{constructor(e,t=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(t)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const t=this.array.buffer;this.array=new e(t),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const t=this.type,n=po()?SharedArrayBuffer:ArrayBuffer,i=new t(new n(Nu(e*t.BYTES_PER_ELEMENT)));this.array&&i.set(this.array,0),this.array=i}expand(){const{array:e,expansionFactor:t}=this;this.setSize(e.length*t)}push(...e){let{array:t,length:n}=this;n+e.length>t.length&&(this.expand(),t=this.array);for(let i=0,s=e.length;i<s;i++)t[n+i]=e[i];this.length+=e.length}clear(){this.length=0}}class Ru{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const t=this.getGroupAttrArray("position",e);return t.length/t.itemSize}getTotalLength(e){const{groupCount:t,groupAttributes:n}=this;let i=0;for(let s=0;s<t;s++){const r=n[s];i+=r[e].length}return i}getGroupAttrSet(e=0){const{groupAttributes:t}=this;if(t[e])return this.groupCount=Math.max(this.groupCount,e+1),t[e];const n=t[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=t.length;){const i={};t.push(i);for(const s in n){const r=n[s],a=new _o(r.type);a.itemSize=r.itemSize,a.normalized=r.normalized,i[s]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:n}=this;if(!n[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,n,i){const{groupAttributes:s}=this,a=s[0][e];if(a){if(a.type!==t)for(let l=0,h=s.length;l<h;l++){const c=s[l][e];c.setType(t),c.itemSize=n,c.normalized=i}}else for(let l=0,h=s.length;l<h;l++){const c=new _o(t);c.itemSize=n,c.normalized=i,s[l][e]=c}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(t=>{for(const n in t)t[n].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class Mo{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:n,ids:i}=this;n[e]||(n[e]=[],i.push(e)),n[e].push(t)}}const Fu=0,Uu=1,Vu=2,So=3,ju=4,Ao=5,Co=6,Ze=new _.Ray,To=new _.Matrix4,Ee=new _.Triangle,ht=new _.Vector3,Po=new _.Vector4,Do=new _.Vector4,ko=new _.Vector4,Ts=new _.Vector4,mi=new _.Vector4,gi=new _.Vector4,Io=new _.Line3,Ps=new _.Vector3,Ds=1e-8,Gu=1e-15,Et=-1,Bt=1,yi=-2,wi=2,vn=0,Ot=1,ks=2,Wu=1e-14;let xi=null;function Lo(o){xi=o}function Eo(o,e){o.getMidpoint(Ze.origin),o.getNormal(Ze.direction);const t=e.raycastFirst(Ze,_.DoubleSide);return!!(t&&Ze.direction.dot(t.face.normal)>0)?Et:Bt}function Xu(o,e){function t(){return Math.random()-.5}o.getNormal(Ps),Ze.direction.copy(Ps),o.getMidpoint(Ze.origin);const n=3;let i=0,s=1/0;for(let r=0;r<n;r++){Ze.direction.x+=t()*Ds,Ze.direction.y+=t()*Ds,Ze.direction.z+=t()*Ds,Ze.direction.multiplyScalar(-1);const a=e.raycastFirst(Ze,_.DoubleSide);if(!!(a&&Ze.direction.dot(a.face.normal)>0)&&i++,a!==null&&(s=Math.min(s,a.distance)),s<=Gu)return a.face.normal.dot(Ps)>0?wi:yi;if(i/n>.5||(r-i+1)/n>.5)break}return i/n>.5?Et:Bt}function Zu(o,e){const t=new Mo,n=new Mo;return To.copy(o.matrixWorld).invert().multiply(e.matrixWorld),o.geometry.boundsTree.bvhcast(e.geometry.boundsTree,To,{intersectsTriangles(i,s,r,a){if(!yt(i)&&!yt(s)){let l=i.intersectsTriangle(s,Io,!0);if(!l){const h=i.plane,c=s.plane,d=h.normal,m=c.normal;d.dot(m)===1&&Math.abs(h.constant-c.constant)<Wu&&(l=!0)}if(l){let h=o.geometry.boundsTree.resolveTriangleIndex(r),c=e.geometry.boundsTree.resolveTriangleIndex(a);t.add(h,c),n.add(c,h),xi&&(xi.addEdge(Io),xi.addIntersectingTriangles(r,i,a,s))}}return!1}}),{aIntersections:t,bIntersections:n}}function qu(o,e,t,n,i,s,r=!1){const a=t.attributes,l=t.index,h=o*3,c=l.getX(h+0),d=l.getX(h+1),m=l.getX(h+2);for(const p in s){const f=a[p],u=s[p];if(!(p in a))throw new Error(`CSG Operations: Attribute ${p} not available on geometry.`);const g=f.itemSize;p==="position"?(Ee.a.fromBufferAttribute(f,c).applyMatrix4(n),Ee.b.fromBufferAttribute(f,d).applyMatrix4(n),Ee.c.fromBufferAttribute(f,m).applyMatrix4(n),Is(Ee.a,Ee.b,Ee.c,e,3,u,r)):p==="normal"?(Ee.a.fromBufferAttribute(f,c).applyNormalMatrix(i),Ee.b.fromBufferAttribute(f,d).applyNormalMatrix(i),Ee.c.fromBufferAttribute(f,m).applyNormalMatrix(i),r&&(Ee.a.multiplyScalar(-1),Ee.b.multiplyScalar(-1),Ee.c.multiplyScalar(-1)),Is(Ee.a,Ee.b,Ee.c,e,3,u,r,!0)):(Po.fromBufferAttribute(f,c),Do.fromBufferAttribute(f,d),ko.fromBufferAttribute(f,m),Is(Po,Do,ko,e,g,u,r))}}function Ku(o,e,t,n,i,s,r,a=!1){Ls(o,n,i,s,r,a),Ls(a?t:e,n,i,s,r,a),Ls(a?e:t,n,i,s,r,a)}function Bo(o,e,t=!1){switch(o){case Fu:if(e===Bt||e===wi&&!t)return Ot;break;case Uu:if(t){if(e===Et)return vn}else if(e===Bt||e===yi)return Ot;break;case Vu:if(t){if(e===Bt||e===yi)return Ot}else if(e===Et)return vn;break;case ju:if(e===Et)return vn;if(e===Bt)return Ot;break;case So:if(e===Et||e===wi&&!t)return Ot;break;case Ao:if(!t&&(e===Bt||e===yi))return Ot;break;case Co:if(!t&&(e===Et||e===wi))return Ot;break;default:throw new Error(`Unrecognized CSG operation enum "${o}".`)}return ks}function Is(o,e,t,n,i,s,r=!1,a=!1){const l=h=>{s.push(h.x),i>1&&s.push(h.y),i>2&&s.push(h.z),i>3&&s.push(h.w)};Ts.set(0,0,0,0).addScaledVector(o,n.a.x).addScaledVector(e,n.a.y).addScaledVector(t,n.a.z),mi.set(0,0,0,0).addScaledVector(o,n.b.x).addScaledVector(e,n.b.y).addScaledVector(t,n.b.z),gi.set(0,0,0,0).addScaledVector(o,n.c.x).addScaledVector(e,n.c.y).addScaledVector(t,n.c.z),a&&(Ts.normalize(),mi.normalize(),gi.normalize()),l(Ts),r?(l(gi),l(mi)):(l(mi),l(gi))}function Ls(o,e,t,n,i,s=!1){for(const r in i){const a=e[r],l=i[r];if(!(r in e))throw new Error(`CSG Operations: Attribute ${r} no available on geometry.`);const h=a.itemSize;r==="position"?(ht.fromBufferAttribute(a,o).applyMatrix4(t),l.push(ht.x,ht.y,ht.z)):r==="normal"?(ht.fromBufferAttribute(a,o).applyNormalMatrix(n),s&&ht.multiplyScalar(-1),l.push(ht.x,ht.y,ht.z)):(l.push(a.getX(o)),h>1&&l.push(a.getY(o)),h>2&&l.push(a.getZ(o)),h>3&&l.push(a.getW(o)))}}class Yu{constructor(e){this.triangle=new _.Triangle().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new _.Triangle().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const n in t)e.push(t[n]);return e}}class Oo{constructor(){this.data={}}addTriangleIntersection(e,t,n,i){const{data:s}=this;s[e]||(s[e]=new Yu(t)),s[e].addTriangle(n,i)}getTrianglesAsArray(e=null){const{data:t}=this,n=[];if(e!==null)e in t&&n.push(t[e].triangle);else for(const i in t)n.push(t[i].triangle);return n}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(n=>parseInt(n)):[]}getIntersectionsAsArray(e=null,t=null){const{data:n}=this,i=new Set,s=[],r=a=>{if(n[a])if(t!==null)n[a].intersects[t]&&s.push(n[a].intersects[t]);else{const l=n[a].intersects;for(const h in l)i.has(h)||(i.add(h),s.push(l[h]))}};if(e!==null)r(e);else for(const a in n)r(a);return s}reset(){this.data={}}}class $u{constructor(){this.enabled=!1,this.triangleIntersectsA=new Oo,this.triangleIntersectsB=new Oo,this.intersectionEdges=[]}addIntersectingTriangles(e,t,n,i){const{triangleIntersectsA:s,triangleIntersectsB:r}=this;s.addTriangleIntersection(e,t,n,i),r.addTriangleIntersection(n,i,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),Lo(this))}complete(){this.enabled&&Lo(null)}}const wt=new _.Matrix4,vi=new _.Matrix3,zt=new _.Triangle,bi=new _.Triangle,xt=new _.Triangle,_i=new _.Triangle,Ye=[],Nt=[];function Hu(o){for(const e of o)return e}function Ju(o,e,t,n,i,s={}){const{useGroups:r=!0}=s,{aIntersections:a,bIntersections:l}=Zu(o,e),h=[];let c=null,d;return d=r?0:-1,zo(o,e,a,t,!1,n,i,d),No(o,e,a,t,!1,i,d),t.findIndex(p=>p!==Co&&p!==Ao)!==-1&&(d=r?o.geometry.groups.length||1:-1,zo(e,o,l,t,!0,n,i,d),No(e,o,l,t,!0,i,d)),Ye.length=0,Nt.length=0,{groups:h,materials:c}}function zo(o,e,t,n,i,s,r,a=0){const l=o.matrixWorld.determinant()<0;wt.copy(e.matrixWorld).invert().multiply(o.matrixWorld),vi.getNormalMatrix(o.matrixWorld).multiplyScalar(l?-1:1);const h=o.geometry.groupIndices,c=o.geometry.index,d=o.geometry.attributes.position,m=e.geometry.boundsTree,p=e.geometry.index,f=e.geometry.attributes.position,u=t.ids,g=t.intersectionSet;for(let y=0,w=u.length;y<w;y++){const x=u[y],v=a===-1?0:h[x]+a,b=3*x,D=c.getX(b+0),T=c.getX(b+1),k=c.getX(b+2);zt.a.fromBufferAttribute(d,D).applyMatrix4(wt),zt.b.fromBufferAttribute(d,T).applyMatrix4(wt),zt.c.fromBufferAttribute(d,k).applyMatrix4(wt),s.reset(),s.initialize(zt);const P=g[x];for(let z=0,C=P.length;z<C;z++){const E=3*P[z],M=p.getX(E+0),B=p.getX(E+1),V=p.getX(E+2);bi.a.fromBufferAttribute(f,M),bi.b.fromBufferAttribute(f,B),bi.c.fromBufferAttribute(f,V),s.splitByTriangle(bi)}const I=s.triangles;for(let z=0,C=I.length;z<C;z++){const E=I[z],M=s.coplanarTriangleUsed?Xu(E,m):Eo(E,m);Ye.length=0,Nt.length=0;for(let B=0,V=n.length;B<V;B++){const U=Bo(n[B],M,i);U!==ks&&(Nt.push(U),Ye.push(r[B].getGroupAttrSet(v)))}if(Ye.length!==0){zt.getBarycoord(E.a,_i.a),zt.getBarycoord(E.b,_i.b),zt.getBarycoord(E.c,_i.c);for(let B=0,V=Ye.length;B<V;B++){const U=Ye[B],G=Nt[B]===vn;qu(x,_i,o.geometry,o.matrixWorld,vi,U,l!==G)}}}}return u.length}function No(o,e,t,n,i,s,r=0){const a=o.matrixWorld.determinant()<0;wt.copy(e.matrixWorld).invert().multiply(o.matrixWorld),vi.getNormalMatrix(o.matrixWorld).multiplyScalar(a?-1:1);const l=e.geometry.boundsTree,h=o.geometry.groupIndices,c=o.geometry.index,d=o.geometry.attributes,m=d.position,p=[],f=o.geometry.halfEdges,u=new Set,g=ws(o.geometry);for(let y=0,w=g;y<w;y++)y in t.intersectionSet||u.add(y);for(;u.size>0;){const y=Hu(u);u.delete(y),p.push(y);const w=3*y,x=c.getX(w+0),v=c.getX(w+1),b=c.getX(w+2);xt.a.fromBufferAttribute(m,x).applyMatrix4(wt),xt.b.fromBufferAttribute(m,v).applyMatrix4(wt),xt.c.fromBufferAttribute(m,b).applyMatrix4(wt);const D=Eo(xt,l);Nt.length=0,Ye.length=0;for(let T=0,k=n.length;T<k;T++){const P=Bo(n[T],D,i);P!==ks&&(Nt.push(P),Ye.push(s[T]))}for(;p.length>0;){const T=p.pop();for(let k=0;k<3;k++){const P=f.getSiblingTriangleIndex(T,k);P!==-1&&u.has(P)&&(p.push(P),u.delete(P))}if(Ye.length!==0){const k=3*T,P=c.getX(k+0),I=c.getX(k+1),z=c.getX(k+2),C=r===-1?0:h[T]+r;if(xt.a.fromBufferAttribute(m,P),xt.b.fromBufferAttribute(m,I),xt.c.fromBufferAttribute(m,z),!yt(xt))for(let E=0,M=Ye.length;E<M;E++){const B=Nt[E],V=Ye[E].getGroupAttrSet(C),U=B===vn;Ku(P,I,z,d,o.matrixWorld,vi,V,U!==a)}}}}}function Qu(o){for(let e=0;e<o.length-1;e++){const t=o[e],n=o[e+1];if(t.materialIndex===n.materialIndex){const i=t.start,s=n.start+n.count;n.start=i,n.count=s-i,o.splice(e,1),e--}}}function ed(o,e,t,n){t.clear();const i=o.attributes;for(let s=0,r=n.length;s<r;s++){const a=n[s],l=i[a];t.initializeArray(a,l.array.constructor,l.itemSize,l.normalized)}for(const s in t.attributes)n.includes(s)||t.delete(s);for(const s in e.attributes)n.includes(s)||(e.deleteAttribute(s),e.dispose())}function td(o,e,t){let n=!1,i=-1;const s=o.attributes,r=e.groupAttributes[0];for(const l in r){const h=e.getTotalLength(l),c=e.getType(l),d=e.getItemSize(l),m=e.getNormalized(l);let p=s[l];(!p||p.array.length<h)&&(p=new _.BufferAttribute(new c(h),d,m),o.setAttribute(l,p),n=!0);let f=0;for(let u=0,g=Math.min(t.length,e.groupCount);u<g;u++){const y=t[u].index,{array:w,type:x,length:v}=e.groupAttributes[y][l],b=new x(w.buffer,0,v);p.array.set(b,f),f+=b.length}p.needsUpdate=!0,i=h/p.itemSize}if(o.index){const l=o.index.array;if(l.length<i)o.index=null,n=!0;else for(let h=0,c=l.length;h<c;h++)l[h]=h}let a=0;o.clearGroups();for(let l=0,h=Math.min(t.length,e.groupCount);l<h;l++){const{index:c,materialIndex:d}=t[l],m=e.getCount(c);m!==0&&(o.addGroup(a,m,d),a+=m)}o.setDrawRange(0,i),o.boundsTree=null,n&&o.dispose()}function Ro(o,e){let t=e;return Array.isArray(e)||(t=[],o.forEach(n=>{t[n.materialIndex]=e})),t}class nd{constructor(){this.triangleSplitter=new zu,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new $u}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,n,i=new fi){let s=!0;if(Array.isArray(n)||(n=[n]),Array.isArray(i)||(i=[i],s=!1),i.length!==n.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:r,attributeData:a,attributes:l,useGroups:h,consolidateGroups:c,debug:d}=this;for(;a.length<i.length;)a.push(new Ru);i.forEach((y,w)=>{ed(e.geometry,y.geometry,a[w],l)}),d.init(),Ju(e,t,n,r,a,{useGroups:h}),d.complete();const m=this.getGroupRanges(e.geometry),p=Ro(m,e.material),f=this.getGroupRanges(t.geometry),u=Ro(f,t.material);f.forEach(y=>y.materialIndex+=p.length);let g=[...m,...f].map((y,w)=>({...y,index:w}));if(h){const y=[...p,...u];c&&(g=g.map(x=>{const v=y[x.materialIndex];return x.materialIndex=y.indexOf(v),x}).sort((x,v)=>x.materialIndex-v.materialIndex));const w=[];for(let x=0,v=y.length;x<v;x++){let b=!1;for(let D=0,T=g.length;D<T;D++){const k=g[D];k.materialIndex===x&&(b=!0,k.materialIndex=w.length)}b&&w.push(y[x])}i.forEach(x=>{x.material=w})}else g=[{start:0,count:1/0,index:0,materialIndex:0}],i.forEach(y=>{y.material=p[0]});return i.forEach((y,w)=>{const x=y.geometry;td(x,a[w],g),c&&Qu(x.groups)}),s?i:i[0]}evaluateHierarchy(e,t=new fi){e.updateMatrixWorld(!0);const n=(s,r)=>{const a=s.children;for(let l=0,h=a.length;l<h;l++){const c=a[l];c.isOperationGroup?n(c,r):r(c)}},i=s=>{const r=s.children;let a=!1;for(let h=0,c=r.length;h<c;h++){const d=r[h];a=i(d)||a}const l=s.isDirty();if(l&&s.markUpdated(),a&&!s.isOperationGroup){let h;return n(s,c=>{h?h=this.evaluate(h,c,c.operation):h=this.evaluate(s,c,c.operation)}),s._cachedGeometry=h.geometry,s._cachedMaterials=h.material,!0}else return a||l};return i(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class id{engine;planeObjects=[];planes=[];isActive=!1;evaluator;geometryCache=new Map;sectionMeshes=new Map;planeGroup;planeSize=1e3;sourceMeshes=new Map;planeThickness=.01;updateThrottleTime=100;lastUpdateTime=0;pendingUpdate=!1;updateTimer=null;cacheExpireTime=3e4;planeStates=new Map;constructor(e,t={}){this.engine=e,this.evaluator=new nd,this.planeGroup=new S.Group,this.planeGroup.name="CSG_ClippingPlanes_Optimized",t.updateThrottleTime!==void 0&&(this.updateThrottleTime=t.updateThrottleTime),t.cacheExpireTime!==void 0&&(this.cacheExpireTime=t.cacheExpireTime),t.planeThickness!==void 0&&(this.planeThickness=t.planeThickness),this.evaluator.attributes=["position","normal"],this.evaluator.useGroups=!1}init(){this.calculateSceneSize(),this.engine.scene.add(this.planeGroup),this.planes.forEach((e,t)=>{const n=this.createEmptySectionMesh(e,t);this.planeGroup.add(n),this.sectionMeshes.set(`plane_${t}`,n),this.planeObjects.push(n),this.planeStates.set(t,{constant:e.constant,normal:e.normal.clone()})})}createEmptySectionMesh(e,t){const n=new S.BufferGeometry,i=new S.MeshStandardMaterial({color:new S.Color(33023),metalness:.1,roughness:.75,side:S.DoubleSide,depthWrite:!0,depthTest:!0,clippingPlanes:this.planes.filter((r,a)=>a!==t)}),s=new S.Mesh(n,i);return s.name=`CSG_Section_Optimized_${t}`,s.visible=!1,s.renderOrder=t+1,s}active(){this.isActive=!0,this.requestUpdate(),this.planeObjects.forEach(e=>{e.visible=!0})}disActive(){this.isActive=!1,this.planeObjects.forEach(e=>{e.visible=!1}),this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null)}setSourceMeshes(e){this.sourceMeshes.clear(),e.forEach(t=>{const n=t.uuid;this.sourceMeshes.set(n,t)}),this.isActive&&this.requestUpdate()}addSourceMesh(e){const t=e.uuid;this.sourceMeshes.has(t)||(this.sourceMeshes.set(t,e),this.isActive&&this.requestUpdate())}removeSourceMesh(e){const t=e.uuid;this.sourceMeshes.delete(t)&&(this.clearMeshCache(t),this.isActive&&this.requestUpdate())}requestUpdate(){if(!this.isActive)return;const e=Date.now(),t=e-this.lastUpdateTime;t>=this.updateThrottleTime?(this.lastUpdateTime=e,this.pendingUpdate=!1):(this.pendingUpdate=!0,this.updateTimer&&clearTimeout(this.updateTimer),this.updateTimer=setTimeout(()=>{this.pendingUpdate&&this.isActive&&(this.lastUpdateTime=Date.now(),this.pendingUpdate=!1),this.updateTimer=null},this.updateThrottleTime-t))}updateAllSections(){this.isActive&&(this.planes.forEach((e,t)=>{if(Math.abs(e.constant)<99999)this.hasPlaneChanged(t,e)&&(this.updateSection(e,t),this.updatePlaneState(t,e));else{const n=this.sectionMeshes.get(`plane_${t}`);n&&(n.visible=!1)}}),this.cleanExpiredCache())}hasPlaneChanged(e,t){const n=this.planeStates.get(e);if(!n)return!0;const i=Math.abs(n.constant-t.constant)>1e-4,s=!n.normal.equals(t.normal);return i||s}updatePlaneState(e,t){this.planeStates.set(e,{constant:t.constant,normal:t.normal.clone()})}getPlaneHash(e){const t=e.normal,n=e.constant;return`${t.x.toFixed(4)}_${t.y.toFixed(4)}_${t.z.toFixed(4)}_${n.toFixed(4)}`}getCacheKey(e,t){return`${e}_plane_${t}`}updateSection(e,t){const n=this.sectionMeshes.get(`plane_${t}`);if(!n)return;const i=this.getPlaneHash(e),s=[];if(this.sourceMeshes.forEach((r,a)=>{const l=this.getCacheKey(a,t),h=this.geometryCache.get(l);if(h&&h.planeHash===i)s.push(h.geometry.clone()),h.timestamp=Date.now();else try{const c=this.createPlaneBrush(e),d=new fi(r.geometry);r.updateMatrixWorld(!0),d.matrix.copy(r.matrixWorld),d.updateMatrixWorld();const m=this.evaluator.evaluate(c,d,So);m&&m.geometry.attributes.position.count>0?(s.push(m.geometry),this.geometryCache.set(l,{geometry:m.geometry.clone(),planeHash:i,timestamp:Date.now()})):this.geometryCache.delete(l)}catch(c){console.warn(`CSG intersection failed for mesh ${a}:`,c)}}),s.length>0){const r=this.mergeGeometries(s);n.geometry&&n.geometry.dispose(),n.geometry=r,n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.scale.set(1,1,1),n.updateMatrixWorld()}else n.visible=!1;s.forEach(r=>r.dispose())}clearMeshCache(e){const t=[];this.geometryCache.forEach((n,i)=>{i.startsWith(e)&&(n.geometry.dispose(),t.push(i))}),t.forEach(n=>this.geometryCache.delete(n))}cleanExpiredCache(){const e=Date.now(),t=[];this.geometryCache.forEach((n,i)=>{e-n.timestamp>this.cacheExpireTime&&(n.geometry.dispose(),t.push(i))}),t.forEach(n=>this.geometryCache.delete(n))}clearAllCache(){this.geometryCache.forEach(e=>{e.geometry.dispose()}),this.geometryCache.clear()}createPlaneBrush(e){const t=new S.BoxGeometry(this.planeSize,this.planeThickness,this.planeSize);t.translate(0,e.constant,0),t.applyQuaternion(new S.Quaternion().setFromUnitVectors(new S.Vector3(0,-1,0),e.normal));const n=new S.Mesh(t),i=new fi(t);return i.matrix.copy(n.matrixWorld),i.updateMatrixWorld(),i}mergeGeometries(e){if(e.length===1)return e[0].clone();const t=new S.BufferGeometry,n=[],i=[],s=[];let r=0;return e.forEach(a=>{const l=a.attributes.position,h=a.attributes.normal;for(let c=0;c<l.count;c++)n.push(l.getX(c),l.getY(c),l.getZ(c));if(h)for(let c=0;c<h.count;c++)i.push(h.getX(c),h.getY(c),h.getZ(c));if(a.index)for(let c=0;c<a.index.count;c++)s.push(a.index.getX(c)+r);r+=l.count}),t.setAttribute("position",new S.Float32BufferAttribute(n,3)),i.length>0?t.setAttribute("normal",new S.Float32BufferAttribute(i,3)):t.computeVertexNormals(),s.length>0&&t.setIndex(s),t}calculateSceneSize(){const e=new S.Box3;if(this.engine.scene.traverse(t=>{if(t.isMesh&&t.geometry){const n=new S.Box3().setFromObject(t);e.union(n)}}),e.isEmpty())this.planeSize=1e3;else{const t=e.getSize(new S.Vector3),n=Math.max(t.x,t.y,t.z);this.planeSize=n*3}}update(){this.isActive&&this.pendingUpdate&&!this.updateTimer&&this.requestUpdate()}dispose(){this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null),this.clearAllCache(),this.planeObjects.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(t=>t.dispose()):e.material.dispose())}),this.sectionMeshes.clear(),this.planeObjects=[],this.sourceMeshes.clear(),this.planeGroup.parent&&this.planeGroup.parent.remove(this.planeGroup)}setSectionColor(e){this.planeObjects.forEach(t=>{t.material instanceof S.MeshStandardMaterial&&t.material.color.set(e)})}getCacheStats(){return{cacheSize:this.geometryCache.size,sourceMeshCount:this.sourceMeshes.size,sectionMeshCount:this.sectionMeshes.size}}setPlaneThickness(e){if(e<=0){console.warn("Plane thickness must be positive");return}this.planeThickness=e,this.clearAllCache(),this.isActive&&this.requestUpdate()}getPlaneThickness(){return this.planeThickness}showSections(){this.sectionMeshes.forEach(e=>{e.geometry?.attributes.position?.count&&e.geometry.attributes.position.count>0&&(e.visible=!0)})}hideSections(){this.sectionMeshes.forEach(e=>{e.visible=!1})}showSection(){this.planeGroup.visible=!0}hideSection(){this.planeGroup.visible=!1}toggleSectionsVisibility(){let e=!1;return this.sectionMeshes.forEach(t=>{t.visible&&(e=!0)}),e?(this.hideSections(),!1):(this.showSections(),!0)}toggleSectionVisibility(e){const t=this.sectionMeshes.get(`plane_${e}`);return t?(t.visible=!t.visible,t.visible):!1}}class sd{engine;isActive=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;csgClipping=null;useCsgClipping=!1;constructor(e,t){this.engine=e,this.meshs=[],t?.useCsgClipping!==void 0&&(this.useCsgClipping=t.useCsgClipping),this.useCsgClipping&&this.initCsgClipping()}initCsgClipping(){this.csgClipping=new id(this.engine,{updateThrottleTime:150,cacheExpireTime:45e3}),this.csgClipping.planes=this.engine.sectionPlane,this.csgClipping.init()}active(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0,this.init())}disActive(){this.init(),this.isActive=!1,this.engine.handelBehaved.disActive(),this.csgClipping&&this.csgClipping.disActive(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})}),this.engine.interactionModule.init(),this.engine.interactionModule.active()}disabled(){this.isActive=!1,this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(){let e=this.engine.octreeBox.getBoundingBox();this.maxBox=JSON.parse(JSON.stringify(e)),this.box=e,this.updata_face(e)}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box)}setBox(e){this.box=e,this.updata_face(e)}reverseBox(){}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0)if(this.pickPoint=t[0].point,this.pickNormal=t[0].face.normal,this.engine.controls.enabled=!1,this.pickMesh=t[0].object,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const n=new S.Plane;n.setFromNormalAndCoplanarPoint(new S.Vector3(0,1,0),this.pickPoint),this.plane=n}else{let n=new S.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const i=new S.Plane;i.setFromNormalAndCoplanarPoint(n.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=i}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.engine.controls.enabled=!0,this.csgClipping&&this.isActive}handleMouseMove(e){this.meshs.forEach(n=>{n.material.opacity=0});const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const n=new S.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,n)){let i=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());this.pickMesh.name=="前"||this.pickMesh.name=="左"||this.pickMesh.name=="底"?this.box.min=this.box_.min.clone().add(this.pickNormal.clone().setLength(i)):this.box.max=this.box_.max.clone().add(this.pickNormal.clone().setLength(i)),this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){let e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,n=this.maxBox.max.z-this.maxBox.min.z,i=(this.box.min.x-this.maxBox.min.x)/e*100,s=(this.box.max.x-this.maxBox.min.x)/e*100,r=(this.box.min.y-this.maxBox.min.y)/t*100,a=(this.box.max.y-this.maxBox.min.y)/t*100,l=(this.box.min.z-this.maxBox.min.z)/n*100,h=(this.box.max.z-this.maxBox.min.z)/n*100;i<0&&(i=0),s<0&&(s=0),r<0&&(r=0),a<0&&(a=0),l<0&&(l=0),h<0&&(h=0),i>100&&(i=100),s>100&&(s=100),r>100&&(r=100),a>100&&(a=100),l>100&&(l=100),h>100&&(h=100);let c={x:{min:i,max:s},y:{min:r,max:a},z:{min:l,max:h}};this.engine.events.trigger(_e.SectionMove,c)}updata_face(e){let t=this,n=[new S.Vector3(e.min.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.min.z),new S.Vector3(e.min.x,e.max.y,e.min.z)],i=[new S.Vector3(e.min.x,e.min.y,e.max.z),new S.Vector3(e.max.x,e.min.y,e.max.z),new S.Vector3(e.max.x,e.max.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.max.z)],s=[new S.Vector3(e.max.x,e.min.y,e.max.z),new S.Vector3(e.max.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.max.z)],r=[new S.Vector3(e.min.x,e.min.y,e.min.z),new S.Vector3(e.min.x,e.min.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.min.z)],a=[new S.Vector3(e.min.x,e.max.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.max.z)],l=[new S.Vector3(e.min.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.min.y,e.max.z),new S.Vector3(e.min.x,e.min.y,e.max.z)];h(n,new S.Vector3(0,0,-1),"前"),h(i,new S.Vector3(0,0,1),"后"),h(s,new S.Vector3(1,0,0),"右"),h(r,new S.Vector3(-1,0,0),"左"),h(a,new S.Vector3(0,1,0),"顶"),h(l,new S.Vector3(0,-1,0),"底");function h(c,d,m){const p=new S.BufferGeometry,f=new Float32Array([c[0].x,c[0].y,c[0].z,c[1].x,c[1].y,c[1].z,c[2].x,c[2].y,c[2].z,c[3].x,c[3].y,c[3].z]),u=[0,1,2,0,2,3];p.setAttribute("position",new S.BufferAttribute(f,3)),p.setIndex(u);let g=t.engine.scene.children.find(D=>D.type=="Group"&&D.name=="ClippingBox");g==null&&(g=new S.Group,g.name="ClippingBox",t.engine.scene.add(g));let y=t.meshs.find(D=>D.name==m);if(y==null){const D=new S.MeshBasicMaterial({color:65280,transparent:!0,opacity:0,side:S.DoubleSide});D.polygonOffset=!0,D.polygonOffsetFactor=1,D.polygonOffsetUnits=4;const T=new S.Mesh(p,D);T.normal=d,T.name=m,g.add(T),t.meshs.push(T)}else y.geometry=p;const w=new Float32Array([c[0].x,c[0].y,c[0].z,c[1].x,c[1].y,c[1].z,c[2].x,c[2].y,c[2].z,c[3].x,c[3].y,c[3].z,c[0].x,c[0].y,c[0].z]);let x=new S.LineBasicMaterial({color:255}),v=new S.BufferGeometry;v.setAttribute("position",new S.BufferAttribute(w,3));let b=t.meshs.find(D=>D.name==m+"Line");b==null&&(b=new S.Line(v,x),b.name=m+"Line",g.add(b),t.meshs.push(b)),b.geometry=v,b.material=x,m=="前"||m=="左"||m=="底"?t.engine.sectionPlane.find(D=>D.name==m).setFromNormalAndCoplanarPoint(d.clone().setLength(-1),e.min):t.engine.sectionPlane.find(D=>D.name==m).setFromNormalAndCoplanarPoint(d.clone().setLength(-1),e.max),t.engine.scene.children.filter(D=>D.type=="Mesh"&&D.url).forEach(D=>{D.material&&Array.isArray(D.material)?D.material.forEach(T=>{T.clippingPlanes=t.engine.sectionPlane}):D.material.clippingPlanes=t.engine.sectionPlane})}}}class rd{engine;isActive=!1;isDrag=!1;meshs=[];box;pickPoint;pickNormal;pickMesh;box_;plane;angleX=0;angleY=0;angleZ=0;direction=1;normal=new S.Vector3(0,0,1);distance=0;center=null;current_center=null;constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.engine.handelBehaved.init(this),this.engine.handelBehaved.active();let e=this;e.engine.scene.children.filter(t=>t.type=="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(n=>{n.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(n=>n.name=="face"),t)}),this.init()}disActive(){this.init(),this.isActive=!1,this.engine.handelBehaved.disActive();const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(n=>{n.name.includes("face")&&(n.visible=!1)})})}init(){let e=this.engine.octreeBox.getBoundingBox();this.box=e,this.updata_face(0)}disabled(){this.isActive=!1,this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,n){this.angleX=e,this.angleY=t,this.angleZ=n,this.normal=new S.Vector3(0,1,0).applyAxisAngle(new S.Vector3(1,0,0),e).applyAxisAngle(new S.Vector3(0,0,1),t).applyAxisAngle(new S.Vector3(0,1,0),n),this.normal.normalize(),this.updata_face(0)}setFaceNormal(e,t=0){this.normal=e,this.distance=t,this.updata_face(t)}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance)}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){let t=this,n=t.engine.scene.children.find(P=>P.type=="Group"&&P.name=="ClippingBox");n==null&&(n=new S.Group,n.name="ClippingBox",t.engine.scene.add(n));let i=new S.Vector3(1,0,0),s=new S.Vector3(0,1,0),r=new S.Vector3(0,0,1),a,l,h=this.normal.clone().normalize(),c=Math.abs(h.dot(i)),d=Math.abs(h.dot(s)),m=Math.abs(h.dot(r));c<=d&&c<=m?a=i:d<=c&&d<=m?a=s:a=r,a=a.clone().sub(h.clone().multiplyScalar(a.dot(h))).normalize(),l=new S.Vector3().crossVectors(h,a).normalize();let p=null;this.center==null?(p=new S.Vector3((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),this.center=p.clone()):p=this.center.clone();let f=this.box.max.x-this.box.min.x,u=this.box.max.y-this.box.min.y,g=this.box.max.z-this.box.min.z,y=Math.max(Math.abs(a.x)*f,Math.abs(a.y)*u,Math.abs(a.z)*g),w=Math.max(Math.abs(l.x)*f,Math.abs(l.y)*u,Math.abs(l.z)*g),x=p.clone().add(a.clone().multiplyScalar(-y/2)).add(l.clone().multiplyScalar(-w/2)),v=p.clone().add(a.clone().multiplyScalar(y/2)).add(l.clone().multiplyScalar(-w/2)),b=p.clone().add(a.clone().multiplyScalar(y/2)).add(l.clone().multiplyScalar(w/2)),D=p.clone().add(a.clone().multiplyScalar(-y/2)).add(l.clone().multiplyScalar(w/2));x.add(h.clone().multiplyScalar(e)),v.add(h.clone().multiplyScalar(e)),b.add(h.clone().multiplyScalar(e)),D.add(h.clone().multiplyScalar(e)),this.current_center=p.clone().add(h.clone().multiplyScalar(e)),k([x,v,b,D],h,"face");function k(P,I,z){const C=new S.BufferGeometry,E=new Float32Array([P[0].x,P[0].y,P[0].z,P[1].x,P[1].y,P[1].z,P[2].x,P[2].y,P[2].z,P[3].x,P[3].y,P[3].z]),M=[0,1,2,0,2,3];C.setAttribute("position",new S.BufferAttribute(E,3)),C.setIndex(M);let B=t.meshs.find($=>$.name==z);if(B==null){const $=new S.MeshBasicMaterial({color:65280,transparent:!0,opacity:.02,side:S.DoubleSide});$.polygonOffset=!0,$.polygonOffsetFactor=1,$.polygonOffsetUnits=4;const F=new S.Mesh(C,$);F.normal=I,F.name=z,n.add(F),t.meshs.push(F)}else B.geometry=C;const V=new Float32Array([P[0].x,P[0].y,P[0].z,P[1].x,P[1].y,P[1].z,P[2].x,P[2].y,P[2].z,P[3].x,P[3].y,P[3].z,P[0].x,P[0].y,P[0].z]);let U=new S.LineBasicMaterial({color:255}),H=new S.BufferGeometry;H.setAttribute("position",new S.BufferAttribute(V,3));let G=t.meshs.find($=>$.name==z+"Line");G==null&&(G=new S.Line(H,U),G.name=z+"Line",n.add(G),t.meshs.push(G)),G.geometry=H,G.material=U,t.engine.sectionPlane.find($=>$.name==z).setFromNormalAndCoplanarPoint(I.clone().setLength(t.direction),P[0])}}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0)if(this.pickPoint=t[0].point,this.pickNormal=t[0].face.normal,this.engine.controls.enabled=!1,this.pickMesh=t[0].object,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.center=this.current_center.clone(),this.pickNormal.y==0){const n=new S.Plane;n.setFromNormalAndCoplanarPoint(new S.Vector3(0,1,0),this.pickPoint),this.plane=n}else{let n=new S.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const i=new S.Plane;i.setFromNormalAndCoplanarPoint(n.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=i}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.engine.controls.enabled=!0}handleMouseMove(e){this.meshs.forEach(n=>{n.material.opacity=0});const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const n=new S.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,n)){let i=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());this.distance=i,this.updata_face(this.distance)}}}}class od{engine;callback_;constructor(e){this.engine=e}init(){this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){let t=e.catch.normal;this.engine.handelBehaved.disActive(),this.callback_({dir:t,position:e.catch.point})}}class ad{engine;sectionBox;sectionFace;clippingStencil;currentClippingMode="";constructor(e){this.engine=e;let t=new S.Plane(new S.Vector3(0,0,1),1e5);t.name="前";let n=new S.Plane(new S.Vector3(0,0,1),1e5);n.name="左";let i=new S.Plane(new S.Vector3(0,0,1),1e5);i.name="后";let s=new S.Plane(new S.Vector3(0,0,1),1e5);s.name="右";let r=new S.Plane(new S.Vector3(0,0,1),1e5);r.name="顶";let a=new S.Plane(new S.Vector3(0,0,1),1e5);a.name="底";let l=new S.Plane(new S.Vector3(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,n,i,s,r,a,l]}init(){this.sectionBox=new sd(this.engine),this.sectionFace=new rd(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}clippingModel(e){let t=[];e.forEach(s=>{let r=this.engine.models.find(a=>a.url===s.url);s.ids.forEach(a=>{r.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let n=i(t);this.sectionBox.setBox(n);function i(s){let r=new S.Vector3(1e8,1e9,1e10),a=new S.Vector3(-1e8,-1e9,-1e10);return s.forEach(l=>{l.min.x<r.x&&(r.x=l.min.x),l.min.y<r.y&&(r.y=l.min.y),l.min.z<r.z&&(r.z=l.min.z),l.max.x>a.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new S.Box3(r,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,n=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,i=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,s=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,r=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:n,minY:i,minZ:s,maxX:r,maxY:a,maxZ:l})}active(e){if(this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=e,e=="x")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(Math.PI/2,0,0);else if(e=="y")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(0,Math.PI/2,0);else if(e=="z")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(0,0,Math.PI/2);else if(e=="box")this.sectionBox.init(),this.sectionBox.active();else if(e=="face"){let t=new od(this.engine);t.init(),t.catch_face(n=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),s=n.position.clone().sub(i.min.clone().add(i.max.clone()).setLength(.5)),r=new S.Vector3(n.dir.x,n.dir.y,n.dir.z),a=s.dot(r);this.sectionFace.setFaceNormal(n.dir,a)})}}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled()}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=""}}class ld{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class cd{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,n=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(i=>{if(i instanceof S.Mesh){const s=i.geometry;if(s&&s.attributes){const r=s.attributes.position;if(r){const a=r.count;e+=a;let l=0;s.index?l=s.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(i=>{n=n+i.info.modelEdge.length}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:n})}}class hd{engine;constructor(e){this.engine=e}init(){}getModelProperties(e,t,n){let i=this.engine.engineStatus.models.find(r=>r.url===e);i.properties==null&&Dr(e+"/property",r=>{let a=JSON.parse(r);i.properties=a,setTimeout(()=>{s(a,t,n)},100)}),s(i.properties,t,n);function s(r,a,l){let h=[],c=r.models[a.toString()||""],d=c.map(m=>m[0]);d=d.filter((m,p)=>d.indexOf(m)===p),d.forEach(m=>{let p={name:r.categorys[m],children:[]};h.push(p),c.filter(f=>f[0]===m).forEach(f=>{p.children.push({name:r.names[f[1]],value:r.values[f[2]]})})}),l?.({properties:h,materials:h})}}}class ud{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.typeName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.majorName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.levelName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelMappers(e){}getModelMapper(e,t){let n=this.engine.engineStatus.models.find(r=>r.url==e);return n?n.info.modelMapper.find(r=>r.id==t):null}getModelsWithLevelType(e,t,n=null){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(l=>l.levelName===e&&l.typeName===t).forEach(l=>{r.ids.push(Number(l.id))})}),n&&n(i),i}getModelsWithType(e,t=null){let n=[];return this.engine.engineStatus.models.forEach(i=>{let s={url:i.url,ids:[]};n.push(s),i.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{s.ids.push(Number(a.id))})}),t&&t(n),n}getModelsWithLevel(e,t){let n=[];return this.engine.engineStatus.models.forEach(i=>{let s={url:i.url,ids:[]};n.push(s),i.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{s.ids.push(Number(a.id))})}),t&&t(n),n}getModelsWithMajor(e,t){let n=[];return this.engine.engineStatus.models.forEach(i=>{let s={url:i.url,ids:[]};n.push(s),i.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{s.ids.push(Number(a.id))})}),t&&t(n),n}}class dd{engine;isActive=!1;groupEdge;material;modelEdgeLoaded=!1;indexes=new Map;constructor(e){this.engine=e,this.groupEdge=this.engine.scene.getObjectByName("groupEdge"),this.material=new S.LineBasicMaterial({color:"#000000",depthTest:!0,transparent:!0,opacity:.3}),this.material.clippingPlanes=this.engine.sectionPlane}active(){this.isActive=!0,this.groupEdge.visible=!0,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&(Array.isArray(e.material)?e.material:[e.material]).forEach(n=>{n.polygonOffset=!0,n.polygonOffsetFactor=1,n.polygonOffsetUnits=4})}),this.show()}disActive(){this.isActive=!1,this.groupEdge.visible=!1,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&(Array.isArray(e.material)?e.material:[e.material]).forEach(n=>{n.polygonOffset=!1})})}loadModelEdge(){this.modelEdgeLoaded||(this.engine.engineStatus.models.forEach(e=>{if(!this.groupEdge.children.find(n=>n.url==e.url)){let n=e.info,i=[],s=new Map;n.modelEdge.forEach(r=>{let a=i.length;for(let l=0;l<r.points.length;l++)r.points[l].length==2&&(i.push(r.points[l][0].X),i.push(r.points[l][0].Z),i.push(-r.points[l][0].Y),i.push(r.points[l][1].X),i.push(r.points[l][1].Z),i.push(-r.points[l][1].Y));s.set(Number(r.id),[a,i.length,r.points])}),this.indexes.set(e.url,s)}}),this.modelEdgeLoaded=!0)}show(){this.modelEdgeLoaded||this.loadModelEdge(),this.indexes.forEach((e,t)=>{let n=[];e.forEach((r,a)=>{r[2].forEach((l,h)=>{l.length==2&&(n.push(l[0].X),n.push(l[0].Z),n.push(-l[0].Y),n.push(l[1].X),n.push(l[1].Z),n.push(-l[1].Y))})});let i=new S.BufferGeometry;i.setAttribute("position",new S.Float32BufferAttribute(n,3));let s=new S.LineSegments(i,this.material);s.url=t,this.groupEdge.add(s)})}getModelEdge(e,t){let n=this.indexes.get(e);if(n){let i=n.get(t);if(i)return i.slice()}return null}hideModelEdge(e,t){let n=this.indexes.get(e);if(n){let i=n.get(t);if(i){let[s,r,a]=i,l=this.groupEdge.children.find(h=>h.url==e);if(l){let h=l.geometry.attributes.position.array;for(let c=s;c<r;c++)h[c]=NaN;l.geometry.attributes.position.needsUpdate=!0}}}}showModelEdge(e,t){let n=this.indexes.get(e);if(n){let i=n.get(t);if(i){let[s,r,a]=i,l=this.groupEdge.children.find(h=>h.url==e);if(l){let h=l.geometry.attributes.position.array,c=0;for(let d=s;d<r;d+=3){const m=Math.floor(c/6),p=c%6>=3;if(a[m]&&a[m].length===2){const f=p?a[m][1]:a[m][0];h[d]=f.X,h[d+1]=f.Z,h[d+2]=-f.Y}c+=3}l.geometry.attributes.position.needsUpdate=!0}}}}}class fd{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeout);try{const i=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(n),!i.ok){const r=await i.json().catch(()=>({}));throw new Error(`API请求失败 (${i.status}): ${r.error?.message||r.message||i.statusText}`)}return(await i.json()).choices?.[0]?.message?.content||""}catch(i){throw clearTimeout(n),i.name==="AbortError"?new Error("请求超时,请重试"):i.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查:
971
+ `;continue}if((V=B.match(I))&&(M.gamma=parseFloat(V[1])),(V=B.match(z))&&(M.exposure=parseFloat(V[1])),(V=B.match(C))&&(M.valid|=2,M.format=V[1]),(V=B.match(E))&&(M.valid|=4,M.height=parseInt(V[1],10),M.width=parseInt(V[2],10)),M.valid&2&&M.valid&4)break}return M.valid&2||r(3,"missing format specifier"),M.valid&4||r(3,"missing image size specifier"),M},p=function(k,P,I){const z=P;if(z<8||z>32767||k[0]!==2||k[1]!==2||k[2]&128)return new Uint8Array(k);z!==(k[2]<<8|k[3])&&r(3,"wrong scanline width");const C=new Uint8Array(4*P*I);C.length||r(4,"unable to allocate buffer space");let E=0,M=0;const B=4*z,V=new Uint8Array(4),U=new Uint8Array(B);let H=I;for(;H>0&&M<k.byteLength;){M+4>k.byteLength&&r(1),V[0]=k[M++],V[1]=k[M++],V[2]=k[M++],V[3]=k[M++],(V[0]!=2||V[1]!=2||(V[2]<<8|V[3])!=z)&&r(3,"bad rgbe scanline format");let G=0,$;for(;G<B&&M<k.byteLength;){$=k[M++];const N=$>128;if(N&&($-=128),($===0||G+$>B)&&r(3,"bad scanline data"),N){const te=k[M++];for(let ee=0;ee<$;ee++)U[G++]=te}else U.set(k.subarray(M,M+$),G),G+=$,M+=$}const F=z;for(let N=0;N<F;N++){let te=0;C[E]=U[N+te],te+=z,C[E+1]=U[N+te],te+=z,C[E+2]=U[N+te],te+=z,C[E+3]=U[N+te],E+=4}H--}return C},f=function(k,P,I,z){const C=k[P+3],E=Math.pow(2,C-128)/255;I[z+0]=k[P+0]*E,I[z+1]=k[P+1]*E,I[z+2]=k[P+2]*E,I[z+3]=1},u=function(k,P,I,z){const C=k[P+3],E=Math.pow(2,C-128)/255;I[z+0]=_.DataUtils.toHalfFloat(Math.min(k[P+0]*E,65504)),I[z+1]=_.DataUtils.toHalfFloat(Math.min(k[P+1]*E,65504)),I[z+2]=_.DataUtils.toHalfFloat(Math.min(k[P+2]*E,65504)),I[z+3]=_.DataUtils.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const y=m(g),w=y.width,x=y.height,v=p(g.subarray(g.pos),w,x);let b,D,T;switch(this.type){case _.FloatType:T=v.length/4;const k=new Float32Array(T*4);for(let I=0;I<T;I++)f(v,I*4,k,I*4);b=k,D=_.FloatType;break;case _.HalfFloatType:T=v.length/4;const P=new Uint16Array(T*4);for(let I=0;I<T;I++)u(v,I*4,P,I*4);b=P,D=_.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:w,height:x,data:b,header:y.string,gamma:y.gamma,exposure:y.exposure,type:D}}setDataType(e){return this.type=e,this}load(e,t,n,i){function s(r,a){switch(r.type){case _.FloatType:case _.HalfFloatType:r.colorSpace=_.LinearSRGBColorSpace,r.minFilter=_.LinearFilter,r.magFilter=_.LinearFilter,r.generateMipmaps=!1,r.flipY=!0;break}t&&t(r,a)}return super.load(e,s,n,i)}}function Jc(){return new S.Scene}function Qc(o,e){o.appendChild(e.domElement)}function eh(o,e,t){var n=new Object;n.visible=!0;let i=null,s,r,a=[];n.init=function(){s||(h(),c(),d())},n.Hide=function(){s.style.display="none",n.visible=!1},n.Show=function(){s.style.display="block",n.visible=!0},n.RenderScene=function(){n.camera.quaternion.copy(e.camera.quaternion);const f=new S.Vector3(0,0,1).applyQuaternion(e.camera.quaternion);n.camera.position.copy(f.multiplyScalar(100)),n.sceneOrtho.renderer.render(n.sceneOrtho,n.camera)},n.ToggleDirectionView=function(f){var u=new S.Vector3(0,0,0);f=="top"?u=new S.Vector3(0,1,1e-5):f=="down"?u=new S.Vector3(0,-1,1e-5):f=="front"?u=new S.Vector3(0,0,1):f=="left"?u=new S.Vector3(-1,0,0):f=="back"?u=new S.Vector3(0,0,-1):f=="right"?u=new S.Vector3(1,0,0):f=="top_front"?u=new S.Vector3(1,1,0):f=="top_left"?u=new S.Vector3(0,1,-1):f=="top_back"?u=new S.Vector3(-1,1,0):f=="top_right"?u=new S.Vector3(0,1,1):f=="down_front"?u=new S.Vector3(1,-1,0):f=="down_left"?u=new S.Vector3(0,-1,-1):f=="down_back"?u=new S.Vector3(-1,-1,0):f=="down_right"?u=new S.Vector3(0,-1,1):f=="front_right"?u=new S.Vector3(1,0,1):f=="right_back"?u=new S.Vector3(-1,0,1):f=="back_left"?u=new S.Vector3(-1,0,-1):f=="left_front"?u=new S.Vector3(1,0,-1):f=="top_left_front"?u=new S.Vector3(1,1,-1):f=="top_front_right"?u=new S.Vector3(1,1,1):f=="top_right_back"?u=new S.Vector3(-1,1,1):f=="top_back_left"?u=new S.Vector3(-1,1,-1):f=="button_left_front"?u=new S.Vector3(1,-1,-1):f=="button_front_right"?u=new S.Vector3(1,-1,1):f=="button_right_back"?u=new S.Vector3(-1,1,1):f=="button_back_left"&&(u=new S.Vector3(-1,-1,-1));var g=o.octreeBox.getBoundingBox(),y=g.min,w=g.max,x=y.clone().add(w.clone()).multiplyScalar(.5),v=x.clone().add(u.multiplyScalar(1*w.distanceTo(y)));l(e.camera.position,v,o.controls.target.clone(),x)},n.GetCameraPose=function(){var f=e.camera.quaternion,u=e.camera.position,g=o.controls.target,y={quaternion:f,position:u,target:g};return y},n.ReductionCameraPose=function(f,u=1e3,g){var y=new S.Quaternion(f.quaternion._x,f.quaternion._y,f.quaternion._z,f.quaternion._w),w=new S.Vector3(f.position.x,f.position.y,f.position.z),x=new S.Vector3(f.target.x,f.target.y,f.target.z);let v=!1;l(e.camera.position,w,o.controls.target.clone(),x,e.camera.quaternion,y,u,b=>{g&&(v||(g(b),v=!0))}),g&&setTimeout(()=>{v||(g(!0),v=!0)},u+10)},n.CameraGoHome=function(){var f=o.octreeBox.getBoundingBox(),u=f.min.clone().add(f.max.clone()).multiplyScalar(.5);let g=new S.Vector3(1,1,1);var y=f.max.distanceTo(f.min),w=u.clone().add(g.multiplyScalar(y*.5));if(e.camera.isOrthographicCamera){var x=o.container.clientWidth/o.container.clientHeight,v=y*.6;e.camera.left=-v*x,e.camera.right=v*x,e.camera.top=v,e.camera.bottom=-v,e.camera.zoom=1,e.camera.updateProjectionMatrix()}o.controlModule.orbitControls.origin=u.clone(),l(e.camera.position,w,o.controls.target.clone(),u)},n.zoomToBox=function(f){if(e.camera.isOrthographicCamera){let N=function(){i=requestAnimationFrame(N),F.update()};var u=f.min.clone().add(f.max.clone()).multiplyScalar(.5),g=e.camera.position.clone().sub(o.controls.target.clone()).normalize(),y=e.camera.position.distanceTo(o.controls.target),w=u.clone().add(g.multiplyScalar(y)),x=e.camera.zoom,v=new S.Vector3(1,0,0).applyQuaternion(e.camera.quaternion),b=new S.Vector3(0,1,0).applyQuaternion(e.camera.quaternion),D=[new S.Vector3(f.min.x,f.min.y,f.min.z),new S.Vector3(f.max.x,f.min.y,f.min.z),new S.Vector3(f.min.x,f.max.y,f.min.z),new S.Vector3(f.max.x,f.max.y,f.min.z),new S.Vector3(f.min.x,f.min.y,f.max.z),new S.Vector3(f.max.x,f.min.y,f.max.z),new S.Vector3(f.min.x,f.max.y,f.max.z),new S.Vector3(f.max.x,f.max.y,f.max.z)],T=1/0,k=-1/0,P=1/0,I=-1/0;for(var z of D){var C=z.dot(v),E=z.dot(b);T=Math.min(T,C),k=Math.max(k,C),P=Math.min(P,E),I=Math.max(I,E)}var M=(k-T)/2,B=(I-P)/2,V=(e.camera.right-e.camera.left)/2,U=(e.camera.top-e.camera.bottom)/2;x=Math.min(V/M,U/B)*.75;var H=e.camera.position.clone(),G=o.controls.target.clone(),$=e.camera.zoom,F=new hn.Tween({x1:H.x,y1:H.y,z1:H.z,x2:G.x,y2:G.y,z2:G.z,zoom:$}).to({x1:w.x,y1:w.y,z1:w.z,x2:u.x,y2:u.y,z2:u.z,zoom:x},1e3);F.onUpdate(function(te){o.controls&&(e.camera.position.set(te.x1,te.y1,te.z1),o.controls.target.set(te.x2,te.y2,te.z2),e.camera.isOrthographicCamera&&(e.camera.zoom=te.zoom,e.camera.updateProjectionMatrix()),o.controls.auto=!0,o.controls.update(),n.RenderScene())}),F.onComplete(function(){o.controls&&(o.controls.auto=!1,n.RenderScene(),cancelAnimationFrame(i),i=null)}),F.easing(hn.Easing.Cubic.InOut),F.start(),N()}else{var u=f.min.clone().add(f.max.clone()).multiplyScalar(.5);let ee=e.camera.position.clone().sub(o.controls.target.clone()).normalize();var w=u.clone().add(ee.multiplyScalar(2*f.max.distanceTo(f.min)));l(e.camera.position,w,o.controls.target.clone(),u)}};function l(f,u,g,y,w,x,v=1e3,b){var D;w&&x?(D=new hn.Tween({x1:f.x,y1:f.y,z1:f.z,x2:g.x,y2:g.y,z2:g.z,_x:w._x,_y:w._y,_z:w._z,_w:w._w}),D.to({x1:u.x,y1:u.y,z1:u.z,x2:y.x,y2:y.y,z2:y.z,_x:x._x,_y:x._y,_z:x._z,_w:x._w},v)):(D=new hn.Tween({x1:f.x,y1:f.y,z1:f.z,x2:g.x,y2:g.y,z2:g.z}),D.to({x1:u.x,y1:u.y,z1:u.z,x2:y.x,y2:y.y,z2:y.z},v)),D.onUpdate(function(k){o.controls&&(w&&x?(e.camera.quaternion._x=k._x,e.camera.quaternion._y=k._y,e.camera.quaternion._z=k._z,e.camera.quaternion._w=k._w):o.controls.auto=!0,e.camera.position.x=k.x1,e.camera.position.y=k.y1,e.camera.position.z=k.z1,o.controls.target.x=k.x2,o.controls.target.y=k.y2,o.controls.target.z=k.z2,o.controls.update(),n.RenderScene())}),D.onComplete(function(k){o.controls&&(o.controls.auto=!1,n.RenderScene(),b&&b(!0),cancelAnimationFrame(i),i=null)}),D.easing(hn.Easing.Cubic.InOut);function T(k){i=requestAnimationFrame(T),D.update()}D.start(),T()}function h(){s=document.createElement("div"),s.className="ViewCube",t.appendChild(s),r=document.createElement("div"),r.className="viewSettingWrapper",r.innerHTML="...",s.appendChild(r);var f=document.createElement("div");f.className="homeViewWrapper",f.addEventListener("mousedown",function(){console.log("归位"),n.CameraGoHome()}),s.appendChild(f);const u=document.createElement("div");u.className="cameraToggleWrapper",u.title="切换正交/透视视图",u.innerHTML="⊞",u.addEventListener("mousedown",function(v){v.stopPropagation(),console.log("切换视图"),n.ToggleCameraType(),w()}),s.appendChild(u);const g=document.createElement("div");g.className="screenshotWrapper",g.title="截图",g.innerHTML="📷",g.addEventListener("mousedown",function(v){v.stopPropagation(),console.log("截图"),n.TakeScreenshot(),w()}),s.appendChild(g);const y=document.createElement("div");y.className="fullscreenWrapper",y.title="全屏",y.innerHTML="⛶",y.addEventListener("mousedown",function(v){v.stopPropagation(),console.log("全屏"),n.ToggleFullscreen(),w()}),s.appendChild(y),r.addEventListener("mousedown",function(v){v.stopPropagation(),u.classList.contains("show")?(w(),console.log("隐藏功能按钮")):(x(),console.log("显示功能按钮"))});function w(){u.classList.remove("show"),g.classList.remove("show"),y.classList.remove("show")}function x(){u.classList.add("show"),g.classList.add("show"),y.classList.add("show")}}function c(){n.sceneOrtho=Jc();var g=t.clientWidth,y=t.clientWidth,f=g>y?g/y:y/g,u=300;n.camera=new S.OrthographicCamera(u*f/-2,u*f/2,u/2,u/-2,.01,1e4);var g=s.clientWidth,y=s.clientHeight,w=new S.WebGLRenderer({alpha:!0});w.setSize(g,y),w.setClearAlpha(0),n.sceneOrtho.renderer=w;let x=new S.AmbientLight(16777215,.8);n.sceneOrtho.add(x),Qc(s,w)}function d(){const f="/assets/viewcube/";let u=[{label:"右",icon:f+"cn_right.png"},{label:"左",icon:f+"cn_left.png"},{label:"顶",icon:f+"cn_top.png"},{label:"底",icon:f+"cn_bottom.png"},{label:"前",icon:f+"cn_front.png"},{label:"后",icon:f+"cn_back.png"}];var g=[];for(const w of u)g.push(new S.MeshBasicMaterial({color:16777215,map:new S.TextureLoader().load(w.icon)}));new S.MeshLambertMaterial({color:255});var y=new S.Mesh(new S.BoxGeometry(110,110,110),g);n.sceneOrtho.add(y),m(122),s.addEventListener("mousedown",w=>{var x={};x.x=w.offsetX/s.clientWidth*2-1,x.y=-(w.offsetY/s.clientHeight)*2+1;var v=new S.Raycaster;v.setFromCamera(x,n.camera);const b=v.intersectObjects(a,!1);b.length>0&&n.ToggleDirectionView(b[0].object.name)}),s.addEventListener("mousemove",w=>{var x={};x.x=w.offsetX/s.clientWidth*2-1,x.y=-(w.offsetY/s.clientHeight)*2+1;var v=new S.Raycaster;v.setFromCamera(x,n.camera);const b=v.intersectObjects(a,!1);for(var D of a)D.material.opacity=.01;b.length>0&&(b[0].object.material.opacity=.2)})}function m(f){for(var u=f*.5-20,g=[{name:"right",a:30,b:75,c:75,point:new S.Vector3(u,0,0)},{name:"back",a:75,b:75,c:30,point:new S.Vector3(0,0,-u)},{name:"left",a:30,b:75,c:75,point:new S.Vector3(-u,0,0)},{name:"front",a:75,b:75,c:30,point:new S.Vector3(0,0,u)},{name:"top",a:75,b:30,c:75,point:new S.Vector3(0,u,0)},{name:"button",a:75,b:30,c:75,point:new S.Vector3(0,-u,0)}],y=[{name:"top_right_back",a:30,b:30,c:30,point:new S.Vector3(-u,u,u)},{name:"button_front_right",a:30,b:30,c:30,point:new S.Vector3(-u,-u,u)},{name:"top_front_right",a:30,b:30,c:30,point:new S.Vector3(u,u,u)},{name:"button_right_back",a:30,b:30,c:30,point:new S.Vector3(u,-u,u)},{name:"top_back_left",a:30,b:30,c:30,point:new S.Vector3(-u,u,-u)},{name:"button_back_left",a:30,b:30,c:30,point:new S.Vector3(-u,-u,-u)},{name:"top_left_front",a:30,b:30,c:30,point:new S.Vector3(u,u,-u)},{name:"button_left_front",a:30,b:30,c:30,point:new S.Vector3(u,-u,-u)}],w=[{name:"top_front",a:30,b:30,c:75,point:new S.Vector3(u,u,0)},{name:"top_right",a:75,b:30,c:30,point:new S.Vector3(0,u,u)},{name:"top_back",a:30,b:30,c:75,point:new S.Vector3(-u,u,0)},{name:"top_left",a:75,b:30,c:30,point:new S.Vector3(0,u,-u)},{name:"button_front",a:30,b:30,c:75,point:new S.Vector3(u,-u,0)},{name:"button_right",a:75,b:30,c:30,point:new S.Vector3(0,-u,u)},{name:"button_back",a:30,b:30,c:75,point:new S.Vector3(-u,-u,0)},{name:"button_left",a:75,b:30,c:30,point:new S.Vector3(0,-u,-u)},{name:"front_right",a:30,b:75,c:30,point:new S.Vector3(u,0,u)},{name:"right_back",a:30,b:75,c:30,point:new S.Vector3(-u,0,u)},{name:"back_left",a:30,b:75,c:30,point:new S.Vector3(-u,0,-u)},{name:"left_front",a:30,b:75,c:30,point:new S.Vector3(u,0,-u)}],x=0;x<g.length;x++)a.push(p(g[x]));for(var x=0;x<y.length;x++)a.push(p(y[x]));for(var x=0;x<w.length;x++)a.push(p(w[x]))}function p(f){const u=new S.BoxGeometry(f.a,f.b,f.c),g=new S.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.01}),y=new S.Matrix4().makeTranslation(f.point.x,f.point.y,f.point.z);let w=u.applyMatrix4(y),x=new S.Mesh(w,g);return x.name=f.name,n.sceneOrtho.add(x),x}return n.ToggleCameraType=function(){o.cameraModule.switchCurrentCamera()},n.TakeScreenshot=function(){try{if(!o.renderer){console.error("渲染器未初始化");return}o.renderer.render(e,e.camera);const u=o.renderer.domElement.toDataURL("image/png"),g=document.createElement("a"),y=new Date().toISOString().replaceAll(/[:.]/g,"-");g.download=`screenshot_${y}.png`,g.href=u,g.click(),console.log("截图已保存")}catch(f){console.error("截图失败:",f)}},n.ToggleFullscreen=function(){const f=t||document.documentElement;!document.fullscreenElement&&!document.webkitFullscreenElement&&!document.mozFullScreenElement&&!document.msFullscreenElement?(f.requestFullscreen?f.requestFullscreen():f.webkitRequestFullscreen?f.webkitRequestFullscreen():f.mozRequestFullScreen?f.mozRequestFullScreen():f.msRequestFullscreen&&f.msRequestFullscreen(),console.log("已进入全屏模式")):(document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen(),console.log("已退出全屏模式"))},n}class th{engine;cubeTool;constructor(e){this.engine=e}init(){this.cubeTool=eh(this.engine,this.engine.scene,this.engine.container),this.cubeTool.init()}CameraGoHome(){this.cubeTool.CameraGoHome()}zoomToModel(e){this.cubeTool.zoomToBox(e)}hide(){}}function nh(o){let e=new Object;return e.getBoundingBox=function(){let t=o.models,n=new S.Vector3(1e8,1e9,1e10),i=new S.Vector3(-1e8,-1e9,-1e10);t.forEach(d=>{let m=d.boundingBox.min,p=d.boundingBox.max;m.x<n.x&&(n.x=m.x),m.y<n.y&&(n.y=m.y),m.z<n.z&&(n.z=m.z),p.x>i.x&&(i.x=p.x),p.y>i.y&&(i.y=p.y),p.z>i.z&&(i.z=p.z)});let s=Math.min(n.x,i.x),r=Math.min(n.y,i.y),a=Math.min(n.z,i.z),l=Math.max(n.x,i.x),h=Math.max(n.y,i.y),c=Math.max(n.z,i.z);return{min:new S.Vector3(s,r,a),max:new S.Vector3(l,h,c)}},e.rayInterationModel=function(t){let n=[];return o.engineStatus.models.forEach(r=>{r.info.lods.forEach(a=>{let l=a.octreeBox;s(t,l,r)})}),n=n.filter(r=>r instanceof S.Mesh),t.intersectObjects(n,!1);function s(r,a,l){if(a==null)return;let h=new S.Vector3(a.min.X*.3048,a.min.Z*.3048,-a.min.Y*.3048),c=new S.Vector3(a.max.X*.3048,a.max.Z*.3048,-a.max.Y*.3048),d=new S.Vector3(Math.min(h.x,c.X),Math.min(h.y,c.y),Math.min(h.z,c.z)),m=new S.Vector3(Math.max(c.x,h.x),Math.max(c.y,h.y),Math.max(c.z,h.z)),p=new S.Box3(d,m),f=r.ray.intersectsBox(p);if(!(f==null||f==!1))if(a.children==null||a.children.length==0){if(a.elements!=null)for(var u of a.elements){let g=o.engineStatus.hideModels.find(v=>v.url==l.url)?.ids;if(g!=null&&g.includes(u))continue;let y=o.engineStatus.translucentModels.find(v=>v.url==l.url)?.ids;if(y!=null&&y.includes(u))continue;let x=o.models.find(v=>v.url==l.url).nodesMap.get(u);x!=null&&!x.instance&&x.infos.map(b=>b.mesh).forEach(b=>{n.push(b)})}}else{if(a.elements!=null)for(var u of a.elements){let y=o.engineStatus.hideModels.find(b=>b.url==l.url)?.ids;if(y!=null&&y.includes(u))continue;let w=o.engineStatus.translucentModels.find(b=>b.url==l.url)?.ids;if(w!=null&&w.includes(u))continue;let v=o.models.find(b=>b.url==l.url).nodesMap.get(u);v!=null&&!v.instance&&v.infos.map(D=>D.mesh).forEach(D=>{n.push(D)})}for(let g of a.children)s(r,g,l)}}},e}class ih{engine;isDrawing=!1;startPoint=new S.Vector2;endPoint=new S.Vector2;selectionBox=null;worldToScreen=null;boundMouseDown;boundMouseMove;boundMouseUp;boundKeyDown;constructor(e){this.engine=e,this.boundMouseDown=this.onMouseDown.bind(this),this.boundMouseMove=this.onMouseMove.bind(this),this.boundMouseUp=this.onMouseUp.bind(this),this.boundKeyDown=this.onKeyDown.bind(this)}init(){this.createSelectionBoxElement(),this.engine.scene&&this.engine.camera&&this.engine.renderer&&(this.worldToScreen=new ze(this.engine.camera,this.engine.renderer,this.engine.scene))}active(){this.engine.controlModule.disActive();const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.boundMouseDown),e.addEventListener("mousemove",this.boundMouseMove),e.addEventListener("mouseup",this.boundMouseUp),e.style.cursor="crosshair"),window.addEventListener("keydown",this.boundKeyDown)}disActive(){this.engine.controlModule.active();const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.boundMouseDown),e.removeEventListener("mousemove",this.boundMouseMove),e.removeEventListener("mouseup",this.boundMouseUp),e.style.cursor="default"),window.removeEventListener("keydown",this.boundKeyDown),this.isDrawing&&this.endDrawing()}createSelectionBoxElement(){this.selectionBox=document.createElement("div"),this.selectionBox.style.position="absolute",this.selectionBox.style.border="2px dashed #00aaff",this.selectionBox.style.backgroundColor="rgba(0, 170, 255, 0.1)",this.selectionBox.style.pointerEvents="none",this.selectionBox.style.display="none",this.selectionBox.style.zIndex="1000",this.selectionBox.style.boxSizing="border-box";const e=this.engine.renderer?.domElement;e&&e.parentElement&&e.parentElement.appendChild(this.selectionBox)}onMouseDown(e){e.button!==0||!this.engine.renderer?.domElement||(this.startPoint.set(e.offsetX,e.offsetY),this.endPoint.copy(this.startPoint),this.isDrawing=!0,this.selectionBox&&(this.selectionBox.style.display="block",this.updateSelectionBoxUI()),e.preventDefault(),e.stopPropagation())}onMouseMove(e){!this.isDrawing||!this.engine.renderer?.domElement||(this.endPoint.set(e.offsetX,e.offsetY),this.updateSelectionBoxUI(),e.preventDefault(),e.stopPropagation())}onMouseUp(e){this.isDrawing&&(this.endDrawing(),this.performZoom(),e.preventDefault(),e.stopPropagation(),this.disActive())}onKeyDown(e){e.key==="Escape"&&(this.disActive(),e.preventDefault(),e.stopPropagation())}endDrawing(){this.isDrawing&&(this.isDrawing=!1,this.selectionBox&&(this.selectionBox.style.display="none"))}updateSelectionBoxUI(){if(!this.selectionBox||!this.engine.renderer?.domElement)return;const t=Math.min(this.startPoint.x,this.endPoint.x),n=Math.min(this.startPoint.y,this.endPoint.y),i=Math.abs(this.endPoint.x-this.startPoint.x),s=Math.abs(this.endPoint.y-this.startPoint.y);this.selectionBox.style.left=`${t}px`,this.selectionBox.style.top=`${n}px`,this.selectionBox.style.width=`${i}px`,this.selectionBox.style.height=`${s}px`}performZoom(){const e=Math.abs(this.endPoint.x-this.startPoint.x),t=Math.abs(this.endPoint.y-this.startPoint.y);if(e<5||t<5)return;if(!this.worldToScreen){console.warn("RangeScale: 坐标转换工具未初始化");return}const n=Math.min(this.startPoint.x,this.endPoint.x),i=Math.max(this.startPoint.x,this.endPoint.x),s=Math.min(this.startPoint.y,this.endPoint.y),r=Math.max(this.startPoint.y,this.endPoint.y),a=[],l=[{x:n,y:s},{x:i,y:s},{x:i,y:r},{x:n,y:r}];for(const c of l){const d=this.worldToScreen.screenToWorld(c.x,c.y);d&&a.push(d)}if(a.length<3){console.warn("RangeScale: 框选区域未命中模型,无法执行缩放操作");return}if(a.length<3){console.warn("RangeScale: 无法将屏幕区域转换为世界坐标");return}const h=new S.Box3;for(const c of a)h.expandByPoint(c);if(h.isEmpty()){console.warn("RangeScale: 计算得到的包围盒无效");return}this.fitCameraToBoundingBox(h)}fitCameraToBoundingBox(e){const t=this.engine.camera,n=this.engine.controls;if(!t||!n){console.warn("RangeScale: 相机或控制器未初始化");return}const i=new S.Vector3;e.getCenter(i);const s=new S.Vector3;e.getSize(s);const r=Math.max(s.x,s.y,s.z);if(t instanceof S.PerspectiveCamera){const a=t.fov*(Math.PI/180),h=r/(2*Math.tan(a/2))*1.2,c=new S.Vector3;t.getWorldDirection(c);const d=i.clone().sub(t.position);c.dot(d.normalize())<0&&c.negate();const p=i.clone().sub(c.multiplyScalar(h));t.position.copy(p),n.target&&n.target.copy(i),t.lookAt(i),n.update()}else if(t instanceof S.OrthographicCamera){const l=r*1.2,h=this.engine.renderer?.domElement,c=h?h.width/h.height:1;t.left=-l*c/2,t.right=l*c/2,t.top=l/2,t.bottom=-l/2,t.updateProjectionMatrix();const d=new S.Vector3;t.getWorldDirection(d);const m=r*1.5,p=i.clone().sub(d.multiplyScalar(m));t.position.copy(p),n.target&&n.target.copy(i),t.lookAt(i),n.update()}}}class sh{engine;ground=null;constructor(e){this.engine=e}init(){}setStatsVisible(e){this.engine.stats?.dom&&(this.engine.stats.dom.style.display=e?"block":"none")}setAmbientLightIntensity(e){const t=this.engine.scene.children.find(n=>n instanceof S.AmbientLight);t&&(t.intensity=e)}setAmbientLightColor(e){const t=this.engine.scene.children.find(n=>n instanceof S.AmbientLight);t&&t.color.set(e)}setDirectionalLightIntensity(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);t&&(t.intensity=e)}setDirectionalLightColor(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);t&&t.color.set(e)}setShadowQuality(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);if(t?.shadow){const i={low:1024,medium:2048,high:4096,ultra:8192}[e];t.shadow.mapSize.width=i,t.shadow.mapSize.height=i,t.shadow.map?.dispose(),t.shadow.map=null}}setDirectionalLightShadow(e){const t=this.engine.scene.children.find(n=>n instanceof S.DirectionalLight);t&&(t.castShadow=e),this.engine.renderer&&(this.engine.renderer.shadowMap.enabled=e)}setGTAOEnabled(e){if(!this.engine.composerModule?.composer){console.warn("Composer not initialized");return}const t=this.engine.composerModule.composer,n=t.passes.find(i=>i instanceof Ne);if(e)if(n)n.enabled=!0;else{const{width:i,height:s}=this.engine.deviceModule.getContainerSize(),r=new Ne(this.engine.scene,this.engine.camera,i,s);r.output=Ne.OUTPUT.Default,r.blendIntensity=.5,r.updateGtaoMaterial&&r.updateGtaoMaterial({radius:1,distanceExponent:1,thickness:1,scale:1,distanceFallOff:1,screenSpaceRadius:!0});const a=t.passes.findIndex(l=>l.constructor.name==="RenderPass");t.passes.splice(a+1,0,r)}else n&&(n.enabled=!1)}setSceneSaturation(e){if(!this.engine.composerModule?.saturationPass){console.warn("Saturation pass not initialized");return}this.engine.composerModule.saturationPass.uniforms.saturation.value=e}setSceneContrast(e){if(!this.engine.composerModule?.saturationPass){console.warn("Saturation pass not initialized");return}this.engine.composerModule.saturationPass.uniforms.contrast.value=e}setGroundEnabled(e,t){if(e)if(this.ground)this.ground.visible=!0;else{const n=t?.size??100,i=t?.color??8421504,s=t?.opacity??.3,r=new S.PlaneGeometry(n,n),a=new S.MeshStandardMaterial({color:i,transparent:!0,opacity:s,side:S.DoubleSide});this.ground=new S.Mesh(r,a),this.ground.rotation.x=-Math.PI/2,this.ground.position.y=0,this.ground.receiveShadow=!0,this.ground.name="ground",this.engine.scene.add(this.ground)}else this.ground&&(this.ground.visible=!1)}setHDRBackground(e){e?(this.engine.scene.background=e,this.engine.scene.environment=e):(this.engine.scene.background=null,this.engine.scene.environment=null)}}function it(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(o){var e=Math.random()*16|0,t=o=="x"?e:e&3|8;return t.toString(16)})}class st{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Ci(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let n=this.setting.unit,i=n;return t==1?n=="mm"?e=e*1e3:n=="cm"?e=e*100:n=="dm"?e=e*10:n=="m"?e=e*1:n=="km"&&(e=e*.001):t==2&&(n=="mm"?e=e*1e3*1e3:n=="cm"?e=e*100*100:n=="dm"?e=e*10*10:n=="m"?e=e*1*1:n=="km"&&(e=e*.001*.001),i=i+"²"),e.toFixed(this.setting.precision)+" "+i}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight==!0&&(n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let i=e[t][n];i.isSelect==!0&&(i.container.remove(),e[t].splice(n,1))}this.engine.measure.clearAllPoints()}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let i=e[t][n];i.highlight==!0&&(i.container.remove(),e[t].splice(n,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(f=>{p(f)}),this.engine.measure.annotationData.elevationAnnotation.forEach(f=>{m(f)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(f=>{d(f)}),this.engine.measure.annotationData.angleAnnotation.forEach(f=>{l(f)}),this.engine.measure.annotationData.areaAnnotation.forEach(f=>{h(f)}),this.engine.measure.annotationData.slopeAnnotation.forEach(f=>{c(f)});function l(f){if(f.container==null){let T=['<svg class="measureSvg">','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+f.text+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="angle-annotation",f.container.id=f.id,f.container.style.pointerEvents="none",f.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point1),g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point2),y=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point3),w=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;u.x+=w,u.y+=x,g.x+=w,g.y+=x,y.x+=w,y.y+=x;let v=f.container;v.getElementsByTagName("circle")[0].setAttribute("cx",u.x),v.getElementsByTagName("circle")[0].setAttribute("cy",u.y),v.getElementsByTagName("circle")[1].setAttribute("cx",g.x),v.getElementsByTagName("circle")[1].setAttribute("cy",g.y),v.getElementsByTagName("circle")[2].setAttribute("cx",y.x),v.getElementsByTagName("circle")[2].setAttribute("cy",y.y),v.getElementsByTagName("polyline")[0].setAttribute("points",u.x+","+u.y+" "+g.x+","+g.y),v.getElementsByTagName("polyline")[1].setAttribute("points",g.x+","+g.y+" "+y.x+","+y.y);let b=g.x,D=g.y-30;v.getElementsByTagName("rect")[0].setAttribute("x",b-40),v.getElementsByTagName("rect")[0].setAttribute("y",D-12.5),v.getElementsByTagName("text")[0].setAttribute("x",b),v.getElementsByTagName("text")[0].setAttribute("y",D+4),v.getElementsByTagName("text")[0].innerHTML=f.text,v.style.top="0px",v.style.left="0px"}function h(f){if(f.container==null){let k=['<svg class="measureSvg">','<polygon fill="rgba(255, 165, 0, 0.3)" stroke="orange" stroke-width="2" points="" style="opacity: 0.3;"/>','<polyline stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+e.getMeasureText(f.text,2)+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="area-annotation",f.container.id=f.id,f.container.innerHTML=k,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}if(!f.points||f.points.length<3)return;let u=e.engine.reactBoundingClientRect.left,g=e.engine.reactBoundingClientRect.top,y=[],w=0,x=0;for(let k=0;k<f.points.length;k++){let P=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.points[k]);P.x+=u,P.y+=g,y.push(P),w+=P.x,x+=P.y}w=w/y.length,x=x/y.length;let v=y.map(k=>k.x+","+k.y).join(" "),b=f.container;b.getElementsByTagName("polygon")[0].setAttribute("points",v),b.getElementsByTagName("polyline")[0].setAttribute("points",v);let D=w,T=x;b.getElementsByTagName("rect")[0].setAttribute("x",D-40),b.getElementsByTagName("rect")[0].setAttribute("y",T-12.5),b.getElementsByTagName("text")[0].setAttribute("x",D),b.getElementsByTagName("text")[0].setAttribute("y",T+4),b.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(f.text,2),b.style.top="0px",b.style.left="0px"}function c(f){if(f.container==null){let D=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+f.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path d="M0,0 L0,6 L9,3 z" fill="orange" stroke="orange" />',"</marker>","</defs>",'<polyline stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+f.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+f.text+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="slope-annotation",f.container.id=f.id,f.container.innerHTML=D,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point1),g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point2),y=e.engine.reactBoundingClientRect.left,w=e.engine.reactBoundingClientRect.top;u.x+=y,u.y+=w,g.x+=y,g.y+=w;let x=f.container;x.getElementsByTagName("polyline")[0].setAttribute("points",u.x+","+u.y+" "+g.x+","+g.y);let v=(u.x+g.x)/2,b=(u.y+g.y)/2-30;x.getElementsByTagName("rect")[0].setAttribute("x",v-50),x.getElementsByTagName("rect")[0].setAttribute("y",b-12.5),x.getElementsByTagName("text")[0].setAttribute("x",v),x.getElementsByTagName("text")[0].setAttribute("y",b+4),x.getElementsByTagName("text")[0].innerHTML=f.text,x.style.top="0px",x.style.left="0px"}function d(f){if(f.container==null){let T=['<svg class="measureSvg">','<circle cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="40" y="-11" text-anchor="middle" class="measureLabel">X: '+e.getMeasureText(f.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="40" y="25" text-anchor="middle" class="measureLabel">Y: '+e.getMeasureText(-f.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="40" y="51" text-anchor="middle" class="measureLabel">Z: '+e.getMeasureText(f.textY,1)+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="coordinate-annotation",f.container.id=f.id,f.container.style.position="absolute",f.container.style.pointerEvents="none",f.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=f.container,g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point),y=e.engine.reactBoundingClientRect.left,w=e.engine.reactBoundingClientRect.top;g.x+=y,g.y+=w,u.style.top="0px",u.style.left="0px";let x=u.getElementsByTagName("circle")[0];x&&(x.setAttribute("cx",g.x),x.setAttribute("cy",g.y));let v=u.getElementsByTagName("rect"),b=u.getElementsByTagName("text"),D=-55;v[0]&&(v[0].setAttribute("x",g.x+10),v[0].setAttribute("y",g.y+10+D)),b[0]&&(b[0].setAttribute("x",g.x+10+40),b[0].setAttribute("y",g.y+10+16+D)),v[1]&&(v[1].setAttribute("x",g.x+10),v[1].setAttribute("y",g.y+10+30+D)),b[1]&&(b[1].setAttribute("x",g.x+10+40),b[1].setAttribute("y",g.y+10+46+D)),v[2]&&(v[2].setAttribute("x",g.x+10),v[2].setAttribute("y",g.y+10+60+D)),b[2]&&(b[2].setAttribute("x",g.x+10+40),b[2].setAttribute("y",g.y+10+76+D)),b[0]&&(b[0].innerHTML="X: "+e.getMeasureText(f.textX,1)),b[1]&&(b[1].innerHTML="Y: "+e.getMeasureText(-f.textZ,1)),b[2]&&(b[2].innerHTML="Z: "+e.getMeasureText(f.textY,1))}function m(f){if(f.container==null){let x=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+e.getMeasureText(f.text,1)+"</text>",'<polyline stroke="#f99d0b" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");f.container=document.createElement("div"),f.container.className="elevation-annotation",f.container.id=f.id,f.container.style.position="absolute",f.container.style.pointerEvents="none",f.container.innerHTML=x,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=f.container,g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point),y=e.engine.reactBoundingClientRect.left,w=e.engine.reactBoundingClientRect.top;u.style.top=g.y+w-48+"px",u.style.left=g.x+y-16+"px",u.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(f.text,1)}function p(f){if(f.container==null){let v=['<svg class="measureSvg">','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<circle cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="80" height="25" class="measureBack" />','<text x="40" y="16" text-anchor="middle" class="measureLabel">'+e.getMeasureText(f.text,1)+"</text>","</svg>"].join("");f.container=document.createElement("div"),f.container.className="normal-annotation",f.container.id=f.id,f.container.innerHTML=v,e.engine.measure.annotationContainer.appendChild(f.container),f.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),f.container.getElementsByTagName("svg")[0].classList.add("Hight"),f.highlight=!0,e.engine.events.trigger(_e.MeasureClick,f)})}let u=f.container;if(f.point1==null||f.point2==null){u.style.display="none";return}else u.style.display="block";let g=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point1),y=new ze(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(f.point2),w=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;g.x+=w,g.y+=x,y.x+=w,y.y+=x,u.getElementsByTagName("polyline")[0].setAttribute("points",g.x+","+g.y+" "+y.x+","+y.y),u.getElementsByTagName("circle")[0].setAttribute("cx",g.x),u.getElementsByTagName("circle")[0].setAttribute("cy",g.y),u.getElementsByTagName("circle")[1].setAttribute("cx",y.x),u.getElementsByTagName("circle")[1].setAttribute("cy",y.y),u.getElementsByTagName("rect")[0].setAttribute("x",g.x*.5+y.x*.5-40),u.getElementsByTagName("rect")[0].setAttribute("y",g.y*.5+y.y*.5-12.5),u.getElementsByTagName("text")[0].setAttribute("x",g.x*.5+y.x*.5+40-40),u.getElementsByTagName("text")[0].setAttribute("y",g.y*.5+y.y*.5+16-12.5),u.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(f.text,1),u.style.top="0px",u.style.left="0px"}}}class rh{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let i=0;i<e.length;i++){const s=e[i];if(!s)continue;typeof s.updateMatrixWorld=="function"&&s.updateMatrixWorld(!0);const r=new S.Box3().setFromObject(s);!Number.isFinite(r.min.y)||!Number.isFinite(r.max.y)||(r.min.y<t&&(t=r.min.y),r.max.y>n&&(n=r.max.y))}return!Number.isFinite(t)||!Number.isFinite(n)?null:{minY:t,maxY:n}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let s=this.engine.interactionModule.getCatchMeshs(e);var n=this.getMeshesMinMaxY(s);this.catchDir==0?t.set(t.x,n?.minY,t.z):t.set(t.x,n?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.points.push(t);return}let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);i!=null&&(i.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);t==null&&(t={text:null,id:it(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=e.catch;if(this.type=="element"){let i=e.catch.point.clone();i.set(i.x,this.points[0].y,i.z);let s=new S.Raycaster(i.add(new S.Vector3(0,.01,0)),new S.Vector3(0,this.catchDir==0?-1:1,0));n.point=this.points[0];const r=this.engine.octreeBox.rayInterationModel(s);if(r.length===0){t.point2=null;return}t.point1=i,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(_e.MeasureChanged,t)}else{let i=new S.Raycaster(e.catch.point.clone().add(new S.Vector3(0,.01,0)),new S.Vector3(0,this.catchDir==0?-1:1,0));const s=this.engine.octreeBox.rayInterationModel(i);if(s.length===0){t.point2=null;return}t.point1=n.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(_e.MeasureChanged,t)}}}class oh{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);if(n==null)return;n.point2=t.point,n.isSelect=!1,this.points=[],this.engine.events.trigger(_e.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(i=>i.isSelect==!0);n==null&&(n={id:it(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(n)),n.point2=t.point,n.text=n.point1.clone().distanceTo(n.point2.clone())}}}class ah{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);t==null&&(t={text:null,id:it(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=new S.Raycaster(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const i=this.engine.octreeBox.rayInterationModel(n);if(i.length==0){t.point2=null;return}let s=e.catch;t.point1=s.point,t.point2=i[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(_e.MeasureChanged,t)}}class lh{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active(),this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:it(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),t.point=e.catch.point.clone(),t.text=e.catch.point.y}handleMouseClick(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(_e.MeasureChanged,t))}}class ch{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active(),this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:it(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t)),t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,console.log("有在移动")}handleMouseClick(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,this.engine.events.trigger(_e.MeasureChanged,t))}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(_e.MeasureChanged,e))}}class hh{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,n){const i=new S.Vector3().subVectors(e,t),s=new S.Vector3().subVectors(n,t),r=i.length(),a=s.length();if(r===0||a===0)return 0;const h=i.dot(s)/(r*a),c=Math.max(-1,Math.min(1,h));return Math.acos(c)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);if(n==null)return;n.point3=t.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",n.isSelect=!1,n.type="angle",this.points=[],this.engine.events.trigger(_e.MeasureChanged,n)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:it(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}}class uh{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;let t=0;const n=e.length;for(let i=0;i<n;i++){const s=(i+1)%n;t+=e[i].x*e[s].z,t-=e[s].x*e[i].z}return t=Math.abs(t)/2,t}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.push(t.point.clone()),this.points.length>=3){let n=this.engine.measure.annotationData.areaAnnotation.find(i=>i.isSelect==!0);n==null?(n={id:it(),points:this.points.map(i=>i.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n)):(this.points.push(t.point.clone()),n.points=this.points.map(i=>i.clone())),n.area=this.calculateArea(n.points),n.text=n.area,console.log("面积",n.text)}}handleMouseMove(e){if(e.catch!=null&&this.points.length>=2){let t=this.engine.measure.annotationData.areaAnnotation.find(n=>n.isSelect==!0);if(t==null){if(this.points.length>=2){let n=this.points.map(i=>i.clone());n.push(e.catch.point.clone()),n.length>=3&&(t={id:it(),points:n,area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t))}}else if(t.points.length>0){const n=t.points.length-1;t.points[n]=e.catch.point.clone()}else t.points=this.points.map(n=>n.clone()),t.points.push(e.catch.point.clone());t&&t.points.length>=3&&(t.area=this.calculateArea(t.points),t.text=t.area)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){this.points=this.points.slice(0,this.points.length-1);let e=this.engine.measure.annotationData.areaAnnotation.find(t=>t.isSelect==!0);e!=null&&e.points.length>=3&&(e.points.length>this.points.length&&(e.points=this.points.map(t=>t.clone())),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(_e.MeasureChanged,e))}}class dh{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new st(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this),this.behavior.active();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const n=t.y-e.y,i=t.x-e.x,s=t.z-e.z,r=Math.sqrt(i*i+s*s);if(r===0)return{percentage:0,angle:0,heightDiff:n,horizontalDist:0,type:"slope"};const a=n/r*100,h=Math.atan(n/r)*(180/Math.PI);return{percentage:a,angle:h,heightDiff:n,horizontalDist:r,type:"slope"}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.points.push(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);if(n==null)return;console.log("进来了"),n.point2=t.point.clone();const i=this.calculateSlope(n.point1,n.point2);n.slopePercentage=i.percentage,n.slopeAngle=i.angle,n.heightDiff=i.heightDiff,n.horizontalDist=i.horizontalDist,n.text=i.percentage.toFixed(2)+"% ("+i.angle.toFixed(2)+"°)",n.isSelect=!1,this.points=[],this.engine.events.trigger(_e.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(s=>s.isSelect==!0);n==null&&(n={id:it(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00% (0.00°)",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(n)),n.point2=t.point.clone();const i=this.calculateSlope(n.point1,n.point2);n.slopePercentage=i.percentage,n.slopeAngle=i.angle,n.heightDiff=i.heightDiff,n.horizontalDist=i.horizontalDist,n.text=i.percentage.toFixed(2)+"% ("+i.angle.toFixed(2)+"°)"}}}class fh{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new rh(e),this.distanceMeasure=new oh(e),this.clearDistanceMeasure=new ah(e),this.elevationMeasure=new lh(e),this.pointMeasure=new ch(e),this.angleMeasure=new hh(e),this.areaMeasure=new uh(e),this.slopeMeasure=new dh(e),this.tools=new st(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let n=0;n<t.length;n++)t[n].container.remove();t=[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}}const Gr=0,ph=1,mh=2,Wr=2,Ki=1.25,Xr=1,Ie=32,Me=Ie/4,Zr=65535,gh=Math.pow(2,-24),Yi=Symbol("SKIP_GENERATION");function yh(o){return o.index?o.index.count:o.attributes.position.count}function Dt(o){return yh(o)/3}function wh(o,e=ArrayBuffer){return o>65535?new Uint32Array(new e(4*o)):new Uint16Array(new e(2*o))}function xh(o,e){if(!o.index){const t=o.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=wh(t,n);o.setIndex(new _.BufferAttribute(i,1));for(let s=0;s<t;s++)i[s]=s}}function qr(o,e){const t=Dt(o),n=e||o.drawRange,i=n.start/3,s=(n.start+n.count)/3,r=Math.max(0,i),a=Math.min(t,s)-r;return[{offset:Math.floor(r),count:Math.floor(a)}]}function Kr(o,e){if(!o.groups||!o.groups.length)return qr(o,e);const t=[],n=e||o.drawRange,i=n.start/3,s=(n.start+n.count)/3,r=Dt(o),a=[];for(const c of o.groups){const{start:d,count:m}=c,p=d/3,f=isFinite(m)?m:r*3-d,u=(d+f)/3;p<s&&u>i&&(a.push({pos:Math.max(i,p),isStart:!0}),a.push({pos:Math.min(s,u),isStart:!1}))}a.sort((c,d)=>c.pos!==d.pos?c.pos-d.pos:c.type==="end"?-1:1);let l=0,h=null;for(const c of a){const d=c.pos;l!==0&&d!==h&&t.push({offset:h,count:d-h}),l+=c.isStart?1:-1,h=d}return t}function $i(o,e,t,n,i){let s=1/0,r=1/0,a=1/0,l=-1/0,h=-1/0,c=-1/0,d=1/0,m=1/0,p=1/0,f=-1/0,u=-1/0,g=-1/0;const y=o.offset||0;for(let w=(e-y)*6,x=(e+t-y)*6;w<x;w+=6){const v=o[w+0],b=o[w+1],D=v-b,T=v+b;D<s&&(s=D),T>l&&(l=T),v<d&&(d=v),v>f&&(f=v);const k=o[w+2],P=o[w+3],I=k-P,z=k+P;I<r&&(r=I),z>h&&(h=z),k<m&&(m=k),k>u&&(u=k);const C=o[w+4],E=o[w+5],M=C-E,B=C+E;M<a&&(a=M),B>c&&(c=B),C<p&&(p=C),C>g&&(g=C)}n[0]=s,n[1]=r,n[2]=a,n[3]=l,n[4]=h,n[5]=c,i[0]=d,i[1]=m,i[2]=p,i[3]=f,i[4]=u,i[5]=g}function Yr(o,e,t=null,n=null,i=null){const s=o.attributes.position,r=o.index?o.index.array:null,a=s.normalized;if(i===null)i=new Float32Array(t*6),i.offset=e;else if(e<0||t+e>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=s.array,h=s.offset||0;let c=3;s.isInterleavedBufferAttribute&&(c=s.data.stride);const d=["getX","getY","getZ"],m=i.offset;for(let p=e,f=e+t;p<f;p++){const g=(n?n[p]:p)*3,y=(p-m)*6;let w=g+0,x=g+1,v=g+2;r&&(w=r[w],x=r[x],v=r[v]),a||(w=w*c+h,x=x*c+h,v=v*c+h);for(let b=0;b<3;b++){let D,T,k;a?(D=s[d[b]](w),T=s[d[b]](x),k=s[d[b]](v)):(D=l[w+b],T=l[x+b],k=l[v+b]);let P=D;T<P&&(P=T),k<P&&(P=k);let I=D;T>I&&(I=T),k>I&&(I=k);const z=(I-P)/2,C=b*2;i[y+C+0]=P+z,i[y+C+1]=z+(Math.abs(P)+z)*gh}}return i}function we(o,e,t){return t.min.x=e[o],t.min.y=e[o+1],t.min.z=e[o+2],t.max.x=e[o+3],t.max.y=e[o+4],t.max.z=e[o+5],t}function $r(o){let e=-1,t=-1/0;for(let n=0;n<3;n++){const i=o[n+3]-o[n];i>t&&(t=i,e=n)}return e}function Hr(o,e){e.set(o)}function Jr(o,e,t){let n,i;for(let s=0;s<3;s++){const r=s+3;n=o[s],i=e[s],t[s]=n<i?n:i,n=o[r],i=e[r],t[r]=n>i?n:i}}function Yn(o,e,t){for(let n=0;n<3;n++){const i=e[o+2*n],s=e[o+2*n+1],r=i-s,a=i+s;r<t[n]&&(t[n]=r),a>t[n+3]&&(t[n+3]=a)}}function un(o){const e=o[3]-o[0],t=o[4]-o[1],n=o[5]-o[2];return 2*(e*t+t*n+n*e)}const rt=32,vh=(o,e)=>o.candidate-e.candidate,ft=new Array(rt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),$n=new Float32Array(6);function bh(o,e,t,n,i,s){let r=-1,a=0;if(s===Gr)r=$r(e),r!==-1&&(a=(e[r]+e[r+3])/2);else if(s===ph)r=$r(o),r!==-1&&(a=_h(t,n,i,r));else if(s===mh){const l=un(o);let h=Ki*i;const c=t.offset||0,d=(n-c)*6,m=(n+i-c)*6;for(let p=0;p<3;p++){const f=e[p],y=(e[p+3]-f)/rt;if(i<rt/4){const w=[...ft];w.length=i;let x=0;for(let b=d;b<m;b+=6,x++){const D=w[x];D.candidate=t[b+2*p],D.count=0;const{bounds:T,leftCacheBounds:k,rightCacheBounds:P}=D;for(let I=0;I<3;I++)P[I]=1/0,P[I+3]=-1/0,k[I]=1/0,k[I+3]=-1/0,T[I]=1/0,T[I+3]=-1/0;Yn(b,t,T)}w.sort(vh);let v=i;for(let b=0;b<v;b++){const D=w[b];for(;b+1<v&&w[b+1].candidate===D.candidate;)w.splice(b+1,1),v--}for(let b=d;b<m;b+=6){const D=t[b+2*p];for(let T=0;T<v;T++){const k=w[T];D>=k.candidate?Yn(b,t,k.rightCacheBounds):(Yn(b,t,k.leftCacheBounds),k.count++)}}for(let b=0;b<v;b++){const D=w[b],T=D.count,k=i-D.count,P=D.leftCacheBounds,I=D.rightCacheBounds;let z=0;T!==0&&(z=un(P)/l);let C=0;k!==0&&(C=un(I)/l);const E=Xr+Ki*(z*T+C*k);E<h&&(r=p,h=E,a=D.candidate)}}else{for(let v=0;v<rt;v++){const b=ft[v];b.count=0,b.candidate=f+y+v*y;const D=b.bounds;for(let T=0;T<3;T++)D[T]=1/0,D[T+3]=-1/0}for(let v=d;v<m;v+=6){let T=~~((t[v+2*p]-f)/y);T>=rt&&(T=rt-1);const k=ft[T];k.count++,Yn(v,t,k.bounds)}const w=ft[rt-1];Hr(w.bounds,w.rightCacheBounds);for(let v=rt-2;v>=0;v--){const b=ft[v],D=ft[v+1];Jr(b.bounds,D.rightCacheBounds,b.rightCacheBounds)}let x=0;for(let v=0;v<rt-1;v++){const b=ft[v],D=b.count,T=b.bounds,P=ft[v+1].rightCacheBounds;D!==0&&(x===0?Hr(T,$n):Jr(T,$n,$n)),x+=D;let I=0,z=0;x!==0&&(I=un($n)/l);const C=i-x;C!==0&&(z=un(P)/l);const E=Xr+Ki*(I*x+z*C);E<h&&(r=p,h=E,a=b.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${s} used.`);return{axis:r,pos:a}}function _h(o,e,t,n){let i=0;const s=o.offset;for(let r=e,a=e+t;r<a;r++)i+=o[(r-s)*6+n*2];return i/t}class Hi{constructor(){this.boundingData=new Float32Array(6)}}function Mh(o,e,t,n,i,s){let r=n,a=n+i-1;const l=s.pos,h=s.axis*2,c=t.offset||0;for(;;){for(;r<=a&&t[(r-c)*6+h]<l;)r++;for(;r<=a&&t[(a-c)*6+h]>=l;)a--;if(r<a){for(let d=0;d<3;d++){let m=e[r*3+d];e[r*3+d]=e[a*3+d],e[a*3+d]=m}for(let d=0;d<6;d++){const m=r-c,p=a-c,f=t[m*6+d];t[m*6+d]=t[p*6+d],t[p*6+d]=f}r++,a--}else return r}}function Sh(o,e,t,n,i,s){let r=n,a=n+i-1;const l=s.pos,h=s.axis*2,c=t.offset||0;for(;;){for(;r<=a&&t[(r-c)*6+h]<l;)r++;for(;r<=a&&t[(a-c)*6+h]>=l;)a--;if(r<a){let d=o[r];o[r]=o[a],o[a]=d;for(let m=0;m<6;m++){const p=r-c,f=a-c,u=t[p*6+m];t[p*6+m]=t[f*6+m],t[f*6+m]=u}r++,a--}else return r}}let Qr,Hn,Ji,eo;const Ah=Math.pow(2,32);function Qi(o){return"count"in o?1:1+Qi(o.left)+Qi(o.right)}function Ch(o,e,t){return Qr=new Float32Array(t),Hn=new Uint32Array(t),Ji=new Uint16Array(t),eo=new Uint8Array(t),es(o,e)}function es(o,e){const t=o/4,n=o/2,i="count"in e,s=e.boundingData;for(let r=0;r<6;r++)Qr[t+r]=s[r];if(i)return e.buffer?(eo.set(new Uint8Array(e.buffer),o),o+e.buffer.byteLength):(Hn[t+6]=e.offset,Ji[n+14]=e.count,Ji[n+15]=Zr,o+Ie);{const{left:r,right:a,splitAxis:l}=e,h=o+Ie;let c=es(h,r);const d=o/Ie,p=c/Ie-d;if(p>Ah)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Hn[t+6]=p,Hn[t+7]=l,es(c,a)}}function Th(o,e,t){const i=(o.index?o.index.count:o.attributes.position.count)/3>2**16,s=t.reduce((c,d)=>c+d.count,0),r=i?4:2,a=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),l=i?new Uint32Array(a):new Uint16Array(a);let h=0;for(let c=0;c<t.length;c++){const{offset:d,count:m}=t[c];for(let p=0;p<m;p++)l[h+p]=d+p;h+=m}return l}function Ph(o,e,t,n,i){const{maxDepth:s,verbose:r,maxLeafTris:a,strategy:l,onProgress:h,indirect:c}=i,d=o._indirectBuffer,m=o.geometry,p=m.index?m.index.array:null,f=c?Sh:Mh,u=Dt(m),g=new Float32Array(6);let y=!1;const w=new Hi;return $i(e,t,n,w.boundingData,g),v(w,t,n,g),w;function x(b){h&&h(b/u)}function v(b,D,T,k=null,P=0){if(!y&&P>=s&&(y=!0,r&&(console.warn(`MeshBVH: Max depth of ${s} reached when generating BVH. Consider increasing maxDepth.`),console.warn(m))),T<=a||P>=s)return x(D+T),b.offset=D,b.count=T,b;const I=bh(b.boundingData,k,e,D,T,l);if(I.axis===-1)return x(D+T),b.offset=D,b.count=T,b;const z=f(d,p,e,D,T,I);if(z===D||z===D+T)x(D+T),b.offset=D,b.count=T;else{b.splitAxis=I.axis;const C=new Hi,E=D,M=z-D;b.left=C,$i(e,E,M,C.boundingData,g),v(C,E,M,g,P+1);const B=new Hi,V=z,U=T-M;b.right=B,$i(e,V,U,B.boundingData,g),v(B,V,U,g,P+1)}return b}}function Dh(o,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=o.geometry;let i,s;if(e.indirect){const r=Kr(n,e.range),a=Th(n,e.useSharedArrayBuffer,r);o._indirectBuffer=a,i=Yr(n,0,a.length,a),s=[{offset:0,count:a.length}]}else{xh(n,e);const r=qr(n,e.range)[0];i=Yr(n,r.offset,r.count),s=Kr(n,e.range)}o._roots=s.map(r=>{const a=Ph(o,i,r.offset,r.count,e),l=Qi(a),h=new t(Ie*l);return Ch(0,a,h),h})}class ot{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let n=1/0,i=-1/0;for(let s=0,r=e.length;s<r;s++){const l=e[s][t];n=l<n?l:n,i=l>i?l:i}this.min=n,this.max=i}setFromPoints(e,t){let n=1/0,i=-1/0;for(let s=0,r=t.length;s<r;s++){const a=t[s],l=e.dot(a);n=l<n?l:n,i=l>i?l:i}this.min=n,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}ot.prototype.setFromBox=(function(){const o=new _.Vector3;return function(t,n){const i=n.min,s=n.max;let r=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let c=0;c<=1;c++){o.x=i.x*l+s.x*(1-l),o.y=i.y*h+s.y*(1-h),o.z=i.z*c+s.z*(1-c);const d=t.dot(o);r=Math.min(d,r),a=Math.max(d,a)}this.min=r,this.max=a}})();const kh=(function(){const o=new _.Vector3,e=new _.Vector3,t=new _.Vector3;return function(i,s,r){const a=i.start,l=o,h=s.start,c=e;t.subVectors(a,h),o.subVectors(i.end,i.start),e.subVectors(s.end,s.start);const d=t.dot(c),m=c.dot(l),p=c.dot(c),f=t.dot(l),g=l.dot(l)*p-m*m;let y,w;g!==0?y=(d*m-f*p)/g:y=0,w=(d+y*m)/p,r.x=y,r.y=w}})(),ts=(function(){const o=new _.Vector2,e=new _.Vector3,t=new _.Vector3;return function(i,s,r,a){kh(i,s,o);let l=o.x,h=o.y;if(l>=0&&l<=1&&h>=0&&h<=1){i.at(l,r),s.at(h,a);return}else if(l>=0&&l<=1){h<0?s.at(0,a):s.at(1,a),i.closestPointToPoint(a,!0,r);return}else if(h>=0&&h<=1){l<0?i.at(0,r):i.at(1,r),s.closestPointToPoint(r,!0,a);return}else{let c;l<0?c=i.start:c=i.end;let d;h<0?d=s.start:d=s.end;const m=e,p=t;if(i.closestPointToPoint(d,!0,e),s.closestPointToPoint(c,!0,t),m.distanceToSquared(d)<=p.distanceToSquared(c)){r.copy(m),a.copy(d);return}else{r.copy(c),a.copy(p);return}}}})(),Ih=(function(){const o=new _.Vector3,e=new _.Vector3,t=new _.Plane,n=new _.Line3;return function(s,r){const{radius:a,center:l}=s,{a:h,b:c,c:d}=r;if(n.start=h,n.end=c,n.closestPointToPoint(l,!0,o).distanceTo(l)<=a||(n.start=h,n.end=d,n.closestPointToPoint(l,!0,o).distanceTo(l)<=a)||(n.start=c,n.end=d,n.closestPointToPoint(l,!0,o).distanceTo(l)<=a))return!0;const u=r.getPlane(t);if(Math.abs(u.distanceToPoint(l))<=a){const y=u.projectPoint(l,e);if(r.containsPoint(y))return!0}return!1}})(),Lh=["x","y","z"],at=1e-15,to=at*at;function je(o){return Math.abs(o)<at}class Ge extends _.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new _.Vector3),this.satBounds=new Array(4).fill().map(()=>new ot),this.points=[this.a,this.b,this.c],this.plane=new _.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new _.Line3,this.needsUpdate=!0}intersectsSphere(e){return Ih(e,this)}update(){const e=this.a,t=this.b,n=this.c,i=this.points,s=this.satAxes,r=this.satBounds,a=s[0],l=r[0];this.getNormal(a),l.setFromPoints(a,i);const h=s[1],c=r[1];h.subVectors(e,t),c.setFromPoints(h,i);const d=s[2],m=r[2];d.subVectors(t,n),m.setFromPoints(d,i);const p=s[3],f=r[3];p.subVectors(n,e),f.setFromPoints(p,i);const u=h.length(),g=d.length(),y=p.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,u<at?g<at||y<at?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(n)):g<at?y<at?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):y<at&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(n),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Ge.prototype.closestPointToSegment=(function(){const o=new _.Vector3,e=new _.Vector3,t=new _.Line3;return function(i,s=null,r=null){const{start:a,end:l}=i,h=this.points;let c,d=1/0;for(let m=0;m<3;m++){const p=(m+1)%3;t.start.copy(h[m]),t.end.copy(h[p]),ts(t,i,o,e),c=o.distanceToSquared(e),c<d&&(d=c,s&&s.copy(o),r&&r.copy(e))}return this.closestPointToPoint(a,o),c=a.distanceToSquared(o),c<d&&(d=c,s&&s.copy(o),r&&r.copy(a)),this.closestPointToPoint(l,o),c=l.distanceToSquared(o),c<d&&(d=c,s&&s.copy(o),r&&r.copy(l)),Math.sqrt(d)}})(),Ge.prototype.intersectsTriangle=(function(){const o=new Ge,e=new ot,t=new ot,n=new _.Vector3,i=new _.Vector3,s=new _.Vector3,r=new _.Vector3,a=new _.Line3,l=new _.Line3,h=new _.Vector3,c=new _.Vector2,d=new _.Vector2;function m(x,v,b,D){const T=n;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?T.copy(x.plane.normal):T.copy(v.plane.normal);const k=x.satBounds,P=x.satAxes;for(let C=1;C<4;C++){const E=k[C],M=P[C];if(e.setFromPoints(M,v.points),E.isSeparated(e)||(r.copy(T).cross(M),e.setFromPoints(r,x.points),t.setFromPoints(r,v.points),e.isSeparated(t)))return!1}const I=v.satBounds,z=v.satAxes;for(let C=1;C<4;C++){const E=I[C],M=z[C];if(e.setFromPoints(M,x.points),E.isSeparated(e)||(r.crossVectors(T,M),e.setFromPoints(r,x.points),t.setFromPoints(r,v.points),e.isSeparated(t)))return!1}return b&&(D||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),b.start.set(0,0,0),b.end.set(0,0,0)),!0}function p(x,v,b,D,T,k,P,I,z,C,E){let M=P/(P-I);C.x=D+(T-D)*M,E.start.subVectors(v,x).multiplyScalar(M).add(x),M=P/(P-z),C.y=D+(k-D)*M,E.end.subVectors(b,x).multiplyScalar(M).add(x)}function f(x,v,b,D,T,k,P,I,z,C,E){if(T>0)p(x.c,x.a,x.b,D,v,b,z,P,I,C,E);else if(k>0)p(x.b,x.a,x.c,b,v,D,I,P,z,C,E);else if(I*z>0||P!=0)p(x.a,x.b,x.c,v,b,D,P,I,z,C,E);else if(I!=0)p(x.b,x.a,x.c,b,v,D,I,P,z,C,E);else if(z!=0)p(x.c,x.a,x.b,D,v,b,z,P,I,C,E);else return!0;return!1}function u(x,v,b,D){const T=v.degenerateSegment,k=x.plane.distanceToPoint(T.start),P=x.plane.distanceToPoint(T.end);return je(k)?je(P)?m(x,v,b,D):(b&&(b.start.copy(T.start),b.end.copy(T.start)),x.containsPoint(T.start)):je(P)?(b&&(b.start.copy(T.end),b.end.copy(T.end)),x.containsPoint(T.end)):x.plane.intersectLine(T,n)!=null?(b&&(b.start.copy(n),b.end.copy(n)),x.containsPoint(n)):!1}function g(x,v,b){const D=v.a;return je(x.plane.distanceToPoint(D))&&x.containsPoint(D)?(b&&(b.start.copy(D),b.end.copy(D)),!0):!1}function y(x,v,b){const D=x.degenerateSegment,T=v.a;return D.closestPointToPoint(T,!0,n),T.distanceToSquared(n)<to?(b&&(b.start.copy(T),b.end.copy(T)),!0):!1}function w(x,v,b,D){if(x.isDegenerateIntoSegment)if(v.isDegenerateIntoSegment){const T=x.degenerateSegment,k=v.degenerateSegment,P=i,I=s;T.delta(P),k.delta(I);const z=n.subVectors(k.start,T.start),C=P.x*I.y-P.y*I.x;if(je(C))return!1;const E=(z.x*I.y-z.y*I.x)/C,M=-(P.x*z.y-P.y*z.x)/C;if(E<0||E>1||M<0||M>1)return!1;const B=T.start.z+P.z*E,V=k.start.z+I.z*M;return je(B-V)?(b&&(b.start.copy(T.start).addScaledVector(P,E),b.end.copy(T.start).addScaledVector(P,E)),!0):!1}else return v.isDegenerateIntoPoint?y(x,v,b):u(v,x,b,D);else{if(x.isDegenerateIntoPoint)return v.isDegenerateIntoPoint?v.a.distanceToSquared(x.a)<to?(b&&(b.start.copy(x.a),b.end.copy(x.a)),!0):!1:v.isDegenerateIntoSegment?y(v,x,b):g(v,x,b);if(v.isDegenerateIntoPoint)return g(x,v,b);if(v.isDegenerateIntoSegment)return u(x,v,b,D)}}return function(v,b=null,D=!1){this.needsUpdate&&this.update(),v.isExtendedTriangle?v.needsUpdate&&v.update():(o.copy(v),o.update(),v=o);const T=w(this,v,b,D);if(T!==void 0)return T;const k=this.plane,P=v.plane;let I=P.distanceToPoint(this.a),z=P.distanceToPoint(this.b),C=P.distanceToPoint(this.c);je(I)&&(I=0),je(z)&&(z=0),je(C)&&(C=0);const E=I*z,M=I*C;if(E>0&&M>0)return!1;let B=k.distanceToPoint(v.a),V=k.distanceToPoint(v.b),U=k.distanceToPoint(v.c);je(B)&&(B=0),je(V)&&(V=0),je(U)&&(U=0);const H=B*V,G=B*U;if(H>0&&G>0)return!1;i.copy(k.normal),s.copy(P.normal);const $=i.cross(s);let F=0,N=Math.abs($.x);const te=Math.abs($.y);te>N&&(N=te,F=1),Math.abs($.z)>N&&(F=2);const Y=Lh[F],ce=this.a[Y],fe=this.b[Y],se=this.c[Y],oe=v.a[Y],ue=v.b[Y],pe=v.c[Y];if(f(this,ce,fe,se,E,M,I,z,C,c,a))return m(this,v,b,D);if(f(v,oe,ue,pe,H,G,B,V,U,d,l))return m(this,v,b,D);if(c.y<c.x){const Ae=c.y;c.y=c.x,c.x=Ae,h.copy(a.start),a.start.copy(a.end),a.end.copy(h)}if(d.y<d.x){const Ae=d.y;d.y=d.x,d.x=Ae,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}return c.y<d.x||d.y<c.x?!1:(b&&(d.x>c.x?b.start.copy(l.start):b.start.copy(a.start),d.y<c.y?b.end.copy(l.end):b.end.copy(a.end)),!0)}})(),Ge.prototype.distanceToPoint=(function(){const o=new _.Vector3;return function(t){return this.closestPointToPoint(t,o),t.distanceTo(o)}})(),Ge.prototype.distanceToTriangle=(function(){const o=new _.Vector3,e=new _.Vector3,t=["a","b","c"],n=new _.Line3,i=new _.Line3;return function(r,a=null,l=null){const h=a||l?n:null;if(this.intersectsTriangle(r,h))return(a||l)&&(a&&h.getCenter(a),l&&h.getCenter(l)),0;let c=1/0;for(let d=0;d<3;d++){let m;const p=t[d],f=r[p];this.closestPointToPoint(f,o),m=f.distanceToSquared(o),m<c&&(c=m,a&&a.copy(o),l&&l.copy(f));const u=this[p];r.closestPointToPoint(u,o),m=u.distanceToSquared(o),m<c&&(c=m,a&&a.copy(u),l&&l.copy(o))}for(let d=0;d<3;d++){const m=t[d],p=t[(d+1)%3];n.set(this[m],this[p]);for(let f=0;f<3;f++){const u=t[f],g=t[(f+1)%3];i.set(r[u],r[g]),ts(n,i,o,e);const y=o.distanceToSquared(e);y<c&&(c=y,a&&a.copy(o),l&&l.copy(e))}}return Math.sqrt(c)}})();class Le{constructor(e,t,n){this.isOrientedBox=!0,this.min=new _.Vector3,this.max=new _.Vector3,this.matrix=new _.Matrix4,this.invMatrix=new _.Matrix4,this.points=new Array(8).fill().map(()=>new _.Vector3),this.satAxes=new Array(3).fill().map(()=>new _.Vector3),this.satBounds=new Array(3).fill().map(()=>new ot),this.alignedSatBounds=new Array(3).fill().map(()=>new ot),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),n&&this.matrix.copy(n)}set(e,t,n){this.min.copy(e),this.max.copy(t),this.matrix.copy(n),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Le.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,n=this.max,i=this.points;for(let h=0;h<=1;h++)for(let c=0;c<=1;c++)for(let d=0;d<=1;d++){const m=1*h|2*c|4*d,p=i[m];p.x=h?n.x:t.x,p.y=c?n.y:t.y,p.z=d?n.z:t.z,p.applyMatrix4(e)}const s=this.satBounds,r=this.satAxes,a=i[0];for(let h=0;h<3;h++){const c=r[h],d=s[h],m=1<<h,p=i[m];c.subVectors(a,p),d.setFromPoints(c,i)}const l=this.alignedSatBounds;l[0].setFromPointsField(i,"x"),l[1].setFromPointsField(i,"y"),l[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),Le.prototype.intersectsBox=(function(){const o=new ot;return function(t){this.needsUpdate&&this.update();const n=t.min,i=t.max,s=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(o.min=n.x,o.max=i.x,a[0].isSeparated(o)||(o.min=n.y,o.max=i.y,a[1].isSeparated(o))||(o.min=n.z,o.max=i.z,a[2].isSeparated(o)))return!1;for(let l=0;l<3;l++){const h=r[l],c=s[l];if(o.setFromBox(h,t),c.isSeparated(o))return!1}return!0}})(),Le.prototype.intersectsTriangle=(function(){const o=new Ge,e=new Array(3),t=new ot,n=new ot,i=new _.Vector3;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(o.copy(r),o.update(),r=o);const a=this.satBounds,l=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let m=0;m<3;m++){const p=a[m],f=l[m];if(t.setFromPoints(f,e),p.isSeparated(t))return!1}const h=r.satBounds,c=r.satAxes,d=this.points;for(let m=0;m<3;m++){const p=h[m],f=c[m];if(t.setFromPoints(f,d),p.isSeparated(t))return!1}for(let m=0;m<3;m++){const p=l[m];for(let f=0;f<4;f++){const u=c[f];if(i.crossVectors(p,u),t.setFromPoints(i,e),n.setFromPoints(i,d),t.isSeparated(n))return!1}}return!0}})(),Le.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})(),Le.prototype.distanceToPoint=(function(){const o=new _.Vector3;return function(t){return this.closestPointToPoint(t,o),t.distanceTo(o)}})(),Le.prototype.distanceToBox=(function(){const o=["x","y","z"],e=new Array(12).fill().map(()=>new _.Line3),t=new Array(12).fill().map(()=>new _.Line3),n=new _.Vector3,i=new _.Vector3;return function(r,a=0,l=null,h=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(l||h)&&(r.getCenter(i),this.closestPointToPoint(i,n),r.closestPointToPoint(n,i),l&&l.copy(n),h&&h.copy(i)),0;const c=a*a,d=r.min,m=r.max,p=this.points;let f=1/0;for(let g=0;g<8;g++){const y=p[g];i.copy(y).clamp(d,m);const w=y.distanceToSquared(i);if(w<f&&(f=w,l&&l.copy(y),h&&h.copy(i),w<c))return Math.sqrt(w)}let u=0;for(let g=0;g<3;g++)for(let y=0;y<=1;y++)for(let w=0;w<=1;w++){const x=(g+1)%3,v=(g+2)%3,b=y<<x|w<<v,D=1<<g|y<<x|w<<v,T=p[b],k=p[D];e[u].set(T,k);const I=o[g],z=o[x],C=o[v],E=t[u],M=E.start,B=E.end;M[I]=d[I],M[z]=y?d[z]:m[z],M[C]=w?d[C]:m[z],B[I]=m[I],B[z]=y?d[z]:m[z],B[C]=w?d[C]:m[z],u++}for(let g=0;g<=1;g++)for(let y=0;y<=1;y++)for(let w=0;w<=1;w++){i.x=g?m.x:d.x,i.y=y?m.y:d.y,i.z=w?m.z:d.z,this.closestPointToPoint(i,n);const x=i.distanceToSquared(n);if(x<f&&(f=x,l&&l.copy(n),h&&h.copy(i),x<c))return Math.sqrt(x)}for(let g=0;g<12;g++){const y=e[g];for(let w=0;w<12;w++){const x=t[w];ts(y,x,n,i);const v=n.distanceToSquared(i);if(v<f&&(f=v,l&&l.copy(n),h&&h.copy(i),v<c))return Math.sqrt(v)}}return Math.sqrt(f)}})();class ns{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Eh extends ns{constructor(){super(()=>new Ge)}}const We=new Eh;function Se(o,e){return e[o+15]===Zr}function Ue(o,e){return e[o+6]}function Xe(o,e){return e[o+14]}function Te(o){return o+Me}function Pe(o,e){const t=e[o+6];return o+t*Me}function is(o,e){return e[o+7]}function Qd(o){return o}class Bh{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=n=>{t&&e.push(t),t=n,this.float32Array=new Float32Array(n),this.uint16Array=new Uint16Array(n),this.uint32Array=new Uint32Array(n)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const me=new Bh;let pt,qt;const Kt=[],Jn=new ns(()=>new _.Box3);function Oh(o,e,t,n,i,s){pt=Jn.getPrimitive(),qt=Jn.getPrimitive(),Kt.push(pt,qt),me.setBuffer(o._roots[e]);const r=ss(0,o.geometry,t,n,i,s);me.clearBuffer(),Jn.releasePrimitive(pt),Jn.releasePrimitive(qt),Kt.pop(),Kt.pop();const a=Kt.length;return a>0&&(qt=Kt[a-1],pt=Kt[a-2]),r}function ss(o,e,t,n,i=null,s=0,r=0){const{float32Array:a,uint16Array:l,uint32Array:h}=me;let c=o*2;if(Se(c,l)){const m=Ue(o,h),p=Xe(c,l);return we(o,a,pt),n(m,p,!1,r,s+o/Me,pt)}else{let I=function(C){const{uint16Array:E,uint32Array:M}=me;let B=C*2;for(;!Se(B,E);)C=Te(C),B=C*2;return Ue(C,M)},z=function(C){const{uint16Array:E,uint32Array:M}=me;let B=C*2;for(;!Se(B,E);)C=Pe(C,M),B=C*2;return Ue(C,M)+Xe(B,E)};const m=Te(o),p=Pe(o,h);let f=m,u=p,g,y,w,x;if(i&&(w=pt,x=qt,we(f,a,w),we(u,a,x),g=i(w),y=i(x),y<g)){f=p,u=m;const C=g;g=y,y=C,w=x}w||(w=pt,we(f,a,w));const v=Se(f*2,l),b=t(w,v,g,r+1,s+f/Me);let D;if(b===Wr){const C=I(f),M=z(f)-C;D=n(C,M,!0,r+1,s+f/Me,w)}else D=b&&ss(f,e,t,n,i,s,r+1);if(D)return!0;x=qt,we(u,a,x);const T=Se(u*2,l),k=t(x,T,y,r+1,s+u/Me);let P;if(k===Wr){const C=I(u),M=z(u)-C;P=n(C,M,!0,r+1,s+u/Me,x)}else P=k&&ss(u,e,t,n,i,s,r+1);return!!P}}const dn=new _.Vector3,rs=new _.Vector3;function zh(o,e,t={},n=0,i=1/0){const s=n*n,r=i*i;let a=1/0,l=null;if(o.shapecast({boundsTraverseOrder:c=>(dn.copy(e).clamp(c.min,c.max),dn.distanceToSquared(e)),intersectsBounds:(c,d,m)=>m<a&&m<r,intersectsTriangle:(c,d)=>{c.closestPointToPoint(e,dn);const m=e.distanceToSquared(dn);return m<a&&(rs.copy(dn),a=m,l=d),m<s}}),a===1/0)return null;const h=Math.sqrt(a);return t.point?t.point.copy(rs):t.point=rs.clone(),t.distance=h,t.faceIndex=l,t}const Qn=parseInt(_.REVISION)>=169,Nh=parseInt(_.REVISION)<=161,kt=new _.Vector3,It=new _.Vector3,Lt=new _.Vector3,ei=new _.Vector2,ti=new _.Vector2,ni=new _.Vector2,no=new _.Vector3,io=new _.Vector3,so=new _.Vector3,fn=new _.Vector3;function Rh(o,e,t,n,i,s,r,a){let l;if(s===_.BackSide?l=o.intersectTriangle(n,t,e,!0,i):l=o.intersectTriangle(e,t,n,s!==_.DoubleSide,i),l===null)return null;const h=o.origin.distanceTo(i);return h<r||h>a?null:{distance:h,point:i.clone()}}function ro(o,e,t,n,i,s,r,a,l,h,c){kt.fromBufferAttribute(e,s),It.fromBufferAttribute(e,r),Lt.fromBufferAttribute(e,a);const d=Rh(o,kt,It,Lt,fn,l,h,c);if(d){if(n){ei.fromBufferAttribute(n,s),ti.fromBufferAttribute(n,r),ni.fromBufferAttribute(n,a),d.uv=new _.Vector2;const p=_.Triangle.getInterpolation(fn,kt,It,Lt,ei,ti,ni,d.uv);Qn||(d.uv=p)}if(i){ei.fromBufferAttribute(i,s),ti.fromBufferAttribute(i,r),ni.fromBufferAttribute(i,a),d.uv1=new _.Vector2;const p=_.Triangle.getInterpolation(fn,kt,It,Lt,ei,ti,ni,d.uv1);Qn||(d.uv1=p),Nh&&(d.uv2=d.uv1)}if(t){no.fromBufferAttribute(t,s),io.fromBufferAttribute(t,r),so.fromBufferAttribute(t,a),d.normal=new _.Vector3;const p=_.Triangle.getInterpolation(fn,kt,It,Lt,no,io,so,d.normal);d.normal.dot(o.direction)>0&&d.normal.multiplyScalar(-1),Qn||(d.normal=p)}const m={a:s,b:r,c:a,normal:new _.Vector3,materialIndex:0};if(_.Triangle.getNormal(kt,It,Lt,m.normal),d.face=m,d.faceIndex=s,Qn){const p=new _.Vector3;_.Triangle.getBarycoord(fn,kt,It,Lt,p),d.barycoord=p}}return d}function oo(o){return o&&o.isMaterial?o.side:o}function ii(o,e,t,n,i,s,r){const a=n*3;let l=a+0,h=a+1,c=a+2;const{index:d,groups:m}=o;o.index&&(l=d.getX(l),h=d.getX(h),c=d.getX(c));const{position:p,normal:f,uv:u,uv1:g}=o.attributes;if(Array.isArray(e)){const y=n*3;for(let w=0,x=m.length;w<x;w++){const{start:v,count:b,materialIndex:D}=m[w];if(y>=v&&y<v+b){const T=oo(e[D]),k=ro(t,p,f,u,g,l,h,c,T,s,r);if(k)if(k.faceIndex=n,k.face.materialIndex=D,i)i.push(k);else return k}}}else{const y=oo(e),w=ro(t,p,f,u,g,l,h,c,y,s,r);if(w)if(w.faceIndex=n,w.face.materialIndex=0,i)i.push(w);else return w}return null}function be(o,e,t,n){const i=o.a,s=o.b,r=o.c;let a=e,l=e+1,h=e+2;t&&(a=t.getX(a),l=t.getX(l),h=t.getX(h)),i.x=n.getX(a),i.y=n.getY(a),i.z=n.getZ(a),s.x=n.getX(l),s.y=n.getY(l),s.z=n.getZ(l),r.x=n.getX(h),r.y=n.getY(h),r.z=n.getZ(h)}function Fh(o,e,t,n,i,s,r,a){const{geometry:l,_indirectBuffer:h}=o;for(let c=n,d=n+i;c<d;c++)ii(l,e,t,c,s,r,a)}function Uh(o,e,t,n,i,s,r){const{geometry:a,_indirectBuffer:l}=o;let h=1/0,c=null;for(let d=n,m=n+i;d<m;d++){let p;p=ii(a,e,t,d,null,s,r),p&&p.distance<h&&(c=p,h=p.distance)}return c}function Vh(o,e,t,n,i,s,r){const{geometry:a}=t,{index:l}=a,h=a.attributes.position;for(let c=o,d=e+o;c<d;c++){let m;if(m=c,be(r,m*3,l,h),r.needsUpdate=!0,n(r,m,i,s))return!0}return!1}function jh(o,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=o.geometry,n=t.index?t.index.array:null,i=t.attributes.position;let s,r,a,l,h=0;const c=o._roots;for(let m=0,p=c.length;m<p;m++)s=c[m],r=new Uint32Array(s),a=new Uint16Array(s),l=new Float32Array(s),d(0,h),h+=s.byteLength;function d(m,p,f=!1){const u=m*2;if(Se(u,a)){const g=r[m+6],y=a[u+14];let w=1/0,x=1/0,v=1/0,b=-1/0,D=-1/0,T=-1/0;for(let k=3*g,P=3*(g+y);k<P;k++){let I=n[k];const z=i.getX(I),C=i.getY(I),E=i.getZ(I);z<w&&(w=z),z>b&&(b=z),C<x&&(x=C),C>D&&(D=C),E<v&&(v=E),E>T&&(T=E)}return l[m+0]!==w||l[m+1]!==x||l[m+2]!==v||l[m+3]!==b||l[m+4]!==D||l[m+5]!==T?(l[m+0]=w,l[m+1]=x,l[m+2]=v,l[m+3]=b,l[m+4]=D,l[m+5]=T,!0):!1}else{const g=Te(m),y=Pe(m,r);let w=f,x=!1,v=!1;if(e){if(!w){const I=g/Me+p/Ie,z=y/Me+p/Ie;x=e.has(I),v=e.has(z),w=!x&&!v}}else x=!0,v=!0;const b=w||x,D=w||v;let T=!1;b&&(T=d(g,p,w));let k=!1;D&&(k=d(y,p,w));const P=T||k;if(P)for(let I=0;I<3;I++){const z=g+I,C=y+I,E=l[z],M=l[z+3],B=l[C],V=l[C+3];l[m+I]=E<B?E:B,l[m+I+3]=M>V?M:V}return P}}}function mt(o,e,t,n,i){let s,r,a,l,h,c;const d=1/t.direction.x,m=1/t.direction.y,p=1/t.direction.z,f=t.origin.x,u=t.origin.y,g=t.origin.z;let y=e[o],w=e[o+3],x=e[o+1],v=e[o+3+1],b=e[o+2],D=e[o+3+2];return d>=0?(s=(y-f)*d,r=(w-f)*d):(s=(w-f)*d,r=(y-f)*d),m>=0?(a=(x-u)*m,l=(v-u)*m):(a=(v-u)*m,l=(x-u)*m),s>l||a>r||((a>s||isNaN(s))&&(s=a),(l<r||isNaN(r))&&(r=l),p>=0?(h=(b-g)*p,c=(D-g)*p):(h=(D-g)*p,c=(b-g)*p),s>c||h>r)?!1:((h>s||s!==s)&&(s=h),(c<r||r!==r)&&(r=c),s<=i&&r>=n)}function Gh(o,e,t,n,i,s,r,a){const{geometry:l,_indirectBuffer:h}=o;for(let c=n,d=n+i;c<d;c++){let m=h?h[c]:c;ii(l,e,t,m,s,r,a)}}function Wh(o,e,t,n,i,s,r){const{geometry:a,_indirectBuffer:l}=o;let h=1/0,c=null;for(let d=n,m=n+i;d<m;d++){let p;p=ii(a,e,t,l?l[d]:d,null,s,r),p&&p.distance<h&&(c=p,h=p.distance)}return c}function Xh(o,e,t,n,i,s,r){const{geometry:a}=t,{index:l}=a,h=a.attributes.position;for(let c=o,d=e+o;c<d;c++){let m;if(m=t.resolveTriangleIndex(c),be(r,m*3,l,h),r.needsUpdate=!0,n(r,m,i,s))return!0}return!1}function Zh(o,e,t,n,i,s,r){me.setBuffer(o._roots[e]),os(0,o,t,n,i,s,r),me.clearBuffer()}function os(o,e,t,n,i,s,r){const{float32Array:a,uint16Array:l,uint32Array:h}=me,c=o*2;if(Se(c,l)){const m=Ue(o,h),p=Xe(c,l);Fh(e,t,n,m,p,i,s,r)}else{const m=Te(o);mt(m,a,n,s,r)&&os(m,e,t,n,i,s,r);const p=Pe(o,h);mt(p,a,n,s,r)&&os(p,e,t,n,i,s,r)}}const qh=["x","y","z"];function Kh(o,e,t,n,i,s){me.setBuffer(o._roots[e]);const r=as(0,o,t,n,i,s);return me.clearBuffer(),r}function as(o,e,t,n,i,s){const{float32Array:r,uint16Array:a,uint32Array:l}=me;let h=o*2;if(Se(h,a)){const d=Ue(o,l),m=Xe(h,a);return Uh(e,t,n,d,m,i,s)}else{const d=is(o,l),m=qh[d],f=n.direction[m]>=0;let u,g;f?(u=Te(o),g=Pe(o,l)):(u=Pe(o,l),g=Te(o));const w=mt(u,r,n,i,s)?as(u,e,t,n,i,s):null;if(w){const b=w.point[m];if(f?b<=r[g+d]:b>=r[g+d+3])return w}const v=mt(g,r,n,i,s)?as(g,e,t,n,i,s):null;return w&&v?w.distance<=v.distance?w:v:w||v||null}}const si=new _.Box3,Yt=new Ge,$t=new Ge,pn=new _.Matrix4,ao=new Le,ri=new Le;function Yh(o,e,t,n){me.setBuffer(o._roots[e]);const i=ls(0,o,t,n);return me.clearBuffer(),i}function ls(o,e,t,n,i=null){const{float32Array:s,uint16Array:r,uint32Array:a}=me;let l=o*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),ao.set(t.boundingBox.min,t.boundingBox.max,n),i=ao),Se(l,r)){const c=e.geometry,d=c.index,m=c.attributes.position,p=t.index,f=t.attributes.position,u=Ue(o,a),g=Xe(l,r);if(pn.copy(n).invert(),t.boundsTree)return we(o,s,ri),ri.matrix.copy(pn),ri.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>ri.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(n),w.b.applyMatrix4(n),w.c.applyMatrix4(n),w.needsUpdate=!0;for(let x=u*3,v=(g+u)*3;x<v;x+=3)if(be($t,x,d,m),$t.needsUpdate=!0,w.intersectsTriangle($t))return!0;return!1}});{const y=Dt(t);for(let w=u*3,x=(g+u)*3;w<x;w+=3){be(Yt,w,d,m),Yt.a.applyMatrix4(pn),Yt.b.applyMatrix4(pn),Yt.c.applyMatrix4(pn),Yt.needsUpdate=!0;for(let v=0,b=y*3;v<b;v+=3)if(be($t,v,p,f),$t.needsUpdate=!0,Yt.intersectsTriangle($t))return!0}}}else{const c=Te(o),d=Pe(o,a);return we(c,s,si),!!(i.intersectsBox(si)&&ls(c,e,t,n,i)||(we(d,s,si),i.intersectsBox(si)&&ls(d,e,t,n,i)))}}const oi=new _.Matrix4,cs=new Le,mn=new Le,$h=new _.Vector3,Hh=new _.Vector3,Jh=new _.Vector3,Qh=new _.Vector3;function eu(o,e,t,n={},i={},s=0,r=1/0){e.boundingBox||e.computeBoundingBox(),cs.set(e.boundingBox.min,e.boundingBox.max,t),cs.needsUpdate=!0;const a=o.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,m=We.getPrimitive(),p=We.getPrimitive();let f=$h,u=Hh,g=null,y=null;i&&(g=Jh,y=Qh);let w=1/0,x=null,v=null;return oi.copy(t).invert(),mn.matrix.copy(oi),o.shapecast({boundsTraverseOrder:b=>cs.distanceToBox(b),intersectsBounds:(b,D,T)=>T<w&&T<r?(D&&(mn.min.copy(b.min),mn.max.copy(b.max),mn.needsUpdate=!0),!0):!1,intersectsRange:(b,D)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:k=>mn.distanceToBox(k),intersectsBounds:(k,P,I)=>I<w&&I<r,intersectsRange:(k,P)=>{for(let I=k,z=k+P;I<z;I++){be(p,3*I,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let C=b,E=b+D;C<E;C++){be(m,3*C,h,l),m.needsUpdate=!0;const M=m.distanceToTriangle(p,f,g);if(M<w&&(u.copy(f),y&&y.copy(g),w=M,x=C,v=I),M<s)return!0}}}});{const T=Dt(e);for(let k=0,P=T;k<P;k++){be(p,3*k,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let I=b,z=b+D;I<z;I++){be(m,3*I,h,l),m.needsUpdate=!0;const C=m.distanceToTriangle(p,f,g);if(C<w&&(u.copy(f),y&&y.copy(g),w=C,x=I,v=k),C<s)return!0}}}}}),We.releasePrimitive(m),We.releasePrimitive(p),w===1/0?null:(n.point?n.point.copy(u):n.point=u.clone(),n.distance=w,n.faceIndex=x,i&&(i.point?i.point.copy(y):i.point=y.clone(),i.point.applyMatrix4(oi),u.applyMatrix4(oi),i.distance=u.sub(i.point).length(),i.faceIndex=v),n)}function tu(o,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=o.geometry,n=t.index?t.index.array:null,i=t.attributes.position;let s,r,a,l,h=0;const c=o._roots;for(let m=0,p=c.length;m<p;m++)s=c[m],r=new Uint32Array(s),a=new Uint16Array(s),l=new Float32Array(s),d(0,h),h+=s.byteLength;function d(m,p,f=!1){const u=m*2;if(Se(u,a)){const g=r[m+6],y=a[u+14];let w=1/0,x=1/0,v=1/0,b=-1/0,D=-1/0,T=-1/0;for(let k=g,P=g+y;k<P;k++){const I=3*o.resolveTriangleIndex(k);for(let z=0;z<3;z++){let C=I+z;C=n?n[C]:C;const E=i.getX(C),M=i.getY(C),B=i.getZ(C);E<w&&(w=E),E>b&&(b=E),M<x&&(x=M),M>D&&(D=M),B<v&&(v=B),B>T&&(T=B)}}return l[m+0]!==w||l[m+1]!==x||l[m+2]!==v||l[m+3]!==b||l[m+4]!==D||l[m+5]!==T?(l[m+0]=w,l[m+1]=x,l[m+2]=v,l[m+3]=b,l[m+4]=D,l[m+5]=T,!0):!1}else{const g=Te(m),y=Pe(m,r);let w=f,x=!1,v=!1;if(e){if(!w){const I=g/Me+p/Ie,z=y/Me+p/Ie;x=e.has(I),v=e.has(z),w=!x&&!v}}else x=!0,v=!0;const b=w||x,D=w||v;let T=!1;b&&(T=d(g,p,w));let k=!1;D&&(k=d(y,p,w));const P=T||k;if(P)for(let I=0;I<3;I++){const z=g+I,C=y+I,E=l[z],M=l[z+3],B=l[C],V=l[C+3];l[m+I]=E<B?E:B,l[m+I+3]=M>V?M:V}return P}}}function nu(o,e,t,n,i,s,r){me.setBuffer(o._roots[e]),hs(0,o,t,n,i,s,r),me.clearBuffer()}function hs(o,e,t,n,i,s,r){const{float32Array:a,uint16Array:l,uint32Array:h}=me,c=o*2;if(Se(c,l)){const m=Ue(o,h),p=Xe(c,l);Gh(e,t,n,m,p,i,s,r)}else{const m=Te(o);mt(m,a,n,s,r)&&hs(m,e,t,n,i,s,r);const p=Pe(o,h);mt(p,a,n,s,r)&&hs(p,e,t,n,i,s,r)}}const iu=["x","y","z"];function su(o,e,t,n,i,s){me.setBuffer(o._roots[e]);const r=us(0,o,t,n,i,s);return me.clearBuffer(),r}function us(o,e,t,n,i,s){const{float32Array:r,uint16Array:a,uint32Array:l}=me;let h=o*2;if(Se(h,a)){const d=Ue(o,l),m=Xe(h,a);return Wh(e,t,n,d,m,i,s)}else{const d=is(o,l),m=iu[d],f=n.direction[m]>=0;let u,g;f?(u=Te(o),g=Pe(o,l)):(u=Pe(o,l),g=Te(o));const w=mt(u,r,n,i,s)?us(u,e,t,n,i,s):null;if(w){const b=w.point[m];if(f?b<=r[g+d]:b>=r[g+d+3])return w}const v=mt(g,r,n,i,s)?us(g,e,t,n,i,s):null;return w&&v?w.distance<=v.distance?w:v:w||v||null}}const ai=new _.Box3,Ht=new Ge,Jt=new Ge,gn=new _.Matrix4,lo=new Le,li=new Le;function ru(o,e,t,n){me.setBuffer(o._roots[e]);const i=ds(0,o,t,n);return me.clearBuffer(),i}function ds(o,e,t,n,i=null){const{float32Array:s,uint16Array:r,uint32Array:a}=me;let l=o*2;if(i===null&&(t.boundingBox||t.computeBoundingBox(),lo.set(t.boundingBox.min,t.boundingBox.max,n),i=lo),Se(l,r)){const c=e.geometry,d=c.index,m=c.attributes.position,p=t.index,f=t.attributes.position,u=Ue(o,a),g=Xe(l,r);if(gn.copy(n).invert(),t.boundsTree)return we(o,s,li),li.matrix.copy(gn),li.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:w=>li.intersectsBox(w),intersectsTriangle:w=>{w.a.applyMatrix4(n),w.b.applyMatrix4(n),w.c.applyMatrix4(n),w.needsUpdate=!0;for(let x=u,v=g+u;x<v;x++)if(be(Jt,3*e.resolveTriangleIndex(x),d,m),Jt.needsUpdate=!0,w.intersectsTriangle(Jt))return!0;return!1}});{const y=Dt(t);for(let w=u,x=g+u;w<x;w++){const v=e.resolveTriangleIndex(w);be(Ht,3*v,d,m),Ht.a.applyMatrix4(gn),Ht.b.applyMatrix4(gn),Ht.c.applyMatrix4(gn),Ht.needsUpdate=!0;for(let b=0,D=y*3;b<D;b+=3)if(be(Jt,b,p,f),Jt.needsUpdate=!0,Ht.intersectsTriangle(Jt))return!0}}}else{const c=Te(o),d=Pe(o,a);return we(c,s,ai),!!(i.intersectsBox(ai)&&ds(c,e,t,n,i)||(we(d,s,ai),i.intersectsBox(ai)&&ds(d,e,t,n,i)))}}const ci=new _.Matrix4,fs=new Le,yn=new Le,ou=new _.Vector3,au=new _.Vector3,lu=new _.Vector3,cu=new _.Vector3;function hu(o,e,t,n={},i={},s=0,r=1/0){e.boundingBox||e.computeBoundingBox(),fs.set(e.boundingBox.min,e.boundingBox.max,t),fs.needsUpdate=!0;const a=o.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,m=We.getPrimitive(),p=We.getPrimitive();let f=ou,u=au,g=null,y=null;i&&(g=lu,y=cu);let w=1/0,x=null,v=null;return ci.copy(t).invert(),yn.matrix.copy(ci),o.shapecast({boundsTraverseOrder:b=>fs.distanceToBox(b),intersectsBounds:(b,D,T)=>T<w&&T<r?(D&&(yn.min.copy(b.min),yn.max.copy(b.max),yn.needsUpdate=!0),!0):!1,intersectsRange:(b,D)=>{if(e.boundsTree){const T=e.boundsTree;return T.shapecast({boundsTraverseOrder:k=>yn.distanceToBox(k),intersectsBounds:(k,P,I)=>I<w&&I<r,intersectsRange:(k,P)=>{for(let I=k,z=k+P;I<z;I++){const C=T.resolveTriangleIndex(I);be(p,3*C,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let E=b,M=b+D;E<M;E++){const B=o.resolveTriangleIndex(E);be(m,3*B,h,l),m.needsUpdate=!0;const V=m.distanceToTriangle(p,f,g);if(V<w&&(u.copy(f),y&&y.copy(g),w=V,x=E,v=I),V<s)return!0}}}})}else{const T=Dt(e);for(let k=0,P=T;k<P;k++){be(p,3*k,d,c),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let I=b,z=b+D;I<z;I++){const C=o.resolveTriangleIndex(I);be(m,3*C,h,l),m.needsUpdate=!0;const E=m.distanceToTriangle(p,f,g);if(E<w&&(u.copy(f),y&&y.copy(g),w=E,x=I,v=k),E<s)return!0}}}}}),We.releasePrimitive(m),We.releasePrimitive(p),w===1/0?null:(n.point?n.point.copy(u):n.point=u.clone(),n.distance=w,n.faceIndex=x,i&&(i.point?i.point.copy(y):i.point=y.clone(),i.point.applyMatrix4(ci),u.applyMatrix4(ci),i.distance=u.sub(i.point).length(),i.faceIndex=v),n)}function uu(){return typeof SharedArrayBuffer<"u"}const wn=new me.constructor,hi=new me.constructor,gt=new ns(()=>new _.Box3),Qt=new _.Box3,en=new _.Box3,ps=new _.Box3,ms=new _.Box3;let gs=!1;function du(o,e,t,n){if(gs)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");gs=!0;const i=o._roots,s=e._roots;let r,a=0,l=0;const h=new _.Matrix4().copy(t).invert();for(let c=0,d=i.length;c<d;c++){wn.setBuffer(i[c]),l=0;const m=gt.getPrimitive();we(0,wn.float32Array,m),m.applyMatrix4(h);for(let p=0,f=s.length;p<f&&(hi.setBuffer(s[p]),r=Ke(0,0,t,h,n,a,l,0,0,m),hi.clearBuffer(),l+=s[p].byteLength/Ie,!r);p++);if(gt.releasePrimitive(m),wn.clearBuffer(),a+=i[c].byteLength/Ie,r)break}return gs=!1,r}function Ke(o,e,t,n,i,s=0,r=0,a=0,l=0,h=null,c=!1){let d,m;c?(d=hi,m=wn):(d=wn,m=hi);const p=d.float32Array,f=d.uint32Array,u=d.uint16Array,g=m.float32Array,y=m.uint32Array,w=m.uint16Array,x=o*2,v=e*2,b=Se(x,u),D=Se(v,w);let T=!1;if(D&&b)c?T=i(Ue(e,y),Xe(e*2,w),Ue(o,f),Xe(o*2,u),l,r+e/Me,a,s+o/Me):T=i(Ue(o,f),Xe(o*2,u),Ue(e,y),Xe(e*2,w),a,s+o/Me,l,r+e/Me);else if(D){const k=gt.getPrimitive();we(e,g,k),k.applyMatrix4(t);const P=Te(o),I=Pe(o,f);we(P,p,Qt),we(I,p,en);const z=k.intersectsBox(Qt),C=k.intersectsBox(en);T=z&&Ke(e,P,n,t,i,r,s,l,a+1,k,!c)||C&&Ke(e,I,n,t,i,r,s,l,a+1,k,!c),gt.releasePrimitive(k)}else{const k=Te(e),P=Pe(e,y);we(k,g,ps),we(P,g,ms);const I=h.intersectsBox(ps),z=h.intersectsBox(ms);if(I&&z)T=Ke(o,k,t,n,i,s,r,a,l+1,h,c)||Ke(o,P,t,n,i,s,r,a,l+1,h,c);else if(I)if(b)T=Ke(o,k,t,n,i,s,r,a,l+1,h,c);else{const C=gt.getPrimitive();C.copy(ps).applyMatrix4(t);const E=Te(o),M=Pe(o,f);we(E,p,Qt),we(M,p,en);const B=C.intersectsBox(Qt),V=C.intersectsBox(en);T=B&&Ke(k,E,n,t,i,r,s,l,a+1,C,!c)||V&&Ke(k,M,n,t,i,r,s,l,a+1,C,!c),gt.releasePrimitive(C)}else if(z)if(b)T=Ke(o,P,t,n,i,s,r,a,l+1,h,c);else{const C=gt.getPrimitive();C.copy(ms).applyMatrix4(t);const E=Te(o),M=Pe(o,f);we(E,p,Qt),we(M,p,en);const B=C.intersectsBox(Qt),V=C.intersectsBox(en);T=B&&Ke(P,E,n,t,i,r,s,l,a+1,C,!c)||V&&Ke(P,M,n,t,i,r,s,l,a+1,C,!c),gt.releasePrimitive(C)}}return T}const ui=new Le,co=new _.Box3,fu={strategy:Gr,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class ys{static serialize(e,t={}){t={cloneBuffers:!0,...t};const n=e.geometry,i=e._roots,s=e._indirectBuffer,r=n.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=i.map(l=>l.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=s?s.slice():null):(a.roots=i,a.index=r?r.array:null,a.indirectBuffer=s),a}static deserialize(e,t,n={}){n={setIndex:!0,indirect:!!e.indirectBuffer,...n};const{index:i,roots:s,indirectBuffer:r}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(s));const a=new ys(t,{...n,[Yi]:!0});if(a._roots=s,a._indirectBuffer=r||null,n.setIndex){const h=t.getIndex();if(h===null){const c=new _.BufferAttribute(e.index,1,!1);t.setIndex(c)}else h.array!==i&&(h.array.set(i),h.needsUpdate=!0)}return a;function l(h){for(let c=0;c<h.length;c++){const d=h[c],m=new Uint32Array(d),p=new Uint16Array(d);for(let f=0,u=d.byteLength/Ie;f<u;f++){const g=Me*f,y=2*g;Se(y,p)||(m[g+6]=m[g+6]/Me-f)}}}}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...fu,[Yi]:!1},t),t.useSharedArrayBuffer&&!uu())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[Yi]||(Dh(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new _.Box3))),this.resolveTriangleIndex=t.indirect?n=>this._indirectBuffer[n]:n=>n}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let n=0,i=t.length;n<i;n++)t[n]+=e;else{const n=this._roots;for(let i=0;i<n.length;i++){const s=n[i],r=new Uint32Array(s),a=new Uint16Array(s),l=s.byteLength/Ie;for(let h=0;h<l;h++){const c=Me*h,d=2*c;Se(d,a)&&(r[c+6]+=e)}}}}refit(e=null){return(this.indirect?tu:jh)(this,e)}traverse(e,t=0){const n=this._roots[t],i=new Uint32Array(n),s=new Uint16Array(n);r(0);function r(a,l=0){const h=a*2,c=Se(h,s);if(c){const d=i[a+6],m=s[h+14];e(l,c,new Float32Array(n,a*4,6),d,m)}else{const d=Te(a),m=Pe(a,i),p=is(a,i);e(l,c,new Float32Array(n,a*4,6),p)||(r(d,l+1),r(m,l+1))}}}raycast(e,t=_.FrontSide,n=0,i=1/0){const s=this._roots,r=[],a=this.indirect?nu:Zh;for(let l=0,h=s.length;l<h;l++)a(this,l,t,e,r,n,i);return r}raycastFirst(e,t=_.FrontSide,n=0,i=1/0){const s=this._roots;let r=null;const a=this.indirect?su:Kh;for(let l=0,h=s.length;l<h;l++){const c=a(this,l,t,e,n,i);c!=null&&(r==null||c.distance<r.distance)&&(r=c)}return r}intersectsGeometry(e,t){let n=!1;const i=this._roots,s=this.indirect?ru:Yh;for(let r=0,a=i.length;r<a&&(n=s(this,r,e,t),!n);r++);return n}shapecast(e){const t=We.getPrimitive(),n=this.indirect?Xh:Vh;let{boundsTraverseOrder:i,intersectsBounds:s,intersectsRange:r,intersectsTriangle:a}=e;if(r&&a){const d=r;r=(m,p,f,u,g)=>d(m,p,f,u,g)?!0:n(m,p,this,a,f,u,t)}else r||(a?r=(d,m,p,f)=>n(d,m,this,a,p,f,t):r=(d,m,p)=>p);let l=!1,h=0;const c=this._roots;for(let d=0,m=c.length;d<m;d++){const p=c[d];if(l=Oh(this,d,s,r,i,h),l)break;h+=p.byteLength/Ie}return We.releasePrimitive(t),l}bvhcast(e,t,n){let{intersectsRanges:i,intersectsTriangles:s}=n;const r=We.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,h=this.indirect?f=>{const u=this.resolveTriangleIndex(f);be(r,u*3,a,l)}:f=>{be(r,f*3,a,l)},c=We.getPrimitive(),d=e.geometry.index,m=e.geometry.attributes.position,p=e.indirect?f=>{const u=e.resolveTriangleIndex(f);be(c,u*3,d,m)}:f=>{be(c,f*3,d,m)};if(s){const f=(u,g,y,w,x,v,b,D)=>{for(let T=y,k=y+w;T<k;T++){p(T),c.a.applyMatrix4(t),c.b.applyMatrix4(t),c.c.applyMatrix4(t),c.needsUpdate=!0;for(let P=u,I=u+g;P<I;P++)if(h(P),r.needsUpdate=!0,s(r,c,P,T,x,v,b,D))return!0}return!1};if(i){const u=i;i=function(g,y,w,x,v,b,D,T){return u(g,y,w,x,v,b,D,T)?!0:f(g,y,w,x,v,b,D,T)}}else i=f}return du(this,e,t,i)}intersectsBox(e,t){return ui.set(e.min,e.max,t),ui.needsUpdate=!0,this.shapecast({intersectsBounds:n=>ui.intersectsBox(n),intersectsTriangle:n=>ui.intersectsTriangle(n)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,n={},i={},s=0,r=1/0){return(this.indirect?hu:eu)(this,e,t,n,i,s,r)}closestPointToPoint(e,t={},n=0,i=1/0){return zh(this,e,t,n,i)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(n=>{we(0,new Float32Array(n),co),e.union(co)}),e}}const ho=1e-6,pu=ho*.5,uo=Math.pow(10,-Math.log10(ho)),mu=pu*uo;function tt(o){return~~(o*uo+mu)}function gu(o){return`${tt(o.x)},${tt(o.y)}`}function fo(o){return`${tt(o.x)},${tt(o.y)},${tt(o.z)}`}function yu(o){return`${tt(o.x)},${tt(o.y)},${tt(o.z)},${tt(o.w)}`}function wu(o,e,t){t.direction.subVectors(e,o).normalize();const n=o.dot(t.direction);return t.origin.copy(o).addScaledVector(t.direction,-n),t}function po(){return typeof SharedArrayBuffer<"u"}function xu(o){if(o.buffer instanceof SharedArrayBuffer)return o;const e=o.constructor,t=o.buffer,n=new SharedArrayBuffer(t.byteLength),i=new Uint8Array(t);return new Uint8Array(n).set(i,0),new e(n)}function vu(o,e=ArrayBuffer){return o>65535?new Uint32Array(new e(4*o)):new Uint16Array(new e(2*o))}function bu(o,e){if(!o.index){const t=o.attributes.position.count,n=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=vu(t,n);o.setIndex(new _.BufferAttribute(i,1));for(let s=0;s<t;s++)i[s]=s}}function _u(o){return o.index?o.index.count:o.attributes.position.count}function ws(o){return _u(o)/3}const Mu=1e-8,Su=new _.Vector3;function Au(o){return~~(o/3)}function Cu(o){return o%3}function mo(o,e){return o.start-e.start}function go(o,e){return Su.subVectors(e,o.origin).dot(o.direction)}function Tu(o,e,t,n=Mu){o.sort(mo),e.sort(mo);for(let a=0;a<o.length;a++){const l=o[a];for(let h=0;h<e.length;h++){const c=e[h];if(!(c.start>l.end)){if(l.end<c.start||c.end<l.start)continue;if(l.start<=c.start&&l.end>=c.end)s(c.end,l.end)||o.splice(a+1,0,{start:c.end,end:l.end,index:l.index}),l.end=c.start,c.start=0,c.end=0;else if(l.start>=c.start&&l.end<=c.end)s(l.end,c.end)||e.splice(h+1,0,{start:l.end,end:c.end,index:c.index}),c.end=l.start,l.start=0,l.end=0;else if(l.start<=c.start&&l.end<=c.end){const d=l.end;l.end=c.start,c.start=d}else if(l.start>=c.start&&l.end>=c.end){const d=c.end;c.end=l.start,l.start=d}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(c.index)||t.set(c.index,[]),t.get(l.index).push(c.index),t.get(c.index).push(l.index),r(c)&&(e.splice(h,1),h--),r(l)){o.splice(a,1),a--;break}}}i(o),i(e);function i(a){for(let l=0;l<a.length;l++)r(a[l])&&(a.splice(l,1),l--)}function s(a,l){return Math.abs(l-a)<n}function r(a){return Math.abs(a.end-a.start)<n}}const yo=1e-5,wo=1e-4;class Pu{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const t=this._rays,n=e.clone();n.direction.multiplyScalar(-1);let i=1/0,s=null;for(let l=0,h=t.length;l<h;l++){const c=t[l];if(r(c,e)&&r(c,n))continue;const d=a(c,e),m=a(c,n),p=Math.min(d,m);p<i&&(i=p,s=c)}return s;function r(l,h){const c=l.origin.distanceTo(h.origin)>yo;return l.direction.angleTo(h.direction)>wo||c}function a(l,h){const c=l.origin.distanceTo(h.origin),d=l.direction.angleTo(h.direction);return c/yo+d/wo}}}const xs=new _.Vector3,vs=new _.Vector3,di=new _.Ray;function Du(o,e,t){const n=o.attributes,i=o.index,s=n.position,r=new Map,a=new Map,l=Array.from(e),h=new Pu;for(let c=0,d=l.length;c<d;c++){const m=l[c],p=Au(m),f=Cu(m);let u=3*p+f,g=3*p+(f+1)%3;i&&(u=i.getX(u),g=i.getX(g)),xs.fromBufferAttribute(s,u),vs.fromBufferAttribute(s,g),wu(xs,vs,di);let y,w=h.findClosestRay(di);w===null&&(w=di.clone(),h.addRay(w)),a.has(w)||a.set(w,{forward:[],reverse:[],ray:w}),y=a.get(w);let x=go(w,xs),v=go(w,vs);x>v&&([x,v]=[v,x]),di.direction.dot(w.direction)<0?y.reverse.push({start:x,end:v,index:m}):y.forward.push({start:x,end:v,index:m})}return a.forEach(({forward:c,reverse:d},m)=>{Tu(c,d,r,t),c.length===0&&d.length===0&&a.delete(m)}),{disjointConnectivityMap:r,fragmentMap:a}}const ku=new _.Vector2,bs=new _.Vector3,Iu=new _.Vector4,_s=["","",""];class Lu{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const n=this.data[e*3+t];return n===-1?-1:~~(n/3)}getSiblingEdgeIndex(e,t){const n=this.data[e*3+t];return n===-1?-1:n%3}getDisjointSiblingTriangleIndices(e,t){const n=e*3+t,i=this.disjointConnections.get(n);return i?i.map(s=>~~(s/3)):[]}getDisjointSiblingEdgeIndices(e,t){const n=e*3+t,i=this.disjointConnections.get(n);return i?i.map(s=>s%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:n,matchDisjointEdges:i,degenerateEpsilon:s}=this,r=t?x:w,a=new Map,{attributes:l}=e,h=t?Object.keys(l):null,c=e.index,d=l.position;let m=ws(e);const p=m;let f=0;n&&(f=e.drawRange.start,e.drawRange.count!==1/0&&(m=~~(e.drawRange.count/3)));let u=this.data;(!u||u.length<3*p)&&(u=new Int32Array(3*p)),u.fill(-1);let g=0,y=new Set;for(let v=f,b=m*3+f;v<b;v+=3){const D=v;for(let T=0;T<3;T++){let k=D+T;c&&(k=c.getX(k)),_s[T]=r(k)}for(let T=0;T<3;T++){const k=(T+1)%3,P=_s[T],I=_s[k],z=`${I}_${P}`;if(a.has(z)){const C=D+T,E=a.get(z);u[C]=E,u[E]=C,a.delete(z),g+=2,y.delete(E)}else{const C=`${P}_${I}`,E=D+T;a.set(C,E),y.add(E)}}}if(i){const{fragmentMap:v,disjointConnectivityMap:b}=Du(e,y,s);y.clear(),v.forEach(({forward:D,reverse:T})=>{D.forEach(({index:k})=>y.add(k)),T.forEach(({index:k})=>y.add(k))}),this.unmatchedDisjointEdges=v,this.disjointConnections=b,g=m*3-y.size}this.matchedEdges=g,this.unmatchedEdges=y.size,this.data=u;function w(v){return bs.fromBufferAttribute(d,v),fo(bs)}function x(v){let b="";for(let D=0,T=h.length;D<T;D++){const k=l[h[D]];let P;switch(k.itemSize){case 1:P=tt(k.getX(v));break;case 2:P=gu(ku.fromBufferAttribute(k,v));break;case 3:P=fo(bs.fromBufferAttribute(k,v));break;case 4:P=yu(Iu.fromBufferAttribute(k,v));break}b!==""&&(b+="|"),b+=P}return b}}}class fi extends _.Mesh{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new _.Matrix4,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:t}=this,n=e.elements,i=t.elements;for(let s=0;s<16;s++)if(n[s]!==i[s])return!0;return!1}prepareGeometry(){const e=this.geometry,t=e.attributes,n=po();if(n)for(const i in t){const s=t[i];if(s.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");s.array=xu(s.array)}if(e.boundsTree||(bu(e,{useSharedArrayBuffer:n}),e.boundsTree=new ys(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:n})),e.halfEdges||(e.halfEdges=new Lu(e)),!e.groupIndices){const i=ws(e),s=new Uint16Array(i),r=e.groups;for(let a=0,l=r.length;a<l;a++){const{start:h,count:c}=r[a];for(let d=h/3,m=(h+c)/3;d<m;d++)s[d]=a}e.groupIndices=s}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const Eu=1e-14,Ms=new _.Vector3,xo=new _.Vector3,vo=new _.Vector3;function yt(o,e=Eu){Ms.subVectors(o.b,o.a),xo.subVectors(o.c,o.a),vo.subVectors(o.b,o.c);const t=Ms.angleTo(xo),n=Ms.angleTo(vo),i=Math.PI-t-n;return Math.abs(t)<e||Math.abs(n)<e||Math.abs(i)<e||o.a.distanceToSquared(o.b)<e||o.a.distanceToSquared(o.c)<e||o.b.distanceToSquared(o.c)<e}const Ss=1e-10,xn=1e-10,Bu=1e-10,lt=new _.Line3,xe=new _.Line3,ct=new _.Vector3,As=new _.Vector3,bo=new _.Vector3,pi=new _.Plane,Cs=new Ge;class Ou{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new _.Triangle),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class zu{constructor(){this.trianglePool=new Ou,this.triangles=[],this.normal=new _.Vector3,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:n,normal:i}=this;if(Array.isArray(e))for(let s=0,r=e.length;s<r;s++){const a=e[s];if(s===0)a.getNormal(i);else if(Math.abs(1-a.getNormal(ct).dot(i))>Ss)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=n.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(i);const s=n.getTriangle();s.copy(e),t.push(s)}}splitByTriangle(e){const{normal:t,triangles:n}=this;if(e.getNormal(As).normalize(),Math.abs(1-Math.abs(As.dot(t)))<Bu){this.coplanarTriangleUsed=!0;for(let s=0,r=n.length;s<r;s++){const a=n[s];a.coplanarCount=0}const i=[e.a,e.b,e.c];for(let s=0;s<3;s++){const r=(s+1)%3,a=i[s],l=i[r];ct.subVectors(l,a).normalize(),bo.crossVectors(As,ct),pi.setFromNormalAndCoplanarPoint(bo,a),this.splitByPlane(pi,e)}}else e.getPlane(pi),this.splitByPlane(pi,e)}splitByPlane(e,t){const{triangles:n,trianglePool:i}=this;Cs.copy(t),Cs.needsUpdate=!0;for(let s=0,r=n.length;s<r;s++){const a=n[s];if(!Cs.intersectsTriangle(a,lt,!0))continue;const{a:l,b:h,c}=a;let d=0,m=-1,p=!1,f=[],u=[];const g=[l,h,c];for(let y=0;y<3;y++){const w=(y+1)%3;lt.start.copy(g[y]),lt.end.copy(g[w]);const x=e.distanceToPoint(lt.start),v=e.distanceToPoint(lt.end);if(Math.abs(x)<xn&&Math.abs(v)<xn){p=!0;break}if(x>0?f.push(y):u.push(y),Math.abs(x)<xn)continue;let b=!!e.intersectLine(lt,ct);!b&&Math.abs(v)<xn&&(ct.copy(lt.end),b=!0),b&&!(ct.distanceTo(lt.start)<Ss)&&(ct.distanceTo(lt.end)<Ss&&(m=y),d===0?xe.start.copy(ct):xe.end.copy(ct),d++)}if(!p&&d===2&&xe.distance()>xn)if(m!==-1){m=(m+1)%3;let y=0;y===m&&(y=(y+1)%3);let w=y+1;w===m&&(w=(w+1)%3);const x=i.getTriangle();x.a.copy(g[w]),x.b.copy(xe.end),x.c.copy(xe.start),yt(x)||n.push(x),a.a.copy(g[y]),a.b.copy(xe.start),a.c.copy(xe.end),yt(a)&&(n.splice(s,1),s--,r--)}else{const y=f.length>=2?u[0]:f[0];if(y===0){let D=xe.start;xe.start=xe.end,xe.end=D}const w=(y+1)%3,x=(y+2)%3,v=i.getTriangle(),b=i.getTriangle();g[w].distanceToSquared(xe.start)<g[x].distanceToSquared(xe.end)?(v.a.copy(g[w]),v.b.copy(xe.start),v.c.copy(xe.end),b.a.copy(g[w]),b.b.copy(g[x]),b.c.copy(xe.start)):(v.a.copy(g[x]),v.b.copy(xe.start),v.c.copy(xe.end),b.a.copy(g[w]),b.b.copy(g[x]),b.c.copy(xe.end)),a.a.copy(g[y]),a.b.copy(xe.end),a.c.copy(xe.start),yt(v)||n.push(v),yt(b)||n.push(b),yt(a)&&(n.splice(s,1),s--,r--)}else d===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function Nu(o){return o=~~o,o+4-o%4}class _o{constructor(e,t=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(t)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const t=this.array.buffer;this.array=new e(t),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const t=this.type,n=po()?SharedArrayBuffer:ArrayBuffer,i=new t(new n(Nu(e*t.BYTES_PER_ELEMENT)));this.array&&i.set(this.array,0),this.array=i}expand(){const{array:e,expansionFactor:t}=this;this.setSize(e.length*t)}push(...e){let{array:t,length:n}=this;n+e.length>t.length&&(this.expand(),t=this.array);for(let i=0,s=e.length;i<s;i++)t[n+i]=e[i];this.length+=e.length}clear(){this.length=0}}class Ru{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const t=this.getGroupAttrArray("position",e);return t.length/t.itemSize}getTotalLength(e){const{groupCount:t,groupAttributes:n}=this;let i=0;for(let s=0;s<t;s++){const r=n[s];i+=r[e].length}return i}getGroupAttrSet(e=0){const{groupAttributes:t}=this;if(t[e])return this.groupCount=Math.max(this.groupCount,e+1),t[e];const n=t[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=t.length;){const i={};t.push(i);for(const s in n){const r=n[s],a=new _o(r.type);a.itemSize=r.itemSize,a.normalized=r.normalized,i[s]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:n}=this;if(!n[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,n,i){const{groupAttributes:s}=this,a=s[0][e];if(a){if(a.type!==t)for(let l=0,h=s.length;l<h;l++){const c=s[l][e];c.setType(t),c.itemSize=n,c.normalized=i}}else for(let l=0,h=s.length;l<h;l++){const c=new _o(t);c.itemSize=n,c.normalized=i,s[l][e]=c}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(t=>{for(const n in t)t[n].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class Mo{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:n,ids:i}=this;n[e]||(n[e]=[],i.push(e)),n[e].push(t)}}const Fu=0,Uu=1,Vu=2,So=3,ju=4,Ao=5,Co=6,Ze=new _.Ray,To=new _.Matrix4,Ee=new _.Triangle,ht=new _.Vector3,Po=new _.Vector4,Do=new _.Vector4,ko=new _.Vector4,Ts=new _.Vector4,mi=new _.Vector4,gi=new _.Vector4,Io=new _.Line3,Ps=new _.Vector3,Ds=1e-8,Gu=1e-15,Et=-1,Bt=1,yi=-2,wi=2,vn=0,Ot=1,ks=2,Wu=1e-14;let xi=null;function Lo(o){xi=o}function Eo(o,e){o.getMidpoint(Ze.origin),o.getNormal(Ze.direction);const t=e.raycastFirst(Ze,_.DoubleSide);return!!(t&&Ze.direction.dot(t.face.normal)>0)?Et:Bt}function Xu(o,e){function t(){return Math.random()-.5}o.getNormal(Ps),Ze.direction.copy(Ps),o.getMidpoint(Ze.origin);const n=3;let i=0,s=1/0;for(let r=0;r<n;r++){Ze.direction.x+=t()*Ds,Ze.direction.y+=t()*Ds,Ze.direction.z+=t()*Ds,Ze.direction.multiplyScalar(-1);const a=e.raycastFirst(Ze,_.DoubleSide);if(!!(a&&Ze.direction.dot(a.face.normal)>0)&&i++,a!==null&&(s=Math.min(s,a.distance)),s<=Gu)return a.face.normal.dot(Ps)>0?wi:yi;if(i/n>.5||(r-i+1)/n>.5)break}return i/n>.5?Et:Bt}function Zu(o,e){const t=new Mo,n=new Mo;return To.copy(o.matrixWorld).invert().multiply(e.matrixWorld),o.geometry.boundsTree.bvhcast(e.geometry.boundsTree,To,{intersectsTriangles(i,s,r,a){if(!yt(i)&&!yt(s)){let l=i.intersectsTriangle(s,Io,!0);if(!l){const h=i.plane,c=s.plane,d=h.normal,m=c.normal;d.dot(m)===1&&Math.abs(h.constant-c.constant)<Wu&&(l=!0)}if(l){let h=o.geometry.boundsTree.resolveTriangleIndex(r),c=e.geometry.boundsTree.resolveTriangleIndex(a);t.add(h,c),n.add(c,h),xi&&(xi.addEdge(Io),xi.addIntersectingTriangles(r,i,a,s))}}return!1}}),{aIntersections:t,bIntersections:n}}function qu(o,e,t,n,i,s,r=!1){const a=t.attributes,l=t.index,h=o*3,c=l.getX(h+0),d=l.getX(h+1),m=l.getX(h+2);for(const p in s){const f=a[p],u=s[p];if(!(p in a))throw new Error(`CSG Operations: Attribute ${p} not available on geometry.`);const g=f.itemSize;p==="position"?(Ee.a.fromBufferAttribute(f,c).applyMatrix4(n),Ee.b.fromBufferAttribute(f,d).applyMatrix4(n),Ee.c.fromBufferAttribute(f,m).applyMatrix4(n),Is(Ee.a,Ee.b,Ee.c,e,3,u,r)):p==="normal"?(Ee.a.fromBufferAttribute(f,c).applyNormalMatrix(i),Ee.b.fromBufferAttribute(f,d).applyNormalMatrix(i),Ee.c.fromBufferAttribute(f,m).applyNormalMatrix(i),r&&(Ee.a.multiplyScalar(-1),Ee.b.multiplyScalar(-1),Ee.c.multiplyScalar(-1)),Is(Ee.a,Ee.b,Ee.c,e,3,u,r,!0)):(Po.fromBufferAttribute(f,c),Do.fromBufferAttribute(f,d),ko.fromBufferAttribute(f,m),Is(Po,Do,ko,e,g,u,r))}}function Ku(o,e,t,n,i,s,r,a=!1){Ls(o,n,i,s,r,a),Ls(a?t:e,n,i,s,r,a),Ls(a?e:t,n,i,s,r,a)}function Bo(o,e,t=!1){switch(o){case Fu:if(e===Bt||e===wi&&!t)return Ot;break;case Uu:if(t){if(e===Et)return vn}else if(e===Bt||e===yi)return Ot;break;case Vu:if(t){if(e===Bt||e===yi)return Ot}else if(e===Et)return vn;break;case ju:if(e===Et)return vn;if(e===Bt)return Ot;break;case So:if(e===Et||e===wi&&!t)return Ot;break;case Ao:if(!t&&(e===Bt||e===yi))return Ot;break;case Co:if(!t&&(e===Et||e===wi))return Ot;break;default:throw new Error(`Unrecognized CSG operation enum "${o}".`)}return ks}function Is(o,e,t,n,i,s,r=!1,a=!1){const l=h=>{s.push(h.x),i>1&&s.push(h.y),i>2&&s.push(h.z),i>3&&s.push(h.w)};Ts.set(0,0,0,0).addScaledVector(o,n.a.x).addScaledVector(e,n.a.y).addScaledVector(t,n.a.z),mi.set(0,0,0,0).addScaledVector(o,n.b.x).addScaledVector(e,n.b.y).addScaledVector(t,n.b.z),gi.set(0,0,0,0).addScaledVector(o,n.c.x).addScaledVector(e,n.c.y).addScaledVector(t,n.c.z),a&&(Ts.normalize(),mi.normalize(),gi.normalize()),l(Ts),r?(l(gi),l(mi)):(l(mi),l(gi))}function Ls(o,e,t,n,i,s=!1){for(const r in i){const a=e[r],l=i[r];if(!(r in e))throw new Error(`CSG Operations: Attribute ${r} no available on geometry.`);const h=a.itemSize;r==="position"?(ht.fromBufferAttribute(a,o).applyMatrix4(t),l.push(ht.x,ht.y,ht.z)):r==="normal"?(ht.fromBufferAttribute(a,o).applyNormalMatrix(n),s&&ht.multiplyScalar(-1),l.push(ht.x,ht.y,ht.z)):(l.push(a.getX(o)),h>1&&l.push(a.getY(o)),h>2&&l.push(a.getZ(o)),h>3&&l.push(a.getW(o)))}}class Yu{constructor(e){this.triangle=new _.Triangle().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new _.Triangle().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const n in t)e.push(t[n]);return e}}class Oo{constructor(){this.data={}}addTriangleIntersection(e,t,n,i){const{data:s}=this;s[e]||(s[e]=new Yu(t)),s[e].addTriangle(n,i)}getTrianglesAsArray(e=null){const{data:t}=this,n=[];if(e!==null)e in t&&n.push(t[e].triangle);else for(const i in t)n.push(t[i].triangle);return n}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(n=>parseInt(n)):[]}getIntersectionsAsArray(e=null,t=null){const{data:n}=this,i=new Set,s=[],r=a=>{if(n[a])if(t!==null)n[a].intersects[t]&&s.push(n[a].intersects[t]);else{const l=n[a].intersects;for(const h in l)i.has(h)||(i.add(h),s.push(l[h]))}};if(e!==null)r(e);else for(const a in n)r(a);return s}reset(){this.data={}}}class $u{constructor(){this.enabled=!1,this.triangleIntersectsA=new Oo,this.triangleIntersectsB=new Oo,this.intersectionEdges=[]}addIntersectingTriangles(e,t,n,i){const{triangleIntersectsA:s,triangleIntersectsB:r}=this;s.addTriangleIntersection(e,t,n,i),r.addTriangleIntersection(n,i,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),Lo(this))}complete(){this.enabled&&Lo(null)}}const wt=new _.Matrix4,vi=new _.Matrix3,zt=new _.Triangle,bi=new _.Triangle,xt=new _.Triangle,_i=new _.Triangle,Ye=[],Nt=[];function Hu(o){for(const e of o)return e}function Ju(o,e,t,n,i,s={}){const{useGroups:r=!0}=s,{aIntersections:a,bIntersections:l}=Zu(o,e),h=[];let c=null,d;return d=r?0:-1,zo(o,e,a,t,!1,n,i,d),No(o,e,a,t,!1,i,d),t.findIndex(p=>p!==Co&&p!==Ao)!==-1&&(d=r?o.geometry.groups.length||1:-1,zo(e,o,l,t,!0,n,i,d),No(e,o,l,t,!0,i,d)),Ye.length=0,Nt.length=0,{groups:h,materials:c}}function zo(o,e,t,n,i,s,r,a=0){const l=o.matrixWorld.determinant()<0;wt.copy(e.matrixWorld).invert().multiply(o.matrixWorld),vi.getNormalMatrix(o.matrixWorld).multiplyScalar(l?-1:1);const h=o.geometry.groupIndices,c=o.geometry.index,d=o.geometry.attributes.position,m=e.geometry.boundsTree,p=e.geometry.index,f=e.geometry.attributes.position,u=t.ids,g=t.intersectionSet;for(let y=0,w=u.length;y<w;y++){const x=u[y],v=a===-1?0:h[x]+a,b=3*x,D=c.getX(b+0),T=c.getX(b+1),k=c.getX(b+2);zt.a.fromBufferAttribute(d,D).applyMatrix4(wt),zt.b.fromBufferAttribute(d,T).applyMatrix4(wt),zt.c.fromBufferAttribute(d,k).applyMatrix4(wt),s.reset(),s.initialize(zt);const P=g[x];for(let z=0,C=P.length;z<C;z++){const E=3*P[z],M=p.getX(E+0),B=p.getX(E+1),V=p.getX(E+2);bi.a.fromBufferAttribute(f,M),bi.b.fromBufferAttribute(f,B),bi.c.fromBufferAttribute(f,V),s.splitByTriangle(bi)}const I=s.triangles;for(let z=0,C=I.length;z<C;z++){const E=I[z],M=s.coplanarTriangleUsed?Xu(E,m):Eo(E,m);Ye.length=0,Nt.length=0;for(let B=0,V=n.length;B<V;B++){const U=Bo(n[B],M,i);U!==ks&&(Nt.push(U),Ye.push(r[B].getGroupAttrSet(v)))}if(Ye.length!==0){zt.getBarycoord(E.a,_i.a),zt.getBarycoord(E.b,_i.b),zt.getBarycoord(E.c,_i.c);for(let B=0,V=Ye.length;B<V;B++){const U=Ye[B],G=Nt[B]===vn;qu(x,_i,o.geometry,o.matrixWorld,vi,U,l!==G)}}}}return u.length}function No(o,e,t,n,i,s,r=0){const a=o.matrixWorld.determinant()<0;wt.copy(e.matrixWorld).invert().multiply(o.matrixWorld),vi.getNormalMatrix(o.matrixWorld).multiplyScalar(a?-1:1);const l=e.geometry.boundsTree,h=o.geometry.groupIndices,c=o.geometry.index,d=o.geometry.attributes,m=d.position,p=[],f=o.geometry.halfEdges,u=new Set,g=ws(o.geometry);for(let y=0,w=g;y<w;y++)y in t.intersectionSet||u.add(y);for(;u.size>0;){const y=Hu(u);u.delete(y),p.push(y);const w=3*y,x=c.getX(w+0),v=c.getX(w+1),b=c.getX(w+2);xt.a.fromBufferAttribute(m,x).applyMatrix4(wt),xt.b.fromBufferAttribute(m,v).applyMatrix4(wt),xt.c.fromBufferAttribute(m,b).applyMatrix4(wt);const D=Eo(xt,l);Nt.length=0,Ye.length=0;for(let T=0,k=n.length;T<k;T++){const P=Bo(n[T],D,i);P!==ks&&(Nt.push(P),Ye.push(s[T]))}for(;p.length>0;){const T=p.pop();for(let k=0;k<3;k++){const P=f.getSiblingTriangleIndex(T,k);P!==-1&&u.has(P)&&(p.push(P),u.delete(P))}if(Ye.length!==0){const k=3*T,P=c.getX(k+0),I=c.getX(k+1),z=c.getX(k+2),C=r===-1?0:h[T]+r;if(xt.a.fromBufferAttribute(m,P),xt.b.fromBufferAttribute(m,I),xt.c.fromBufferAttribute(m,z),!yt(xt))for(let E=0,M=Ye.length;E<M;E++){const B=Nt[E],V=Ye[E].getGroupAttrSet(C),U=B===vn;Ku(P,I,z,d,o.matrixWorld,vi,V,U!==a)}}}}}function Qu(o){for(let e=0;e<o.length-1;e++){const t=o[e],n=o[e+1];if(t.materialIndex===n.materialIndex){const i=t.start,s=n.start+n.count;n.start=i,n.count=s-i,o.splice(e,1),e--}}}function ed(o,e,t,n){t.clear();const i=o.attributes;for(let s=0,r=n.length;s<r;s++){const a=n[s],l=i[a];t.initializeArray(a,l.array.constructor,l.itemSize,l.normalized)}for(const s in t.attributes)n.includes(s)||t.delete(s);for(const s in e.attributes)n.includes(s)||(e.deleteAttribute(s),e.dispose())}function td(o,e,t){let n=!1,i=-1;const s=o.attributes,r=e.groupAttributes[0];for(const l in r){const h=e.getTotalLength(l),c=e.getType(l),d=e.getItemSize(l),m=e.getNormalized(l);let p=s[l];(!p||p.array.length<h)&&(p=new _.BufferAttribute(new c(h),d,m),o.setAttribute(l,p),n=!0);let f=0;for(let u=0,g=Math.min(t.length,e.groupCount);u<g;u++){const y=t[u].index,{array:w,type:x,length:v}=e.groupAttributes[y][l],b=new x(w.buffer,0,v);p.array.set(b,f),f+=b.length}p.needsUpdate=!0,i=h/p.itemSize}if(o.index){const l=o.index.array;if(l.length<i)o.index=null,n=!0;else for(let h=0,c=l.length;h<c;h++)l[h]=h}let a=0;o.clearGroups();for(let l=0,h=Math.min(t.length,e.groupCount);l<h;l++){const{index:c,materialIndex:d}=t[l],m=e.getCount(c);m!==0&&(o.addGroup(a,m,d),a+=m)}o.setDrawRange(0,i),o.boundsTree=null,n&&o.dispose()}function Ro(o,e){let t=e;return Array.isArray(e)||(t=[],o.forEach(n=>{t[n.materialIndex]=e})),t}class nd{constructor(){this.triangleSplitter=new zu,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new $u}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,n,i=new fi){let s=!0;if(Array.isArray(n)||(n=[n]),Array.isArray(i)||(i=[i],s=!1),i.length!==n.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:r,attributeData:a,attributes:l,useGroups:h,consolidateGroups:c,debug:d}=this;for(;a.length<i.length;)a.push(new Ru);i.forEach((y,w)=>{ed(e.geometry,y.geometry,a[w],l)}),d.init(),Ju(e,t,n,r,a,{useGroups:h}),d.complete();const m=this.getGroupRanges(e.geometry),p=Ro(m,e.material),f=this.getGroupRanges(t.geometry),u=Ro(f,t.material);f.forEach(y=>y.materialIndex+=p.length);let g=[...m,...f].map((y,w)=>({...y,index:w}));if(h){const y=[...p,...u];c&&(g=g.map(x=>{const v=y[x.materialIndex];return x.materialIndex=y.indexOf(v),x}).sort((x,v)=>x.materialIndex-v.materialIndex));const w=[];for(let x=0,v=y.length;x<v;x++){let b=!1;for(let D=0,T=g.length;D<T;D++){const k=g[D];k.materialIndex===x&&(b=!0,k.materialIndex=w.length)}b&&w.push(y[x])}i.forEach(x=>{x.material=w})}else g=[{start:0,count:1/0,index:0,materialIndex:0}],i.forEach(y=>{y.material=p[0]});return i.forEach((y,w)=>{const x=y.geometry;td(x,a[w],g),c&&Qu(x.groups)}),s?i:i[0]}evaluateHierarchy(e,t=new fi){e.updateMatrixWorld(!0);const n=(s,r)=>{const a=s.children;for(let l=0,h=a.length;l<h;l++){const c=a[l];c.isOperationGroup?n(c,r):r(c)}},i=s=>{const r=s.children;let a=!1;for(let h=0,c=r.length;h<c;h++){const d=r[h];a=i(d)||a}const l=s.isDirty();if(l&&s.markUpdated(),a&&!s.isOperationGroup){let h;return n(s,c=>{h?h=this.evaluate(h,c,c.operation):h=this.evaluate(s,c,c.operation)}),s._cachedGeometry=h.geometry,s._cachedMaterials=h.material,!0}else return a||l};return i(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class id{engine;planeObjects=[];planes=[];isActive=!1;evaluator;geometryCache=new Map;sectionMeshes=new Map;planeGroup;planeSize=1e3;sourceMeshes=new Map;planeThickness=.01;updateThrottleTime=100;lastUpdateTime=0;pendingUpdate=!1;updateTimer=null;cacheExpireTime=3e4;planeStates=new Map;constructor(e,t={}){this.engine=e,this.evaluator=new nd,this.planeGroup=new S.Group,this.planeGroup.name="CSG_ClippingPlanes_Optimized",t.updateThrottleTime!==void 0&&(this.updateThrottleTime=t.updateThrottleTime),t.cacheExpireTime!==void 0&&(this.cacheExpireTime=t.cacheExpireTime),t.planeThickness!==void 0&&(this.planeThickness=t.planeThickness),this.evaluator.attributes=["position","normal"],this.evaluator.useGroups=!1}init(){this.calculateSceneSize(),this.engine.scene.add(this.planeGroup),this.planes.forEach((e,t)=>{const n=this.createEmptySectionMesh(e,t);this.planeGroup.add(n),this.sectionMeshes.set(`plane_${t}`,n),this.planeObjects.push(n),this.planeStates.set(t,{constant:e.constant,normal:e.normal.clone()})})}createEmptySectionMesh(e,t){const n=new S.BufferGeometry,i=new S.MeshStandardMaterial({color:new S.Color(33023),metalness:.1,roughness:.75,side:S.DoubleSide,depthWrite:!0,depthTest:!0,clippingPlanes:this.planes.filter((r,a)=>a!==t)}),s=new S.Mesh(n,i);return s.name=`CSG_Section_Optimized_${t}`,s.visible=!1,s.renderOrder=t+1,s}active(){this.isActive=!0,this.requestUpdate(),this.planeObjects.forEach(e=>{e.visible=!0})}disActive(){this.isActive=!1,this.planeObjects.forEach(e=>{e.visible=!1}),this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null)}setSourceMeshes(e){this.sourceMeshes.clear(),e.forEach(t=>{const n=t.uuid;this.sourceMeshes.set(n,t)}),this.isActive&&this.requestUpdate()}addSourceMesh(e){const t=e.uuid;this.sourceMeshes.has(t)||(this.sourceMeshes.set(t,e),this.isActive&&this.requestUpdate())}removeSourceMesh(e){const t=e.uuid;this.sourceMeshes.delete(t)&&(this.clearMeshCache(t),this.isActive&&this.requestUpdate())}requestUpdate(){if(!this.isActive)return;const e=Date.now(),t=e-this.lastUpdateTime;t>=this.updateThrottleTime?(this.lastUpdateTime=e,this.pendingUpdate=!1):(this.pendingUpdate=!0,this.updateTimer&&clearTimeout(this.updateTimer),this.updateTimer=setTimeout(()=>{this.pendingUpdate&&this.isActive&&(this.lastUpdateTime=Date.now(),this.pendingUpdate=!1),this.updateTimer=null},this.updateThrottleTime-t))}updateAllSections(){this.isActive&&(this.planes.forEach((e,t)=>{if(Math.abs(e.constant)<99999)this.hasPlaneChanged(t,e)&&(this.updateSection(e,t),this.updatePlaneState(t,e));else{const n=this.sectionMeshes.get(`plane_${t}`);n&&(n.visible=!1)}}),this.cleanExpiredCache())}hasPlaneChanged(e,t){const n=this.planeStates.get(e);if(!n)return!0;const i=Math.abs(n.constant-t.constant)>1e-4,s=!n.normal.equals(t.normal);return i||s}updatePlaneState(e,t){this.planeStates.set(e,{constant:t.constant,normal:t.normal.clone()})}getPlaneHash(e){const t=e.normal,n=e.constant;return`${t.x.toFixed(4)}_${t.y.toFixed(4)}_${t.z.toFixed(4)}_${n.toFixed(4)}`}getCacheKey(e,t){return`${e}_plane_${t}`}updateSection(e,t){const n=this.sectionMeshes.get(`plane_${t}`);if(!n)return;const i=this.getPlaneHash(e),s=[];if(this.sourceMeshes.forEach((r,a)=>{const l=this.getCacheKey(a,t),h=this.geometryCache.get(l);if(h&&h.planeHash===i)s.push(h.geometry.clone()),h.timestamp=Date.now();else try{const c=this.createPlaneBrush(e),d=new fi(r.geometry);r.updateMatrixWorld(!0),d.matrix.copy(r.matrixWorld),d.updateMatrixWorld();const m=this.evaluator.evaluate(c,d,So);m&&m.geometry.attributes.position.count>0?(s.push(m.geometry),this.geometryCache.set(l,{geometry:m.geometry.clone(),planeHash:i,timestamp:Date.now()})):this.geometryCache.delete(l)}catch(c){console.warn(`CSG intersection failed for mesh ${a}:`,c)}}),s.length>0){const r=this.mergeGeometries(s);n.geometry&&n.geometry.dispose(),n.geometry=r,n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.scale.set(1,1,1),n.updateMatrixWorld()}else n.visible=!1;s.forEach(r=>r.dispose())}clearMeshCache(e){const t=[];this.geometryCache.forEach((n,i)=>{i.startsWith(e)&&(n.geometry.dispose(),t.push(i))}),t.forEach(n=>this.geometryCache.delete(n))}cleanExpiredCache(){const e=Date.now(),t=[];this.geometryCache.forEach((n,i)=>{e-n.timestamp>this.cacheExpireTime&&(n.geometry.dispose(),t.push(i))}),t.forEach(n=>this.geometryCache.delete(n))}clearAllCache(){this.geometryCache.forEach(e=>{e.geometry.dispose()}),this.geometryCache.clear()}createPlaneBrush(e){const t=new S.BoxGeometry(this.planeSize,this.planeThickness,this.planeSize);t.translate(0,e.constant,0),t.applyQuaternion(new S.Quaternion().setFromUnitVectors(new S.Vector3(0,-1,0),e.normal));const n=new S.Mesh(t),i=new fi(t);return i.matrix.copy(n.matrixWorld),i.updateMatrixWorld(),i}mergeGeometries(e){if(e.length===1)return e[0].clone();const t=new S.BufferGeometry,n=[],i=[],s=[];let r=0;return e.forEach(a=>{const l=a.attributes.position,h=a.attributes.normal;for(let c=0;c<l.count;c++)n.push(l.getX(c),l.getY(c),l.getZ(c));if(h)for(let c=0;c<h.count;c++)i.push(h.getX(c),h.getY(c),h.getZ(c));if(a.index)for(let c=0;c<a.index.count;c++)s.push(a.index.getX(c)+r);r+=l.count}),t.setAttribute("position",new S.Float32BufferAttribute(n,3)),i.length>0?t.setAttribute("normal",new S.Float32BufferAttribute(i,3)):t.computeVertexNormals(),s.length>0&&t.setIndex(s),t}calculateSceneSize(){const e=new S.Box3;if(this.engine.scene.traverse(t=>{if(t.isMesh&&t.geometry){const n=new S.Box3().setFromObject(t);e.union(n)}}),e.isEmpty())this.planeSize=1e3;else{const t=e.getSize(new S.Vector3),n=Math.max(t.x,t.y,t.z);this.planeSize=n*3}}update(){this.isActive&&this.pendingUpdate&&!this.updateTimer&&this.requestUpdate()}dispose(){this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null),this.clearAllCache(),this.planeObjects.forEach(e=>{e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(t=>t.dispose()):e.material.dispose())}),this.sectionMeshes.clear(),this.planeObjects=[],this.sourceMeshes.clear(),this.planeGroup.parent&&this.planeGroup.parent.remove(this.planeGroup)}setSectionColor(e){this.planeObjects.forEach(t=>{t.material instanceof S.MeshStandardMaterial&&t.material.color.set(e)})}getCacheStats(){return{cacheSize:this.geometryCache.size,sourceMeshCount:this.sourceMeshes.size,sectionMeshCount:this.sectionMeshes.size}}setPlaneThickness(e){if(e<=0){console.warn("Plane thickness must be positive");return}this.planeThickness=e,this.clearAllCache(),this.isActive&&this.requestUpdate()}getPlaneThickness(){return this.planeThickness}showSections(){this.sectionMeshes.forEach(e=>{e.geometry?.attributes.position?.count&&e.geometry.attributes.position.count>0&&(e.visible=!0)})}hideSections(){this.sectionMeshes.forEach(e=>{e.visible=!1})}showSection(){this.planeGroup.visible=!0}hideSection(){this.planeGroup.visible=!1}toggleSectionsVisibility(){let e=!1;return this.sectionMeshes.forEach(t=>{t.visible&&(e=!0)}),e?(this.hideSections(),!1):(this.showSections(),!0)}toggleSectionVisibility(e){const t=this.sectionMeshes.get(`plane_${e}`);return t?(t.visible=!t.visible,t.visible):!1}}class sd{engine;isActive=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;csgClipping=null;useCsgClipping=!1;constructor(e,t){this.engine=e,this.meshs=[],t?.useCsgClipping!==void 0&&(this.useCsgClipping=t.useCsgClipping),this.useCsgClipping&&this.initCsgClipping()}initCsgClipping(){this.csgClipping=new id(this.engine,{updateThrottleTime:150,cacheExpireTime:45e3}),this.csgClipping.planes=this.engine.sectionPlane,this.csgClipping.init()}active(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0,this.init())}disActive(){this.init(),this.isActive=!1,this.engine.handelBehaved.disActive(),this.csgClipping&&this.csgClipping.disActive(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})}),this.engine.interactionModule.init(),this.engine.interactionModule.active()}disabled(){this.isActive=!1,this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(){let e=this.engine.octreeBox.getBoundingBox();this.maxBox=JSON.parse(JSON.stringify(e)),this.box=e,this.updata_face(e)}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box)}setBox(e){this.box=e,this.updata_face(e)}reverseBox(){}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0)if(this.pickPoint=t[0].point,this.pickNormal=t[0].face.normal,this.engine.controls.enabled=!1,this.pickMesh=t[0].object,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const n=new S.Plane;n.setFromNormalAndCoplanarPoint(new S.Vector3(0,1,0),this.pickPoint),this.plane=n}else{let n=new S.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const i=new S.Plane;i.setFromNormalAndCoplanarPoint(n.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=i}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.engine.controls.enabled=!0,this.csgClipping&&this.isActive}handleMouseMove(e){this.meshs.forEach(n=>{n.material.opacity=0});const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const n=new S.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,n)){let i=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());this.pickMesh.name=="前"||this.pickMesh.name=="左"||this.pickMesh.name=="底"?this.box.min=this.box_.min.clone().add(this.pickNormal.clone().setLength(i)):this.box.max=this.box_.max.clone().add(this.pickNormal.clone().setLength(i)),this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){let e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,n=this.maxBox.max.z-this.maxBox.min.z,i=(this.box.min.x-this.maxBox.min.x)/e*100,s=(this.box.max.x-this.maxBox.min.x)/e*100,r=(this.box.min.y-this.maxBox.min.y)/t*100,a=(this.box.max.y-this.maxBox.min.y)/t*100,l=(this.box.min.z-this.maxBox.min.z)/n*100,h=(this.box.max.z-this.maxBox.min.z)/n*100;i<0&&(i=0),s<0&&(s=0),r<0&&(r=0),a<0&&(a=0),l<0&&(l=0),h<0&&(h=0),i>100&&(i=100),s>100&&(s=100),r>100&&(r=100),a>100&&(a=100),l>100&&(l=100),h>100&&(h=100);let c={x:{min:i,max:s},y:{min:r,max:a},z:{min:l,max:h}};this.engine.events.trigger(_e.SectionMove,c)}updata_face(e){let t=this,n=[new S.Vector3(e.min.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.min.z),new S.Vector3(e.min.x,e.max.y,e.min.z)],i=[new S.Vector3(e.min.x,e.min.y,e.max.z),new S.Vector3(e.max.x,e.min.y,e.max.z),new S.Vector3(e.max.x,e.max.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.max.z)],s=[new S.Vector3(e.max.x,e.min.y,e.max.z),new S.Vector3(e.max.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.max.z)],r=[new S.Vector3(e.min.x,e.min.y,e.min.z),new S.Vector3(e.min.x,e.min.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.min.z)],a=[new S.Vector3(e.min.x,e.max.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.min.z),new S.Vector3(e.max.x,e.max.y,e.max.z),new S.Vector3(e.min.x,e.max.y,e.max.z)],l=[new S.Vector3(e.min.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.min.y,e.min.z),new S.Vector3(e.max.x,e.min.y,e.max.z),new S.Vector3(e.min.x,e.min.y,e.max.z)];h(n,new S.Vector3(0,0,-1),"前"),h(i,new S.Vector3(0,0,1),"后"),h(s,new S.Vector3(1,0,0),"右"),h(r,new S.Vector3(-1,0,0),"左"),h(a,new S.Vector3(0,1,0),"顶"),h(l,new S.Vector3(0,-1,0),"底");function h(c,d,m){const p=new S.BufferGeometry,f=new Float32Array([c[0].x,c[0].y,c[0].z,c[1].x,c[1].y,c[1].z,c[2].x,c[2].y,c[2].z,c[3].x,c[3].y,c[3].z]),u=[0,1,2,0,2,3];p.setAttribute("position",new S.BufferAttribute(f,3)),p.setIndex(u);let g=t.engine.scene.children.find(D=>D.type=="Group"&&D.name=="ClippingBox");g==null&&(g=new S.Group,g.name="ClippingBox",t.engine.scene.add(g));let y=t.meshs.find(D=>D.name==m);if(y==null){const D=new S.MeshBasicMaterial({color:65280,transparent:!0,opacity:0,side:S.DoubleSide});D.polygonOffset=!0,D.polygonOffsetFactor=1,D.polygonOffsetUnits=4;const T=new S.Mesh(p,D);T.normal=d,T.name=m,g.add(T),t.meshs.push(T)}else y.geometry=p;const w=new Float32Array([c[0].x,c[0].y,c[0].z,c[1].x,c[1].y,c[1].z,c[2].x,c[2].y,c[2].z,c[3].x,c[3].y,c[3].z,c[0].x,c[0].y,c[0].z]);let x=new S.LineBasicMaterial({color:255}),v=new S.BufferGeometry;v.setAttribute("position",new S.BufferAttribute(w,3));let b=t.meshs.find(D=>D.name==m+"Line");b==null&&(b=new S.Line(v,x),b.name=m+"Line",g.add(b),t.meshs.push(b)),b.geometry=v,b.material=x,m=="前"||m=="左"||m=="底"?t.engine.sectionPlane.find(D=>D.name==m).setFromNormalAndCoplanarPoint(d.clone().setLength(-1),e.min):t.engine.sectionPlane.find(D=>D.name==m).setFromNormalAndCoplanarPoint(d.clone().setLength(-1),e.max),t.engine.scene.children.filter(D=>D.type=="Mesh"&&D.url).forEach(D=>{D.material&&Array.isArray(D.material)?D.material.forEach(T=>{T.clippingPlanes=t.engine.sectionPlane}):D.material.clippingPlanes=t.engine.sectionPlane})}}}class rd{engine;isActive=!1;isDrag=!1;meshs=[];box;pickPoint;pickNormal;pickMesh;box_;plane;angleX=0;angleY=0;angleZ=0;direction=1;normal=new S.Vector3(0,0,1);distance=0;center=null;current_center=null;constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(n=>{n.name.includes("face")&&(n.visible=!0)})}),this.engine.handelBehaved.init(this),this.engine.handelBehaved.active();let e=this;e.engine.scene.children.filter(t=>t.type=="Mesh"&&t.url).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(n=>{n.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(n=>n.name=="face"),t)}),this.init()}disActive(){this.init(),this.isActive=!1,this.engine.handelBehaved.disActive();const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(n=>{n.name.includes("face")&&(n.visible=!1)})})}init(){let e=this.engine.octreeBox.getBoundingBox();this.box=e,this.updata_face(0)}disabled(){this.isActive=!1,this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.engine.handelBehaved.init(this),this.engine.handelBehaved.active(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,n){this.angleX=e,this.angleY=t,this.angleZ=n,this.normal=new S.Vector3(0,1,0).applyAxisAngle(new S.Vector3(1,0,0),e).applyAxisAngle(new S.Vector3(0,0,1),t).applyAxisAngle(new S.Vector3(0,1,0),n),this.normal.normalize(),this.updata_face(0)}setFaceNormal(e,t=0){this.normal=e,this.distance=t,this.updata_face(t)}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance)}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){let t=this,n=t.engine.scene.children.find(P=>P.type=="Group"&&P.name=="ClippingBox");n==null&&(n=new S.Group,n.name="ClippingBox",t.engine.scene.add(n));let i=new S.Vector3(1,0,0),s=new S.Vector3(0,1,0),r=new S.Vector3(0,0,1),a,l,h=this.normal.clone().normalize(),c=Math.abs(h.dot(i)),d=Math.abs(h.dot(s)),m=Math.abs(h.dot(r));c<=d&&c<=m?a=i:d<=c&&d<=m?a=s:a=r,a=a.clone().sub(h.clone().multiplyScalar(a.dot(h))).normalize(),l=new S.Vector3().crossVectors(h,a).normalize();let p=null;this.center==null?(p=new S.Vector3((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),this.center=p.clone()):p=this.center.clone();let f=this.box.max.x-this.box.min.x,u=this.box.max.y-this.box.min.y,g=this.box.max.z-this.box.min.z,y=Math.max(Math.abs(a.x)*f,Math.abs(a.y)*u,Math.abs(a.z)*g),w=Math.max(Math.abs(l.x)*f,Math.abs(l.y)*u,Math.abs(l.z)*g),x=p.clone().add(a.clone().multiplyScalar(-y/2)).add(l.clone().multiplyScalar(-w/2)),v=p.clone().add(a.clone().multiplyScalar(y/2)).add(l.clone().multiplyScalar(-w/2)),b=p.clone().add(a.clone().multiplyScalar(y/2)).add(l.clone().multiplyScalar(w/2)),D=p.clone().add(a.clone().multiplyScalar(-y/2)).add(l.clone().multiplyScalar(w/2));x.add(h.clone().multiplyScalar(e)),v.add(h.clone().multiplyScalar(e)),b.add(h.clone().multiplyScalar(e)),D.add(h.clone().multiplyScalar(e)),this.current_center=p.clone().add(h.clone().multiplyScalar(e)),k([x,v,b,D],h,"face");function k(P,I,z){const C=new S.BufferGeometry,E=new Float32Array([P[0].x,P[0].y,P[0].z,P[1].x,P[1].y,P[1].z,P[2].x,P[2].y,P[2].z,P[3].x,P[3].y,P[3].z]),M=[0,1,2,0,2,3];C.setAttribute("position",new S.BufferAttribute(E,3)),C.setIndex(M);let B=t.meshs.find($=>$.name==z);if(B==null){const $=new S.MeshBasicMaterial({color:65280,transparent:!0,opacity:.02,side:S.DoubleSide});$.polygonOffset=!0,$.polygonOffsetFactor=1,$.polygonOffsetUnits=4;const F=new S.Mesh(C,$);F.normal=I,F.name=z,n.add(F),t.meshs.push(F)}else B.geometry=C;const V=new Float32Array([P[0].x,P[0].y,P[0].z,P[1].x,P[1].y,P[1].z,P[2].x,P[2].y,P[2].z,P[3].x,P[3].y,P[3].z,P[0].x,P[0].y,P[0].z]);let U=new S.LineBasicMaterial({color:255}),H=new S.BufferGeometry;H.setAttribute("position",new S.BufferAttribute(V,3));let G=t.meshs.find($=>$.name==z+"Line");G==null&&(G=new S.Line(H,U),G.name=z+"Line",n.add(G),t.meshs.push(G)),G.geometry=H,G.material=U,t.engine.sectionPlane.find($=>$.name==z).setFromNormalAndCoplanarPoint(I.clone().setLength(t.direction),P[0])}}handleMouseDown(e){this.isDrag=!0;const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0)if(this.pickPoint=t[0].point,this.pickNormal=t[0].face.normal,this.engine.controls.enabled=!1,this.pickMesh=t[0].object,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.center=this.current_center.clone(),this.pickNormal.y==0){const n=new S.Plane;n.setFromNormalAndCoplanarPoint(new S.Vector3(0,1,0),this.pickPoint),this.plane=n}else{let n=new S.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z);const i=new S.Plane;i.setFromNormalAndCoplanarPoint(n.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=i}}handleMouseUp(e){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.engine.controls.enabled=!0}handleMouseMove(e){this.meshs.forEach(n=>{n.material.opacity=0});const t=e.raycaster.intersectObjects(this.meshs,!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=.05),this.pickPoint!=null){const n=new S.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,n)){let i=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());this.distance=i,this.updata_face(this.distance)}}}}class od{engine;callback_;constructor(e){this.engine=e}init(){this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){let t=e.catch.normal;this.engine.handelBehaved.disActive(),this.callback_({dir:t,position:e.catch.point})}}class ad{engine;sectionBox;sectionFace;clippingStencil;currentClippingMode="";constructor(e){this.engine=e;let t=new S.Plane(new S.Vector3(0,0,1),1e5);t.name="前";let n=new S.Plane(new S.Vector3(0,0,1),1e5);n.name="左";let i=new S.Plane(new S.Vector3(0,0,1),1e5);i.name="后";let s=new S.Plane(new S.Vector3(0,0,1),1e5);s.name="右";let r=new S.Plane(new S.Vector3(0,0,1),1e5);r.name="顶";let a=new S.Plane(new S.Vector3(0,0,1),1e5);a.name="底";let l=new S.Plane(new S.Vector3(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,n,i,s,r,a,l]}init(){this.sectionBox=new sd(this.engine),this.sectionFace=new rd(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}clippingModel(e){let t=[];e.forEach(s=>{let r=this.engine.models.find(a=>a.url===s.url);s.ids.forEach(a=>{r.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let n=i(t);this.sectionBox.setBox(n);function i(s){let r=new S.Vector3(1e8,1e9,1e10),a=new S.Vector3(-1e8,-1e9,-1e10);return s.forEach(l=>{l.min.x<r.x&&(r.x=l.min.x),l.min.y<r.y&&(r.y=l.min.y),l.min.z<r.z&&(r.z=l.min.z),l.max.x>a.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new S.Box3(r,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,n=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,i=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,s=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,r=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:n,minY:i,minZ:s,maxX:r,maxY:a,maxZ:l})}active(e){if(this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=e,e=="x")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(Math.PI/2,0,0);else if(e=="y")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(0,Math.PI/2,0);else if(e=="z")this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceAngle(0,0,Math.PI/2);else if(e=="box")this.sectionBox.init(),this.sectionBox.active();else if(e=="face"){let t=new od(this.engine);t.init(),t.catch_face(n=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),s=n.position.clone().sub(i.min.clone().add(i.max.clone()).setLength(.5)),r=new S.Vector3(n.dir.x,n.dir.y,n.dir.z),a=s.dot(r);this.sectionFace.setFaceNormal(n.dir,a)})}}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled()}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.currentClippingMode=""}}class ld{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class cd{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,n=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(i=>{if(i instanceof S.Mesh){const s=i.geometry;if(s&&s.attributes){const r=s.attributes.position;if(r){const a=r.count;e+=a;let l=0;s.index?l=s.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(i=>{n=n+i.info.modelEdge.length}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:n})}}class hd{engine;constructor(e){this.engine=e}init(){}getModelProperties(e,t,n){let i=this.engine.engineStatus.models.find(r=>r.url===e);i.properties==null&&Dr(e+"/property",r=>{let a=JSON.parse(r);i.properties=a,setTimeout(()=>{s(a,t,n)},100)}),s(i.properties,t,n);function s(r,a,l){let h=[],c=r.models[a.toString()||""],d=c.map(m=>m[0]);d=d.filter((m,p)=>d.indexOf(m)===p),d.forEach(m=>{let p={name:r.categorys[m],children:[]};h.push(p),c.filter(f=>f[0]===m).forEach(f=>{p.children.push({name:r.names[f[1]],value:r.values[f[2]]})})}),l?.({properties:h,materials:h})}}}class ud{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.typeName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.majorName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(i=>{e.push(i.levelName)})}),e=e.filter((t,n,i)=>i.indexOf(t)===n),e}getModelMappers(e){}getModelMapper(e,t){let n=this.engine.engineStatus.models.find(r=>r.url==e);return n?n.info.modelMapper.find(r=>r.id==t):null}getModelsWithLevelType(e,t,n=null){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(l=>l.levelName===e&&l.typeName===t).forEach(l=>{r.ids.push(Number(l.id))})}),n&&n(i),i}getModelsWithType(e,t=null){let n=[];return this.engine.engineStatus.models.forEach(i=>{let s={url:i.url,ids:[]};n.push(s),i.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{s.ids.push(Number(a.id))})}),t&&t(n),n}getModelsWithLevel(e,t){let n=[];return this.engine.engineStatus.models.forEach(i=>{let s={url:i.url,ids:[]};n.push(s),i.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{s.ids.push(Number(a.id))})}),t&&t(n),n}getModelsWithMajor(e,t){let n=[];return this.engine.engineStatus.models.forEach(i=>{let s={url:i.url,ids:[]};n.push(s),i.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{s.ids.push(Number(a.id))})}),t&&t(n),n}}class dd{engine;isActive=!1;groupEdge;material;modelEdgeLoaded=!1;indexes=new Map;constructor(e){this.engine=e,this.groupEdge=this.engine.scene.getObjectByName("groupEdge"),this.material=new S.LineBasicMaterial({color:"#000000",depthTest:!0,transparent:!0,opacity:.3}),this.material.clippingPlanes=this.engine.sectionPlane}active(){this.isActive=!0,this.groupEdge.visible=!0,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&(Array.isArray(e.material)?e.material:[e.material]).forEach(n=>{n.polygonOffset=!0,n.polygonOffsetFactor=1,n.polygonOffsetUnits=4})}),this.show()}disActive(){this.isActive=!1,this.groupEdge.visible=!1,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&(Array.isArray(e.material)?e.material:[e.material]).forEach(n=>{n.polygonOffset=!1})})}loadModelEdge(){this.modelEdgeLoaded||(this.engine.engineStatus.models.forEach(e=>{if(!this.groupEdge.children.find(n=>n.url==e.url)){let n=e.info,i=[],s=new Map;n.modelEdge.forEach(r=>{let a=i.length;for(let l=0;l<r.points.length;l++)r.points[l].length==2&&(i.push(r.points[l][0].X),i.push(r.points[l][0].Z),i.push(-r.points[l][0].Y),i.push(r.points[l][1].X),i.push(r.points[l][1].Z),i.push(-r.points[l][1].Y));s.set(Number(r.id),[a,i.length,r.points])}),this.indexes.set(e.url,s)}}),this.modelEdgeLoaded=!0)}show(){this.modelEdgeLoaded||this.loadModelEdge(),this.indexes.forEach((e,t)=>{let n=[];e.forEach((r,a)=>{r[2].forEach((l,h)=>{l.length==2&&(n.push(l[0].X),n.push(l[0].Z),n.push(-l[0].Y),n.push(l[1].X),n.push(l[1].Z),n.push(-l[1].Y))})});let i=new S.BufferGeometry;i.setAttribute("position",new S.Float32BufferAttribute(n,3));let s=new S.LineSegments(i,this.material);s.url=t,this.groupEdge.add(s)})}getModelEdge(e,t){let n=this.indexes.get(e);if(n){let i=n.get(t);if(i)return i.slice()}return null}hideModelEdge(e,t){let n=this.indexes.get(e);if(n){let i=n.get(t);if(i){let[s,r,a]=i,l=this.groupEdge.children.find(h=>h.url==e);if(l){let h=l.geometry.attributes.position.array;for(let c=s;c<r;c++)h[c]=NaN;l.geometry.attributes.position.needsUpdate=!0}}}}showModelEdge(e,t){let n=this.indexes.get(e);if(n){let i=n.get(t);if(i){let[s,r,a]=i,l=this.groupEdge.children.find(h=>h.url==e);if(l){let h=l.geometry.attributes.position.array,c=0;for(let d=s;d<r;d+=3){const m=Math.floor(c/6),p=c%6>=3;if(a[m]&&a[m].length===2){const f=p?a[m][1]:a[m][0];h[d]=f.X,h[d+1]=f.Z,h[d+2]=-f.Y}c+=3}l.geometry.attributes.position.needsUpdate=!0}}}}}class fd{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.config.timeout);try{const i=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(n),!i.ok){const r=await i.json().catch(()=>({}));throw new Error(`API请求失败 (${i.status}): ${r.error?.message||r.message||i.statusText}`)}return(await i.json()).choices?.[0]?.message?.content||""}catch(i){throw clearTimeout(n),i.name==="AbortError"?new Error("请求超时,请重试"):i.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查:
972
972
  1. 网络连接
973
973
  2. API地址是否正确
974
974
  3. 是否有CORS限制`):i}}async chatStream(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!0}),signal:n.signal});if(clearTimeout(i),!s.ok){const h=await s.json().catch(()=>({}));throw new Error(`API请求失败 (${s.status}): ${h.error?.message||h.message||s.statusText}`)}const r=s.body?.getReader();if(!r)throw new Error("无法读取响应流");const a=new TextDecoder;let l="";for(;;){const{done:h,value:c}=await r.read();if(h){t("",!0);break}l+=a.decode(c,{stream:!0});const d=l.split(`
@@ -1096,7 +1096,7 @@ void main() {
1096
1096
 
1097
1097
  gl_FragColor = vec4(color, uOpacity);
1098
1098
  }
1099
- `;class Cd{options;deviceType;animationId=null;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=3;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;text;hdr;ground;models=[];reactBoundingClientRect={left:0,top:0};version="2.1.0";versionEl=null;container;constructor(e){if(this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);this.engineModelModule=new Wc(this),this.engineModelModule.init(),this.ai=new pd(this),this.deviceModule=new Go(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new jo(this),this.sceneModule=new Vo(this),this.scene=this.sceneModule.scene,this.renderModule=new Wo(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.controlModule=new ra(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.composerModule=new wa(this),this.composerModule.init(),this.events=new Nc,this.engineStatus=new zc(this),this.engineStatus.init(),this.loaderModule=new Oc(this),this.lightModule=new Rc(this),this.lightModule.init(),this.viewCube=new th(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=nh(this),this.rangeScale=new ih(this),this.rangeScale.init(),this.clipping=new ad(this),this.clipping.init(),this.setting=new sh(this),this.setting.init(),this.engineModelModule.init(),this.handelBehaved=Ci(this),this.modelMapperBatch=new ud(this),this.measure=new fh(this),this.modelToolModule=new Uc(this),this.modelProperties=new hd(this),this.interactionModule=new Fc(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new qn(this),this.modelEdge=new dd(this),this.modelTree=new ld(this),this.engineInfo=new cd(this),this.pathRoaming=new md(this),this.pathRoaming.init(),this.minMap=new gd(this),this.grid=new wd(this),this.level=new vd(this),this.text=new bd(this),this.hdr=new _d(this),this.ground=new Md(this),this.ground.init(),this.worldToScreen=new ze(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new Kc,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.zIndex="1000",n.style.left="0px",n.style.top="0px",n.style.pointerEvents="none",this.container.appendChild(n),this.catchSvg=n,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let i=this;this.controls.addEventListener("start",()=>{i.events.trigger(ut.EngineBusy)}),this.controls.addEventListener("end",()=>{i.events.trigger(ut.EngineFree)}),this.controls.addEventListener("change",()=>{}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const s=performance.now();if(s-this._fpsLastCheck>=this._fpsCheckInterval){const r=s-this._fpsLastCheck,a=this._fpsFrameCount/r*1e3;this._fpsFrameCount=0,this._fpsLastCheck=s,a<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&s-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=s,this._lowFpsCount=0)):a>this._fpsUpgradeThreshold?(this._highFpsCount++,this._lowFpsCount=0):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let r=this.scene?.dirLight;r&&this.camera&&this.updateLightPosition(this.camera,r)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",n=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${n}`}updateLightPosition(e,t){const n=new S.Vector3;e.getWorldDirection(n);const i=100,s=new S.Vector3().copy(n).multiplyScalar(-i),r=new S.Vector3(0,1,0),a=new S.Vector3().crossVectors(n,r).normalize();s.addScaledVector(r,i*.5),s.addScaledVector(a,i*.3),t.position.copy(e.position).add(s);const l=new S.Vector3().copy(e.position).add(n.multiplyScalar(20));t.target.position.copy(l),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),n=e.indexOf(t);if(n>0){const i=e[n-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),n=e.indexOf(t);if(n<e.length-1){const i=e[n+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const i=this.deviceModule.getContainerSize();e=e??i.width,t=t??i.height}if(!e||!t)return;this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const n=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=n,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const i=this.cameraModule.orthographicCamera,s=50,r=this.container.clientWidth/this.container.clientHeight;i.left=s*r/-2,i.right=s*r/2,i.top=s/2,i.bottom=s/-2,i.updateProjectionMatrix()}if(this.catchSvg){const i=this.container.clientWidth,s=this.container.clientHeight;this.catchSvg.setAttribute("viewBox",`0 0 ${i} ${s}`)}this.events&&this.events.trigger(ut.ViewportResize,{width:e,height:t})}dispose(){console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.measure&&(this.measure.disActive(),this.measure.clearAll(),this.measure.annotationContainer&&this.measure.annotationContainer.remove()),this.hdr&&this.hdr.dispose(),this.minMap&&this.minMap.dispose(),this.text&&this.text.dispose(),this.clipping&&this.clipping.disActive(),this.interactionModule&&this.interactionModule.disActive(),this.viewCube&&this.viewCube.cubeTool&&typeof this.viewCube.cubeTool.dispose=="function"&&this.viewCube.cubeTool.dispose()}catch(e){console.warn("[BimEngine] Error disposing managers:",e)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(e){console.warn("[BimEngine] Error disposing controls:",e)}this.scene&&this.clearScene(this.scene);try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(e=>{e.dispose&&e.dispose()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose())}catch(e){console.warn("[BimEngine] Error disposing composer:",e)}try{this.renderModule&&this.renderModule.disposeRenderer(),this.renderer&&(this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(e){console.warn("[BimEngine] Error disposing renderer:",e)}try{this.stats&&this.stats.dom&&this.stats.dom.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg&&this.catchSvg.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg)}catch(e){console.warn("[BimEngine] Error disposing DOM elements:",e)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(e){console.warn("[BimEngine] Error clearing event listeners:",e)}this.scene=null,this.camera=null,this.renderer=null,this.controls=null,this.models=[],this.container=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){if(!e)return;[...e.children].forEach(n=>{this.clearScene(n)}),e.parent&&e.parent.remove(e),e instanceof S.Mesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>this.disposeMaterial(n)):this.disposeMaterial(e.material))),e instanceof S.Line&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof S.Points&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof S.InstancedMesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>this.disposeMaterial(n)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof S.Sprite&&e.material&&this.disposeMaterial(e.material)}disposeMaterial(e){if(!e)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(n=>{const i=e[n];i&&i instanceof S.Texture&&i.dispose()}),e.dispose()}}function Td(o){return new Cd(o)}const Pd=Object.freeze(Object.defineProperty({__proto__:null,default:`# BIM引擎AI助手 - 需求分析与步骤规划专家\r
1099
+ `;class Cd{options;deviceType;animationId=null;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=3;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;text;hdr;ground;models=[];reactBoundingClientRect={left:0,top:0};version="2.1.2";versionEl=null;container;constructor(e){if(this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);this.engineModelModule=new Wc(this),this.engineModelModule.init(),this.ai=new pd(this),this.deviceModule=new Go(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new jo(this),this.sceneModule=new Vo(this),this.scene=this.sceneModule.scene,this.renderModule=new Wo(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.controlModule=new ra(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.composerModule=new wa(this),this.composerModule.init(),this.events=new Nc,this.engineStatus=new zc(this),this.engineStatus.init(),this.loaderModule=new Oc(this),this.lightModule=new Rc(this),this.lightModule.init(),this.viewCube=new th(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=nh(this),this.rangeScale=new ih(this),this.rangeScale.init(),this.clipping=new ad(this),this.clipping.init(),this.setting=new sh(this),this.setting.init(),this.engineModelModule.init(),this.handelBehaved=Ci(this),this.modelMapperBatch=new ud(this),this.measure=new fh(this),this.modelToolModule=new Uc(this),this.modelProperties=new hd(this),this.interactionModule=new Fc(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new qn(this),this.modelEdge=new dd(this),this.modelTree=new ld(this),this.engineInfo=new cd(this),this.pathRoaming=new md(this),this.pathRoaming.init(),this.minMap=new gd(this),this.grid=new wd(this),this.level=new vd(this),this.text=new bd(this),this.hdr=new _d(this),this.ground=new Md(this),this.ground.init(),this.worldToScreen=new ze(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new Kc,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.zIndex="1000",n.style.left="0px",n.style.top="0px",n.style.pointerEvents="none",this.container.appendChild(n),this.catchSvg=n,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let i=this;this.controls.addEventListener("start",()=>{i.events.trigger(ut.EngineBusy)}),this.controls.addEventListener("end",()=>{i.events.trigger(ut.EngineFree)}),this.controls.addEventListener("change",()=>{}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const s=performance.now();if(s-this._fpsLastCheck>=this._fpsCheckInterval){const r=s-this._fpsLastCheck,a=this._fpsFrameCount/r*1e3;this._fpsFrameCount=0,this._fpsLastCheck=s,a<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&s-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=s,this._lowFpsCount=0)):a>this._fpsUpgradeThreshold?(this._highFpsCount++,this._lowFpsCount=0):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let r=this.scene?.dirLight;r&&this.camera&&this.updateLightPosition(this.camera,r)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",n=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${n}`}updateLightPosition(e,t){const n=new S.Vector3;e.getWorldDirection(n);const i=100,s=new S.Vector3().copy(n).multiplyScalar(-i),r=new S.Vector3(0,1,0),a=new S.Vector3().crossVectors(n,r).normalize();s.addScaledVector(r,i*.5),s.addScaledVector(a,i*.3),t.position.copy(e.position).add(s);const l=new S.Vector3().copy(e.position).add(n.multiplyScalar(20));t.target.position.copy(l),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),n=e.indexOf(t);if(n>0){const i=e[n-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),n=e.indexOf(t);if(n<e.length-1){const i=e[n+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${i}`),this.engineModelModule.autoSwitch(i)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const i=this.deviceModule.getContainerSize();e=e??i.width,t=t??i.height}if(!e||!t)return;this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const n=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=n,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const i=this.cameraModule.orthographicCamera,s=50,r=this.container.clientWidth/this.container.clientHeight;i.left=s*r/-2,i.right=s*r/2,i.top=s/2,i.bottom=s/-2,i.updateProjectionMatrix()}if(this.catchSvg){const i=this.container.clientWidth,s=this.container.clientHeight;this.catchSvg.setAttribute("viewBox",`0 0 ${i} ${s}`)}this.events&&this.events.trigger(ut.ViewportResize,{width:e,height:t})}dispose(){console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.measure&&(this.measure.disActive(),this.measure.clearAll(),this.measure.annotationContainer&&this.measure.annotationContainer.remove()),this.hdr&&this.hdr.dispose(),this.minMap&&this.minMap.dispose(),this.text&&this.text.dispose(),this.clipping&&this.clipping.disActive(),this.interactionModule&&this.interactionModule.disActive(),this.viewCube&&this.viewCube.cubeTool&&typeof this.viewCube.cubeTool.dispose=="function"&&this.viewCube.cubeTool.dispose()}catch(e){console.warn("[BimEngine] Error disposing managers:",e)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(e){console.warn("[BimEngine] Error disposing controls:",e)}this.scene&&this.clearScene(this.scene);try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(e=>{e.dispose&&e.dispose()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose())}catch(e){console.warn("[BimEngine] Error disposing composer:",e)}try{this.renderModule&&this.renderModule.disposeRenderer(),this.renderer&&(this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(e){console.warn("[BimEngine] Error disposing renderer:",e)}try{this.stats&&this.stats.dom&&this.stats.dom.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg&&this.catchSvg.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg)}catch(e){console.warn("[BimEngine] Error disposing DOM elements:",e)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(e){console.warn("[BimEngine] Error clearing event listeners:",e)}this.scene=null,this.camera=null,this.renderer=null,this.controls=null,this.models=[],this.container=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){if(!e)return;[...e.children].forEach(n=>{this.clearScene(n)}),e.parent&&e.parent.remove(e),e instanceof S.Mesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>this.disposeMaterial(n)):this.disposeMaterial(e.material))),e instanceof S.Line&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof S.Points&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof S.InstancedMesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>this.disposeMaterial(n)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof S.Sprite&&e.material&&this.disposeMaterial(e.material)}disposeMaterial(e){if(!e)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(n=>{const i=e[n];i&&i instanceof S.Texture&&i.dispose()}),e.dispose()}}function Td(o){return new Cd(o)}const Pd=Object.freeze(Object.defineProperty({__proto__:null,default:`# BIM引擎AI助手 - 需求分析与步骤规划专家\r
1100
1100
  \r
1101
1101
  ## 角色定位\r
1102
1102
  \r