@ridp/threejs 1.4.4 → 1.4.5

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,2 +1,2 @@
1
- "use strict";const u=require("three"),Ge=require("dexie");function Be(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 x=Be(u),we={type:"change"},ye={type:"start"},Oe={type:"end"},ee=new u.Ray,be=new u.Plane,ze=Math.cos(70*u.MathUtils.DEG2RAD),L=new u.Vector3,O=2*Math.PI,R={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ae=1e-6;class Ie extends u.Controls{constructor(e,t=null){super(e,t),this.state=R.NONE,this.target=new u.Vector3,this.cursor=new u.Vector3,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:u.MOUSE.ROTATE,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.PAN},this.touches={ONE:u.TOUCH.ROTATE,TWO:u.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 u.Vector3,this._lastQuaternion=new u.Quaternion,this._lastTargetPosition=new u.Vector3,this._quat=new u.Quaternion().setFromUnitVectors(e.up,new u.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new u.Spherical,this._sphericalDelta=new u.Spherical,this._scale=1,this._panOffset=new u.Vector3,this._rotateStart=new u.Vector2,this._rotateEnd=new u.Vector2,this._rotateDelta=new u.Vector2,this._panStart=new u.Vector2,this._panEnd=new u.Vector2,this._panDelta=new u.Vector2,this._dollyStart=new u.Vector2,this._dollyEnd=new u.Vector2,this._dollyDelta=new u.Vector2,this._dollyDirection=new u.Vector3,this._mouse=new u.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Ve.bind(this),this._onPointerDown=Ke.bind(this),this._onPointerUp=We.bind(this),this._onContextMenu=Je.bind(this),this._onMouseWheel=qe.bind(this),this._onKeyDown=$e.bind(this),this._onTouchStart=Ze.bind(this),this._onTouchMove=Qe.bind(this),this._onMouseDown=Xe.bind(this),this._onMouseMove=Ye.bind(this),this._interceptControlDown=et.bind(this),this._interceptControlUp=tt.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(we),this.update(),this.state=R.NONE}update(e=null){const t=this.object.position;L.copy(t).sub(this.target),L.applyQuaternion(this._quat),this._spherical.setFromVector3(L),this.autoRotate&&this.state===R.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,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=O:n>Math.PI&&(n-=O),s<-Math.PI?s+=O:s>Math.PI&&(s-=O),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,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 i=!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),i=r!=this._spherical.radius}if(L.setFromSpherical(this._spherical),L.applyQuaternion(this._quatInverse),t.copy(this.target).add(L),this.object.lookAt(this.target),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 c=L.length();r=this._clampDistance(c*this._scale);const a=c-r;this.object.position.addScaledVector(this._dollyDirection,a),this.object.updateMatrixWorld(),i=!!a}else if(this.object.isOrthographicCamera){const c=new u.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object);const a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=a!==this.object.zoom;const l=new u.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(c),this.object.updateMatrixWorld(),r=L.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):(ee.origin.copy(this.object.position),ee.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ee.direction))<ze?this.object.lookAt(this.target):(be.setFromNormalAndCoplanarPoint(this.object.up,this.target),ee.intersectPlane(be,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(),i=!0)}return this._scale=1,this._performCursorZoom=!1,i||this._lastPosition.distanceToSquared(this.object.position)>ae||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ae||this._lastTargetPosition.distanceToSquared(this.target)>ae?(this.dispatchEvent(we),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?O/60*this.autoRotateSpeed*e:O/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){L.setFromMatrixColumn(t,0),L.multiplyScalar(-e),this._panOffset.add(L)}_panUp(e,t){this.screenSpacePanning===!0?L.setFromMatrixColumn(t,1):(L.setFromMatrixColumn(t,0),L.crossVectors(this.object.up,L)),L.multiplyScalar(e),this._panOffset.add(L)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;L.copy(s).sub(this.target);let i=L.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/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(),s=e-n.left,i=t-n.top,r=n.width,c=n.height;this._mouse.x=s/r*2-1,this._mouse.y=-(i/c)*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(O*this._rotateDelta.x/t.clientHeight),this._rotateUp(O*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),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(O*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(-O*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(O*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(-O*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),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_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),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,i=Math.sqrt(n*n+s*s);this._dollyStart.set(0,i)}_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),s=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(O*this._rotateDelta.x/t.clientHeight),this._rotateUp(O*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),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}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,s=e.pageY-t.y,i=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,i),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,c=(e.pageY+t.y)*.5;this._updateZoomParameters(r,c)}_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 u.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 Ke(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 Ve(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function We(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(Oe),this.state=R.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 Xe(o){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 u.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=R.DOLLY;break;case u.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=R.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=R.ROTATE}break;case u.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=R.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=R.PAN}break;default:this.state=R.NONE}this.state!==R.NONE&&this.dispatchEvent(ye)}function Ye(o){switch(this.state){case R.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case R.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case R.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function qe(o){this.enabled===!1||this.enableZoom===!1||this.state!==R.NONE||(o.preventDefault(),this.dispatchEvent(ye),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(Oe))}function $e(o){this.enabled!==!1&&this._handleKeyDown(o)}function Ze(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case u.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=R.TOUCH_ROTATE;break;case u.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=R.TOUCH_PAN;break;default:this.state=R.NONE}break;case 2:switch(this.touches.TWO){case u.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=R.TOUCH_DOLLY_PAN;break;case u.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=R.TOUCH_DOLLY_ROTATE;break;default:this.state=R.NONE}break;default:this.state=R.NONE}this.state!==R.NONE&&this.dispatchEvent(ye)}function Qe(o){switch(this._trackPointer(o),this.state){case R.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case R.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case R.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case R.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=R.NONE}}function Je(o){this.enabled!==!1&&o.preventDefault()}function et(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function tt(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class st extends Ie{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:u.MOUSE.PAN,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.ROTATE},this.touches={ONE:u.TOUCH.PAN,TWO:u.TOUCH.DOLLY_ROTATE}}}function Ee(o,e){if(e===u.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),o;if(e===u.TriangleFanDrawMode||e===u.TriangleStripDrawMode){let t=o.getIndex();if(t===null){const r=[],c=o.getAttribute("position");if(c!==void 0){for(let a=0;a<c.count;a++)r.push(a);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,s=[];if(e===u.TriangleFanDrawMode)for(let r=1;r<=n;r++)s.push(t.getX(0)),s.push(t.getX(r)),s.push(t.getX(r+1));else for(let r=0;r<n;r++)r%2===0?(s.push(t.getX(r)),s.push(t.getX(r+1)),s.push(t.getX(r+2))):(s.push(t.getX(r+2)),s.push(t.getX(r+1)),s.push(t.getX(r)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=o.clone();return i.setIndex(s),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),o}const ce=new WeakMap;class nt extends u.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,s){const i=new u.FileLoader(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{this.parse(r,t,s)},n,s)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,u.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,s,i=u.LinearSRGBColorSpace,r=()=>{}){const c={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,c).then(t).catch(r)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ce.has(e)){const a=ce.get(e);if(a.key===n)return a.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 s;const i=this.workerNextTaskID++,r=e.byteLength,c=this._getWorker(i,r).then(a=>(s=a,new Promise((l,d)=>{s._callbacks[i]={resolve:l,reject:d},s.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(a=>this._createGeometry(a.geometry));return c.catch(()=>!0).then(()=>{s&&i&&this._releaseTask(s,i)}),ce.set(e,{key:n,promise:c}),c}_createGeometry(e){const t=new u.BufferGeometry;e.index&&t.setIndex(new u.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n],i=s.name,r=s.array,c=s.itemSize,a=new u.BufferAttribute(r,c);i==="color"&&(this._assignVertexColorSpace(a,s.vertexColorSpace),a.normalized=!(r instanceof Float32Array)),t.setAttribute(i,a)}return t}_assignVertexColorSpace(e,t){if(t!==u.SRGBColorSpace)return;const n=new u.Color;for(let s=0,i=e.count;s<i;s++)n.fromBufferAttribute(e,s),u.ColorManagement.colorSpaceToWorking(n,u.SRGBColorSpace),e.setXYZ(s,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new u.FileLoader(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((s,i)=>{n.load(e,s,void 0,i)})}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 s=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=it.toString(),r=["/* draco decoder */",s,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
2
- `);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(i){const r=i.data;switch(r.type){case"decode":s._callbacks[r.id].resolve(r);break;case"error":s._callbacks[r.id].reject(r);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+r.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,i){return s._taskLoad>i._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 it(){let o,e;onmessage=function(r){const c=r.data;switch(c.type){case"init":o=c.decoderConfig,e=new Promise(function(d){o.onModuleLoaded=function(h){d({draco:h})},DracoDecoderModule(o)});break;case"decode":const a=c.buffer,l=c.taskConfig;e.then(d=>{const h=d.draco,m=new h.Decoder;try{const g=t(h,m,new Int8Array(a),l),_=g.attributes.map(b=>b.array.buffer);g.index&&_.push(g.index.array.buffer),self.postMessage({type:"decode",id:c.id,geometry:g},_)}catch(g){console.error(g),self.postMessage({type:"error",id:c.id,error:g.message})}finally{h.destroy(m)}});break}};function t(r,c,a,l){const d=l.attributeIDs,h=l.attributeTypes;let m,g;const _=c.GetEncodedGeometryType(a);if(_===r.TRIANGULAR_MESH)m=new r.Mesh,g=c.DecodeArrayToMesh(a,a.byteLength,m);else if(_===r.POINT_CLOUD)m=new r.PointCloud,g=c.DecodeArrayToPointCloud(a,a.byteLength,m);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!g.ok()||m.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+g.error_msg());const b={index:null,attributes:[]};for(const f in d){const p=self[h[f]];let y,w;if(l.useUniqueIDs)w=d[f],y=c.GetAttributeByUniqueId(m,w);else{if(w=c.GetAttributeId(m,r[d[f]]),w===-1)continue;y=c.GetAttribute(m,w)}const T=s(r,c,m,f,p,y);f==="color"&&(T.vertexColorSpace=l.vertexColorSpace),b.attributes.push(T)}return _===r.TRIANGULAR_MESH&&(b.index=n(r,c,m)),r.destroy(m),b}function n(r,c,a){const d=a.num_faces()*3,h=d*4,m=r._malloc(h);c.GetTrianglesUInt32Array(a,h,m);const g=new Uint32Array(r.HEAPF32.buffer,m,d).slice();return r._free(m),{array:g,itemSize:1}}function s(r,c,a,l,d,h){const m=h.num_components(),_=a.num_points()*m,b=_*d.BYTES_PER_ELEMENT,f=i(r,d),p=r._malloc(b);c.GetAttributeDataArrayForAllPoints(a,h,f,b,p);const y=new d(r.HEAPF32.buffer,p,_).slice();return r._free(p),{name:l,array:y,itemSize:m}}function i(r,c){switch(c){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}}}class rt extends u.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ht(t)}),this.register(function(t){return new ut(t)}),this.register(function(t){return new wt(t)}),this.register(function(t){return new bt(t)}),this.register(function(t){return new Et(t)}),this.register(function(t){return new ft(t)}),this.register(function(t){return new pt(t)}),this.register(function(t){return new mt(t)}),this.register(function(t){return new gt(t)}),this.register(function(t){return new lt(t)}),this.register(function(t){return new yt(t)}),this.register(function(t){return new dt(t)}),this.register(function(t){return new _t(t)}),this.register(function(t){return new Tt(t)}),this.register(function(t){return new at(t)}),this.register(function(t){return new St(t)}),this.register(function(t){return new Mt(t)})}load(e,t,n,s){const i=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=u.LoaderUtils.extractUrlBase(e);r=u.LoaderUtils.resolveURL(l,this.path)}else r=u.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const c=function(l){s?s(l):console.error(l),i.manager.itemError(e),i.manager.itemEnd(e)},a=new u.FileLoader(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(l){try{i.parse(l,r,function(d){t(d),i.manager.itemEnd(e)},c)}catch(d){c(d)}},n,c)}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,s){let i;const r={},c={},a=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(a.decode(new Uint8Array(e,0,4))===ke){try{r[E.KHR_BINARY_GLTF]=new xt(e)}catch(h){s&&s(h);return}i=JSON.parse(r[E.KHR_BINARY_GLTF].content)}else i=JSON.parse(a.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new Ft(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](l);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),c[h.name]=h,r[h.name]=!0}if(i.extensionsUsed)for(let d=0;d<i.extensionsUsed.length;++d){const h=i.extensionsUsed[d],m=i.extensionsRequired||[];switch(h){case E.KHR_MATERIALS_UNLIT:r[h]=new ct;break;case E.KHR_DRACO_MESH_COMPRESSION:r[h]=new Rt(i,this.dracoLoader);break;case E.KHR_TEXTURE_TRANSFORM:r[h]=new At;break;case E.KHR_MESH_QUANTIZATION:r[h]=new Lt;break;default:m.indexOf(h)>=0&&c[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}l.setExtensions(r),l.setPlugins(c),l.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,i){n.parse(e,t,s,i)})}}function ot(){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 E={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 at{constructor(e){this.parser=e,this.name=E.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let l;const d=new u.Color(16777215);a.color!==void 0&&d.setRGB(a.color[0],a.color[1],a.color[2],u.LinearSRGBColorSpace);const h=a.range!==void 0?a.range:0;switch(a.type){case"directional":l=new u.DirectionalLight(d),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new u.PointLight(d),l.distance=h;break;case"spot":l=new u.SpotLight(d),l.distance=h,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,l.angle=a.spot.outerConeAngle,l.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return l.position.set(0,0,0),U(l,a),a.intensity!==void 0&&(l.intensity=a.intensity),l.name=t.createUniqueName(a.name||"light_"+e),s=Promise.resolve(l),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],c=(i.extensions&&i.extensions[this.name]||{}).light;return c===void 0?null:this._loadLight(c).then(function(a){return n._getNodeRef(t.cache,c,a)})}}class ct{constructor(){this.name=E.KHR_MATERIALS_UNLIT}getMaterialType(){return u.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new u.Color(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const r=i.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],u.LinearSRGBColorSpace),e.opacity=r[3]}i.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",i.baseColorTexture,u.SRGBColorSpace))}return Promise.all(s)}}class lt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class ht{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];if(r.clearcoatFactor!==void 0&&(t.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){const c=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new u.Vector2(c,c)}return Promise.all(i)}}class ut{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class dt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return r.iridescenceFactor!==void 0&&(t.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&i.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&&i.push(n.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(i)}}class ft{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new u.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const r=s.extensions[this.name];if(r.sheenColorFactor!==void 0){const c=r.sheenColorFactor;t.sheenColor.setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace)}return r.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",r.sheenColorTexture,u.SRGBColorSpace)),r.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(i)}}class pt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return r.transmissionFactor!==void 0&&(t.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(i)}}class mt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];t.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const c=r.attenuationColor||[1,1,1];return t.attenuationColor=new u.Color().setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace),Promise.all(i)}}class gt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class yt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];t.specularIntensity=r.specularFactor!==void 0?r.specularFactor:1,r.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",r.specularTexture));const c=r.specularColorFactor||[1,1,1];return t.specularColor=new u.Color().setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace),r.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",r.specularColorTexture,u.SRGBColorSpace)),Promise.all(i)}}class Tt{constructor(e){this.parser=e,this.name=E.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return t.bumpScale=r.bumpFactor!==void 0?r.bumpFactor:1,r.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(i)}}class _t{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return r.anisotropyStrength!==void 0&&(t.anisotropy=r.anisotropyStrength),r.anisotropyRotation!==void 0&&(t.anisotropyRotation=r.anisotropyRotation),r.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(i)}}class wt{constructor(e){this.parser=e,this.name=E.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const i=s.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,i.source,r)}}class bt{constructor(e){this.parser=e,this.name=E.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,i=s.textures[e];if(!i.extensions||!i.extensions[t])return null;const r=i.extensions[t],c=s.images[r.source];let a=n.textureLoader;if(c.uri){const l=n.options.manager.getHandler(c.uri);l!==null&&(a=l)}return n.loadTextureImage(e,r.source,a)}}class Et{constructor(e){this.parser=e,this.name=E.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,i=s.textures[e];if(!i.extensions||!i.extensions[t])return null;const r=i.extensions[t],c=s.images[r.source];let a=n.textureLoader;if(c.uri){const l=n.options.manager.getHandler(c.uri);l!==null&&(a=l)}return n.loadTextureImage(e,r.source,a)}}class St{constructor(e){this.name=E.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 s=n.extensions[this.name],i=this.parser.getDependency("buffer",s.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 i.then(function(c){const a=s.byteOffset||0,l=s.byteLength||0,d=s.count,h=s.byteStride,m=new Uint8Array(c,a,l);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(d,h,m,s.mode,s.filter).then(function(g){return g.buffer}):r.ready.then(function(){const g=new ArrayBuffer(d*h);return r.decodeGltfBuffer(new Uint8Array(g),d,h,m,s.mode,s.filter),g})})}else return null}}class Mt{constructor(e){this.name=E.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 s=t.meshes[n.mesh];for(const l of s.primitives)if(l.mode!==I.TRIANGLES&&l.mode!==I.TRIANGLE_STRIP&&l.mode!==I.TRIANGLE_FAN&&l.mode!==void 0)return null;const r=n.extensions[this.name].attributes,c=[],a={};for(const l in r)c.push(this.parser.getDependency("accessor",r[l]).then(d=>(a[l]=d,a[l])));return c.length<1?null:(c.push(this.parser.createNodeMesh(e)),Promise.all(c).then(l=>{const d=l.pop(),h=d.isGroup?d.children:[d],m=l[0].count,g=[];for(const _ of h){const b=new u.Matrix4,f=new u.Vector3,p=new u.Quaternion,y=new u.Vector3(1,1,1),w=new u.InstancedMesh(_.geometry,_.material,m);for(let T=0;T<m;T++)a.TRANSLATION&&f.fromBufferAttribute(a.TRANSLATION,T),a.ROTATION&&p.fromBufferAttribute(a.ROTATION,T),a.SCALE&&y.fromBufferAttribute(a.SCALE,T),w.setMatrixAt(T,b.compose(f,p,y));for(const T in a)if(T==="_COLOR_0"){const S=a[T];w.instanceColor=new u.InstancedBufferAttribute(S.array,S.itemSize,S.normalized)}else T!=="TRANSLATION"&&T!=="ROTATION"&&T!=="SCALE"&&_.geometry.setAttribute(T,a[T]);u.Object3D.prototype.copy.call(w,_),this.parser.assignFinalMaterial(w),g.push(w)}return d.isGroup?(d.clear(),d.add(...g),d):g[0]}))}}const ke="glTF",Z=12,Se={JSON:1313821514,BIN:5130562};class xt{constructor(e){this.name=E.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Z),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!==ke)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-Z,i=new DataView(e,Z);let r=0;for(;r<s;){const c=i.getUint32(r,!0);r+=4;const a=i.getUint32(r,!0);if(r+=4,a===Se.JSON){const l=new Uint8Array(e,Z+r,c);this.content=n.decode(l)}else if(a===Se.BIN){const l=Z+r;this.body=e.slice(l,l+c)}r+=c}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Rt{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=E.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,i=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,c={},a={},l={};for(const d in r){const h=pe[d]||d.toLowerCase();c[h]=r[d]}for(const d in e.attributes){const h=pe[d]||d.toLowerCase();if(r[d]!==void 0){const m=n.accessors[e.attributes[d]],g=Y[m.componentType];l[h]=g.name,a[h]=m.normalized===!0}}return t.getDependency("bufferView",i).then(function(d){return new Promise(function(h,m){s.decodeDracoFile(d,function(g){for(const _ in g.attributes){const b=g.attributes[_],f=a[_];f!==void 0&&(b.normalized=f)}h(g)},c,l,u.LinearSRGBColorSpace,m)})})}}class At{constructor(){this.name=E.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 Lt{constructor(){this.name=E.KHR_MESH_QUANTIZATION}}class Ne extends u.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,i=e*s*3+s;for(let r=0;r!==s;r++)t[r]=n[i+r];return t}interpolate_(e,t,n,s){const i=this.resultBuffer,r=this.sampleValues,c=this.valueSize,a=c*2,l=c*3,d=s-t,h=(n-t)/d,m=h*h,g=m*h,_=e*l,b=_-l,f=-2*g+3*m,p=g-m,y=1-f,w=p-m+h;for(let T=0;T!==c;T++){const S=r[b+T+c],M=r[b+T+a]*d,A=r[_+T+c],P=r[_+T]*d;i[T]=y*S+w*M+f*A+p*P}return i}}const Ct=new u.Quaternion;class Pt extends Ne{interpolate_(e,t,n,s){const i=super.interpolate_(e,t,n,s);return Ct.fromArray(i).normalize().toArray(i),i}}const I={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Y={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Me={9728:u.NearestFilter,9729:u.LinearFilter,9984:u.NearestMipmapNearestFilter,9985:u.LinearMipmapNearestFilter,9986:u.NearestMipmapLinearFilter,9987:u.LinearMipmapLinearFilter},xe={33071:u.ClampToEdgeWrapping,33648:u.MirroredRepeatWrapping,10497:u.RepeatWrapping},le={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},pe={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"},G={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Dt={CUBICSPLINE:void 0,LINEAR:u.InterpolateLinear,STEP:u.InterpolateDiscrete},he={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Ot(o){return o.DefaultMaterial===void 0&&(o.DefaultMaterial=new u.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:u.FrontSide})),o.DefaultMaterial}function K(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 U(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 It(o,e,t){let n=!1,s=!1,i=!1;for(let l=0,d=e.length;l<d;l++){const h=e[l];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(i=!0),n&&s&&i)break}if(!n&&!s&&!i)return Promise.resolve(o);const r=[],c=[],a=[];for(let l=0,d=e.length;l<d;l++){const h=e[l];if(n){const m=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):o.attributes.position;r.push(m)}if(s){const m=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):o.attributes.normal;c.push(m)}if(i){const m=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):o.attributes.color;a.push(m)}}return Promise.all([Promise.all(r),Promise.all(c),Promise.all(a)]).then(function(l){const d=l[0],h=l[1],m=l[2];return n&&(o.morphAttributes.position=d),s&&(o.morphAttributes.normal=h),i&&(o.morphAttributes.color=m),o.morphTargetsRelative=!0,o})}function kt(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,s=t.length;n<s;n++)o.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Nt(o){let e;const t=o.extensions&&o.extensions[E.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ue(t.attributes):e=o.indices+":"+ue(o.attributes)+":"+o.mode,o.targets!==void 0)for(let n=0,s=o.targets.length;n<s;n++)e+=":"+ue(o.targets[n]);return e}function ue(o){let e="";const t=Object.keys(o).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+o[t[n]]+";";return e}function me(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 vt(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 Ht=new u.Matrix4;class Ft{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new ot,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,s=-1,i=!1,r=-1;if(typeof navigator<"u"){const c=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(c)===!0;const a=c.match(/Version\/(\d+)/);s=n&&a?parseInt(a[1],10):-1,i=c.indexOf("Firefox")>-1,r=i?c.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||i&&r<98?this.textureLoader=new u.TextureLoader(this.options.manager):this.textureLoader=new u.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new u.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,s=this.json,i=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 c={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:n,userData:{}};return K(i,c,s),U(c,s),Promise.all(n._invokeAll(function(a){return a.afterRoot&&a.afterRoot(c)})).then(function(){for(const a of c.scenes)a.updateMatrixWorld();e(c)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,i=t.length;s<i;s++){const r=t[s].joints;for(let c=0,a=r.length;c<a;c++)e[r[c]].isBone=!0}for(let s=0,i=e.length;s<i;s++){const r=e[s];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 s=n.clone(),i=(r,c)=>{const a=this.associations.get(r);a!=null&&this.associations.set(c,a);for(const[l,d]of r.children.entries())i(d,c.children[l])};return i(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const i=e(t[s]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":s=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(i,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[E.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(i,r){n.load(u.LoaderUtils.resolveURL(t.uri,s.path),i,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 s=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const r=le[s.type],c=Y[s.componentType],a=s.normalized===!0,l=new c(s.count*r);return Promise.resolve(new u.BufferAttribute(l,r,a))}const i=[];return s.bufferView!==void 0?i.push(this.getDependency("bufferView",s.bufferView)):i.push(null),s.sparse!==void 0&&(i.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(i).then(function(r){const c=r[0],a=le[s.type],l=Y[s.componentType],d=l.BYTES_PER_ELEMENT,h=d*a,m=s.byteOffset||0,g=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,_=s.normalized===!0;let b,f;if(g&&g!==h){const p=Math.floor(m/g),y="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+p+":"+s.count;let w=t.cache.get(y);w||(b=new l(c,p*g,s.count*g/d),w=new u.InterleavedBuffer(b,g/d),t.cache.add(y,w)),f=new u.InterleavedBufferAttribute(w,a,m%g/d,_)}else c===null?b=new l(s.count*a):b=new l(c,m,s.count*a),f=new u.BufferAttribute(b,a,_);if(s.sparse!==void 0){const p=le.SCALAR,y=Y[s.sparse.indices.componentType],w=s.sparse.indices.byteOffset||0,T=s.sparse.values.byteOffset||0,S=new y(r[1],w,s.sparse.count*p),M=new l(r[2],T,s.sparse.count*a);c!==null&&(f=new u.BufferAttribute(f.array.slice(),f.itemSize,f.normalized)),f.normalized=!1;for(let A=0,P=S.length;A<P;A++){const D=S[A];if(f.setX(D,M[A*a]),a>=2&&f.setY(D,M[A*a+1]),a>=3&&f.setZ(D,M[A*a+2]),a>=4&&f.setW(D,M[A*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}f.normalized=_}return f})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,r=t.images[i];let c=this.textureLoader;if(r.uri){const a=n.manager.getHandler(r.uri);a!==null&&(c=a)}return this.loadTextureImage(e,i,c)}loadTextureImage(e,t,n){const s=this,i=this.json,r=i.textures[e],c=i.images[t],a=(c.uri||c.bufferView)+":"+r.sampler;if(this.textureCache[a])return this.textureCache[a];const l=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=r.name||c.name||"",d.name===""&&typeof c.uri=="string"&&c.uri.startsWith("data:image/")===!1&&(d.name=c.uri);const m=(i.samplers||{})[r.sampler]||{};return d.magFilter=Me[m.magFilter]||u.LinearFilter,d.minFilter=Me[m.minFilter]||u.LinearMipmapLinearFilter,d.wrapS=xe[m.wrapS]||u.RepeatWrapping,d.wrapT=xe[m.wrapT]||u.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==u.NearestFilter&&d.minFilter!==u.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[a]=l,l}loadImageSource(e,t){const n=this,s=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const r=s.images[e],c=self.URL||self.webkitURL;let a=r.uri||"",l=!1;if(r.bufferView!==void 0)a=n.getDependency("bufferView",r.bufferView).then(function(h){l=!0;const m=new Blob([h],{type:r.mimeType});return a=c.createObjectURL(m),a});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(a).then(function(h){return new Promise(function(m,g){let _=m;t.isImageBitmapLoader===!0&&(_=function(b){const f=new u.Texture(b);f.needsUpdate=!0,m(f)}),t.load(u.LoaderUtils.resolveURL(h,i.path),_,void 0,g)})}).then(function(h){return l===!0&&c.revokeObjectURL(a),U(h,r),h.userData.mimeType=r.mimeType||vt(r.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const i=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),i.extensions[E.KHR_TEXTURE_TRANSFORM]){const c=n.extensions!==void 0?n.extensions[E.KHR_TEXTURE_TRANSFORM]:void 0;if(c){const a=i.associations.get(r);r=i.extensions[E.KHR_TEXTURE_TRANSFORM].extendTexture(r,c),i.associations.set(r,a)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const c="PointsMaterial:"+n.uuid;let a=this.cache.get(c);a||(a=new u.PointsMaterial,u.Material.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,a.sizeAttenuation=!1,this.cache.add(c,a)),n=a}else if(e.isLine){const c="LineBasicMaterial:"+n.uuid;let a=this.cache.get(c);a||(a=new u.LineBasicMaterial,u.Material.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,this.cache.add(c,a)),n=a}if(s||i||r){let c="ClonedMaterial:"+n.uuid+":";s&&(c+="derivative-tangents:"),i&&(c+="vertex-colors:"),r&&(c+="flat-shading:");let a=this.cache.get(c);a||(a=n.clone(),i&&(a.vertexColors=!0),r&&(a.flatShading=!0),s&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(c,a),this.associations.set(a,this.associations.get(n))),n=a}e.material=n}getMaterialType(){return u.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,i=n.materials[e];let r;const c={},a=i.extensions||{},l=[];if(a[E.KHR_MATERIALS_UNLIT]){const h=s[E.KHR_MATERIALS_UNLIT];r=h.getMaterialType(),l.push(h.extendParams(c,i,t))}else{const h=i.pbrMetallicRoughness||{};if(c.color=new u.Color(1,1,1),c.opacity=1,Array.isArray(h.baseColorFactor)){const m=h.baseColorFactor;c.color.setRGB(m[0],m[1],m[2],u.LinearSRGBColorSpace),c.opacity=m[3]}h.baseColorTexture!==void 0&&l.push(t.assignTexture(c,"map",h.baseColorTexture,u.SRGBColorSpace)),c.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,c.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(c,"metalnessMap",h.metallicRoughnessTexture)),l.push(t.assignTexture(c,"roughnessMap",h.metallicRoughnessTexture))),r=this._invokeOne(function(m){return m.getMaterialType&&m.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(m){return m.extendMaterialParams&&m.extendMaterialParams(e,c)})))}i.doubleSided===!0&&(c.side=u.DoubleSide);const d=i.alphaMode||he.OPAQUE;if(d===he.BLEND?(c.transparent=!0,c.depthWrite=!1):(c.transparent=!1,d===he.MASK&&(c.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&r!==u.MeshBasicMaterial&&(l.push(t.assignTexture(c,"normalMap",i.normalTexture)),c.normalScale=new u.Vector2(1,1),i.normalTexture.scale!==void 0)){const h=i.normalTexture.scale;c.normalScale.set(h,h)}if(i.occlusionTexture!==void 0&&r!==u.MeshBasicMaterial&&(l.push(t.assignTexture(c,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(c.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&r!==u.MeshBasicMaterial){const h=i.emissiveFactor;c.emissive=new u.Color().setRGB(h[0],h[1],h[2],u.LinearSRGBColorSpace)}return i.emissiveTexture!==void 0&&r!==u.MeshBasicMaterial&&l.push(t.assignTexture(c,"emissiveMap",i.emissiveTexture,u.SRGBColorSpace)),Promise.all(l).then(function(){const h=new r(c);return i.name&&(h.name=i.name),U(h,i),t.associations.set(h,{materials:e}),i.extensions&&K(s,h,i),h})}createUniqueName(e){const t=u.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,s=this.primitiveCache;function i(c){return n[E.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(c,t).then(function(a){return Re(a,c,t)})}const r=[];for(let c=0,a=e.length;c<a;c++){const l=e[c],d=Nt(l),h=s[d];if(h)r.push(h.promise);else{let m;l.extensions&&l.extensions[E.KHR_DRACO_MESH_COMPRESSION]?m=i(l):m=Re(new u.BufferGeometry,l,t),s[d]={primitive:l,promise:m},r.push(m)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,s=this.extensions,i=n.meshes[e],r=i.primitives,c=[];for(let a=0,l=r.length;a<l;a++){const d=r[a].material===void 0?Ot(this.cache):this.getDependency("material",r[a].material);c.push(d)}return c.push(t.loadGeometries(r)),Promise.all(c).then(function(a){const l=a.slice(0,a.length-1),d=a[a.length-1],h=[];for(let g=0,_=d.length;g<_;g++){const b=d[g],f=r[g];let p;const y=l[g];if(f.mode===I.TRIANGLES||f.mode===I.TRIANGLE_STRIP||f.mode===I.TRIANGLE_FAN||f.mode===void 0)p=i.isSkinnedMesh===!0?new u.SkinnedMesh(b,y):new u.Mesh(b,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),f.mode===I.TRIANGLE_STRIP?p.geometry=Ee(p.geometry,u.TriangleStripDrawMode):f.mode===I.TRIANGLE_FAN&&(p.geometry=Ee(p.geometry,u.TriangleFanDrawMode));else if(f.mode===I.LINES)p=new u.LineSegments(b,y);else if(f.mode===I.LINE_STRIP)p=new u.Line(b,y);else if(f.mode===I.LINE_LOOP)p=new u.LineLoop(b,y);else if(f.mode===I.POINTS)p=new u.Points(b,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+f.mode);Object.keys(p.geometry.morphAttributes).length>0&&kt(p,i),p.name=t.createUniqueName(i.name||"mesh_"+e),U(p,i),f.extensions&&K(s,p,f),t.assignFinalMaterial(p),h.push(p)}for(let g=0,_=h.length;g<_;g++)t.associations.set(h[g],{meshes:e,primitives:g});if(h.length===1)return i.extensions&&K(s,h[0],i),h[0];const m=new u.Group;i.extensions&&K(s,m,i),t.associations.set(m,{meshes:e});for(let g=0,_=h.length;g<_;g++)m.add(h[g]);return m})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new u.PerspectiveCamera(u.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new u.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),U(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,i=t.joints.length;s<i;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const i=s.pop(),r=s,c=[],a=[];for(let l=0,d=r.length;l<d;l++){const h=r[l];if(h){c.push(h);const m=new u.Matrix4;i!==null&&m.fromArray(i.array,l*16),a.push(m)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new u.Skeleton(c,a)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],i=s.name?s.name:"animation_"+e,r=[],c=[],a=[],l=[],d=[];for(let h=0,m=s.channels.length;h<m;h++){const g=s.channels[h],_=s.samplers[g.sampler],b=g.target,f=b.node,p=s.parameters!==void 0?s.parameters[_.input]:_.input,y=s.parameters!==void 0?s.parameters[_.output]:_.output;b.node!==void 0&&(r.push(this.getDependency("node",f)),c.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",y)),l.push(_),d.push(b))}return Promise.all([Promise.all(r),Promise.all(c),Promise.all(a),Promise.all(l),Promise.all(d)]).then(function(h){const m=h[0],g=h[1],_=h[2],b=h[3],f=h[4],p=[];for(let y=0,w=m.length;y<w;y++){const T=m[y],S=g[y],M=_[y],A=b[y],P=f[y];if(T===void 0)continue;T.updateMatrix&&T.updateMatrix();const D=n._createAnimationTracks(T,S,M,A,P);if(D)for(let j=0;j<D.length;j++)p.push(D[j])}return new u.AnimationClip(i,void 0,p)})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(i){const r=n._getNodeRef(n.meshCache,s.mesh,i);return s.weights!==void 0&&r.traverse(function(c){if(c.isMesh)for(let a=0,l=s.weights.length;a<l;a++)c.morphTargetInfluences[a]=s.weights[a]}),r})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],i=n._loadNodeShallow(e),r=[],c=s.children||[];for(let l=0,d=c.length;l<d;l++)r.push(n.getDependency("node",c[l]));const a=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([i,Promise.all(r),a]).then(function(l){const d=l[0],h=l[1],m=l[2];m!==null&&d.traverse(function(g){g.isSkinnedMesh&&g.bind(m,Ht)});for(let g=0,_=h.length;g<_;g++)d.add(h[g]);return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],r=i.name?s.createUniqueName(i.name):"",c=[],a=s._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return a&&c.push(a),i.camera!==void 0&&c.push(s.getDependency("camera",i.camera).then(function(l){return s._getNodeRef(s.cameraCache,i.camera,l)})),s._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){c.push(l)}),this.nodeCache[e]=Promise.all(c).then(function(l){let d;if(i.isBone===!0?d=new u.Bone:l.length>1?d=new u.Group:l.length===1?d=l[0]:d=new u.Object3D,d!==l[0])for(let h=0,m=l.length;h<m;h++)d.add(l[h]);if(i.name&&(d.userData.name=i.name,d.name=r),U(d,i),i.extensions&&K(n,d,i),i.matrix!==void 0){const h=new u.Matrix4;h.fromArray(i.matrix),d.applyMatrix4(h)}else i.translation!==void 0&&d.position.fromArray(i.translation),i.rotation!==void 0&&d.quaternion.fromArray(i.rotation),i.scale!==void 0&&d.scale.fromArray(i.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(i.mesh!==void 0&&s.meshCache.refs[i.mesh]>1){const h=s.associations.get(d);s.associations.set(d,{...h})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,i=new u.Group;n.name&&(i.name=s.createUniqueName(n.name)),U(i,n),n.extensions&&K(t,i,n);const r=n.nodes||[],c=[];for(let a=0,l=r.length;a<l;a++)c.push(s.getDependency("node",r[a]));return Promise.all(c).then(function(a){for(let d=0,h=a.length;d<h;d++)i.add(a[d]);const l=d=>{const h=new Map;for(const[m,g]of s.associations)(m instanceof u.Material||m instanceof u.Texture)&&h.set(m,g);return d.traverse(m=>{const g=s.associations.get(m);g!=null&&h.set(m,g)}),h};return s.associations=l(i),i})}_createAnimationTracks(e,t,n,s,i){const r=[],c=e.name?e.name:e.uuid,a=[];G[i.path]===G.weights?e.traverse(function(m){m.morphTargetInfluences&&a.push(m.name?m.name:m.uuid)}):a.push(c);let l;switch(G[i.path]){case G.weights:l=u.NumberKeyframeTrack;break;case G.rotation:l=u.QuaternionKeyframeTrack;break;case G.translation:case G.scale:l=u.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:l=u.NumberKeyframeTrack;break;case 2:case 3:default:l=u.VectorKeyframeTrack;break}break}const d=s.interpolation!==void 0?Dt[s.interpolation]:u.InterpolateLinear,h=this._getArrayFromAccessor(n);for(let m=0,g=a.length;m<g;m++){const _=new l(a[m]+"."+G[i.path],t.array,h,d);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(_),r.push(_)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=me(t.constructor),s=new Float32Array(t.length);for(let i=0,r=t.length;i<r;i++)s[i]=t[i]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof u.QuaternionKeyframeTrack?Pt:Ne;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Ut(o,e,t){const n=e.attributes,s=new u.Box3;if(n.POSITION!==void 0){const c=t.json.accessors[n.POSITION],a=c.min,l=c.max;if(a!==void 0&&l!==void 0){if(s.set(new u.Vector3(a[0],a[1],a[2]),new u.Vector3(l[0],l[1],l[2])),c.normalized){const d=me(Y[c.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const c=new u.Vector3,a=new u.Vector3;for(let l=0,d=i.length;l<d;l++){const h=i[l];if(h.POSITION!==void 0){const m=t.json.accessors[h.POSITION],g=m.min,_=m.max;if(g!==void 0&&_!==void 0){if(a.setX(Math.max(Math.abs(g[0]),Math.abs(_[0]))),a.setY(Math.max(Math.abs(g[1]),Math.abs(_[1]))),a.setZ(Math.max(Math.abs(g[2]),Math.abs(_[2]))),m.normalized){const b=me(Y[m.componentType]);a.multiplyScalar(b)}c.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(c)}o.boundingBox=s;const r=new u.Sphere;s.getCenter(r.center),r.radius=s.min.distanceTo(s.max)/2,o.boundingSphere=r}function Re(o,e,t){const n=e.attributes,s=[];function i(r,c){return t.getDependency("accessor",r).then(function(a){o.setAttribute(c,a)})}for(const r in n){const c=pe[r]||r.toLowerCase();c in o.attributes||s.push(i(n[r],c))}if(e.indices!==void 0&&!o.index){const r=t.getDependency("accessor",e.indices).then(function(c){o.setIndex(c)});s.push(r)}return u.ColorManagement.workingColorSpace!==u.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${u.ColorManagement.workingColorSpace}" not supported.`),U(o,e),Ut(o,e,t),Promise.all(s).then(function(){return e.targets!==void 0?It(o,e.targets,t):o})}const Ae=new u.Vector3,jt=new u.Quaternion,Le=new u.Vector3;class Gt extends u.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS3DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.addEventListener("removed",function(){this.traverse(function(t){t.element instanceof t.element.ownerDocument.defaultView.Element&&t.element.parentNode!==null&&t.element.remove()})})}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this}}class Bt extends Gt{constructor(e){super(e),this.isCSS3DSprite=!0,this.rotation2D=0}copy(e,t){return super.copy(e,t),this.rotation2D=e.rotation2D,this}}const H=new u.Matrix4,zt=new u.Matrix4;class Kt{constructor(e={}){const t=this;let n,s,i,r;const c={camera:{style:""},objects:new WeakMap},a=e.element!==void 0?e.element:document.createElement("div");a.style.overflow="hidden",this.domElement=a;const l=document.createElement("div");l.style.transformOrigin="0 0",l.style.pointerEvents="none",a.appendChild(l);const d=document.createElement("div");d.style.transformStyle="preserve-3d",l.appendChild(d),this.getSize=function(){return{width:n,height:s}},this.render=function(f,p){const y=p.projectionMatrix.elements[5]*r;p.view&&p.view.enabled?(l.style.transform=`translate( ${-p.view.offsetX*(n/p.view.width)}px, ${-p.view.offsetY*(s/p.view.height)}px )`,l.style.transform+=`scale( ${p.view.fullWidth/p.view.width}, ${p.view.fullHeight/p.view.height} )`):l.style.transform="",f.matrixWorldAutoUpdate===!0&&f.updateMatrixWorld(),p.parent===null&&p.matrixWorldAutoUpdate===!0&&p.updateMatrixWorld();let w,T;p.isOrthographicCamera&&(w=-(p.right+p.left)/2,T=(p.top+p.bottom)/2);const S=p.view&&p.view.enabled?p.view.height/p.view.fullHeight:1,M=p.isOrthographicCamera?`scale( ${S} )scale(`+y+")translate("+h(w)+"px,"+h(T)+"px)"+m(p.matrixWorldInverse):`scale( ${S} )translateZ(`+y+"px)"+m(p.matrixWorldInverse),P=(p.isPerspectiveCamera?"perspective("+y+"px) ":"")+M+"translate("+i+"px,"+r+"px)";c.camera.style!==P&&(d.style.transform=P,c.camera.style=P),b(f,f,p)},this.setSize=function(f,p){n=f,s=p,i=n/2,r=s/2,a.style.width=f+"px",a.style.height=p+"px",l.style.width=f+"px",l.style.height=p+"px",d.style.width=f+"px",d.style.height=p+"px"};function h(f){return Math.abs(f)<1e-10?0:f}function m(f){const p=f.elements;return"matrix3d("+h(p[0])+","+h(-p[1])+","+h(p[2])+","+h(p[3])+","+h(p[4])+","+h(-p[5])+","+h(p[6])+","+h(p[7])+","+h(p[8])+","+h(-p[9])+","+h(p[10])+","+h(p[11])+","+h(p[12])+","+h(-p[13])+","+h(p[14])+","+h(p[15])+")"}function g(f){const p=f.elements;return"translate(-50%,-50%)"+("matrix3d("+h(p[0])+","+h(p[1])+","+h(p[2])+","+h(p[3])+","+h(-p[4])+","+h(-p[5])+","+h(-p[6])+","+h(-p[7])+","+h(p[8])+","+h(p[9])+","+h(p[10])+","+h(p[11])+","+h(p[12])+","+h(p[13])+","+h(p[14])+","+h(p[15])+")")}function _(f){f.isCSS3DObject&&(f.element.style.display="none");for(let p=0,y=f.children.length;p<y;p++)_(f.children[p])}function b(f,p,y,w){if(f.visible===!1){_(f);return}if(f.isCSS3DObject){const T=f.layers.test(y.layers)===!0,S=f.element;if(S.style.display=T===!0?"":"none",T===!0){f.onBeforeRender(t,p,y);let M;f.isCSS3DSprite?(H.copy(y.matrixWorldInverse),H.transpose(),f.rotation2D!==0&&H.multiply(zt.makeRotationZ(f.rotation2D)),f.matrixWorld.decompose(Ae,jt,Le),H.setPosition(Ae),H.scale(Le),H.elements[3]=0,H.elements[7]=0,H.elements[11]=0,H.elements[15]=1,M=g(H)):M=g(f.matrixWorld);const A=c.objects.get(f);if(A===void 0||A.style!==M){S.style.transform=M;const P={style:M};c.objects.set(f,P)}S.parentNode!==d&&d.appendChild(S),f.onAfterRender(t,p,y)}}for(let T=0,S=f.children.length;T<S;T++)b(f.children[T],p,y)}}}var q=function(){var o=0,e=document.createElement("div");e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",function(d){d.preventDefault(),n(++o%e.children.length)},!1);function t(d){return e.appendChild(d.dom),d}function n(d){for(var h=0;h<e.children.length;h++)e.children[h].style.display=h===d?"block":"none";o=d}var s=(performance||Date).now(),i=s,r=0,c=t(new q.Panel("FPS","#0ff","#002")),a=t(new q.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var l=t(new q.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:e,addPanel:t,showPanel:n,begin:function(){s=(performance||Date).now()},end:function(){r++;var d=(performance||Date).now();if(a.update(d-s,200),d>=i+1e3&&(c.update(r*1e3/(d-i),100),i=d,r=0,l)){var h=performance.memory;l.update(h.usedJSHeapSize/1048576,h.jsHeapSizeLimit/1048576)}return d},update:function(){s=this.end()},domElement:e,setMode:n}};q.Panel=function(o,e,t){var n=1/0,s=0,i=Math.round,r=i(window.devicePixelRatio||1),c=80*r,a=48*r,l=3*r,d=2*r,h=3*r,m=15*r,g=74*r,_=30*r,b=document.createElement("canvas");b.width=c,b.height=a,b.style.cssText="width:80px;height:48px";var f=b.getContext("2d");return f.font="bold "+9*r+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=t,f.fillRect(0,0,c,a),f.fillStyle=e,f.fillText(o,l,d),f.fillRect(h,m,g,_),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(h,m,g,_),{dom:b,update:function(p,y){n=Math.min(n,p),s=Math.max(s,p),f.fillStyle=t,f.globalAlpha=1,f.fillRect(0,0,c,m),f.fillStyle=e,f.fillText(i(p)+" "+o+" ("+i(n)+"-"+i(s)+")",l,d),f.drawImage(b,h+r,m,g-r,_,h,m,g-r,_),f.fillRect(h+g-r,m,r,_),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(h+g-r,m,r,i((1-p/y)*_))}}};function Vt(o){return new u.CameraHelper(o)}function Wt(o=150,...e){return new u.GridHelper(o,o/10,...e)}function Xt(o){return new u.BoxHelper(o,16776960)}function Yt(o,e){return new Ie(o,e)}function qt(o,e){return new st(o,e)}function $t(){const o=new u.Raycaster,e=new u.Vector2(0,0);return{raycaster:o,pointer:e}}function Zt(o=10){return new u.AxesHelper(o)}function Qt(o=new u.Vector3(1,1,1),e=new u.Vector3(10,10,10),t=5,n=16776960){return o.normalize(),new u.ArrowHelper(o,e,t,n)}function Jt(){const o=new q;return o.dom.style.cssText="position:absolute;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",o}const ve=o=>{o.geometry&&o.geometry.dispose(),o.material&&(Array.isArray(o.material)?o.material.forEach(e=>{Ce(e)}):Ce(o.material)),o.children&&o.children.forEach(e=>ve(e))};function Ce(o){for(const e in o)o[e]&&o[e].isTexture&&o[e].dispose();o.dispose()}const de={};async function es(o,e=50){const t={type:o.type,name:o.name,position:o.position.toArray(),rotation:o.rotation.toArray(),scale:o.scale.toArray(),visible:o.visible,children:[],geometry:null,material:null,userData:o.userData};o.isMesh&&(t.geometry=se(o.geometry),t.material=ie(o.material));const n=[{object:o,parentData:t}];let s=0;for(;n.length>0;){const{object:i,parentData:r}=n.pop();for(const c of i.children){const a={type:c.type,name:c.name,position:c.position.toArray(),rotation:c.rotation.toArray(),scale:c.scale.toArray(),visible:c.visible,children:[],geometry:null,material:null,userData:c.userData};c.isMesh&&(a.geometry=se(c.geometry),a.material=ie(c.material)),r.children.push(a),n.push({object:c,parentData:a}),s++,s%e===0&&await new Promise(l=>requestAnimationFrame(l))}}return t}function ts(o){const e={type:o.type,name:o.name,position:o.position.toArray(),rotation:o.rotation.toArray(),scale:o.scale.toArray(),visible:o.visible,children:[],geometry:null,material:null,userData:o.userData};o.isMesh&&(e.geometry=se(o.geometry),e.material=ie(o.material));const t=[{object:o,parentData:e}];for(;t.length>0;){const{object:n,parentData:s}=t.pop();for(const i of n.children){const r={type:i.type,name:i.name,position:i.position.toArray(),rotation:i.rotation.toArray(),scale:i.scale.toArray(),visible:i.visible,children:[],geometry:null,material:null,userData:i.userData};i.isMesh&&(r.geometry=se(i.geometry),r.material=ie(i.material)),s.children.push(r),t.push({object:i,parentData:r})}}return e}async function He(o,e=50){const t=[];let n;switch(o.type){case"Mesh":const i=ne(o.geometry),r=re(o.material);n=new x.Mesh(i,r);break;case"Group":n=new x.Group;break;case"Object3D":n=new x.Object3D;break;default:return console.warn(`Unsupported object type: ${o.type}`),null}n.name=o.name,n.position.fromArray(o.position),n.rotation.fromArray(o.rotation),n.scale.fromArray(o.scale),n.visible=o.visible,n.userData=o.userData,t.push({data:o,object:n});let s=0;for(;t.length>0;){const{data:i,object:r}=t.pop();for(const c of[...i.children].reverse()){let a;switch(c.type){case"Mesh":const l=ne(c.geometry),d=re(c.material);a=new x.Mesh(l,d);break;case"Group":a=new x.Group;break;case"Object3D":a=new x.Object3D;break;default:console.warn(`Unsupported object type: ${c.type}`);continue}a&&(a.name=c.name,a.position.fromArray(c.position),a.rotation.fromArray(c.rotation),a.scale.fromArray(c.scale),a.visible=c.visible,a.userData=c.userData,r.add(a),t.push({data:c,object:a}),s++,s%e===0&&await new Promise(l=>requestAnimationFrame(l)))}}return n}function ss(o){const e=[];let t;switch(o.type){case"Mesh":const n=ne(o.geometry),s=re(o.material);t=new x.Mesh(n,s);break;case"Group":t=new x.Group;break;case"Object3D":t=new x.Object3D;break;default:return console.warn(`Unsupported object type: ${o.type}`),null}for(t.name=o.name,t.position.fromArray(o.position),t.rotation.fromArray(o.rotation),t.scale.fromArray(o.scale),t.visible=o.visible,t.userData=o.userData,e.push({data:o,object:t});e.length>0;){const{data:n,object:s}=e.pop();for(const i of[...n.children].reverse()){let r;switch(i.type){case"Mesh":const c=ne(i.geometry),a=re(i.material);r=new x.Mesh(c,a);break;case"Group":r=new x.Group;break;case"Object3D":r=new x.Object3D;break;default:console.warn(`Unsupported object type: ${i.type}`);continue}r&&(r.name=i.name,r.position.fromArray(i.position),r.rotation.fromArray(i.rotation),r.scale.fromArray(i.scale),r.visible=i.visible,r.userData=i.userData,s.add(r),e.push({data:i,object:r}))}}return t}function se(o){const e={},{attributes:t,index:n,type:s}=o;t.position&&(e.position={type:"Float32Array",array:Array.from(t.position.array),itemSize:3}),t.normal&&(e.normal={type:"Float32Array",array:Array.from(t.normal.array),itemSize:3}),t.uv&&(e.uv={type:"Float32Array",array:Array.from(t.uv.array),itemSize:2});const i={type:s,attributes:e};return n&&n.array&&(i.index={type:"Uint32Array",array:Array.from(n.array),itemSize:1}),i}function ne(o){const{type:e,attributes:t,index:n}=o,s=new x.BufferGeometry;for(const i in t)if(t.hasOwnProperty(i)){const{type:r,array:c,itemSize:a}=t[i];s.setAttribute(i,new x.BufferAttribute(new Float32Array(c),a))}return n&&s.setIndex(n.array),s}function ie(o){return{type:o.type,color:o.color.getHex(),map:o.map?o.map.image.src:null,opacity:o.opacity,name:o.name,depthTest:o.depthTest,depthWrite:o.depthWrite,transparent:o.transparent,side:o.side,roughness:o.roughness,metalness:o.metalness,emissive:o.emissive.getHex()}}function re(o){if(de[o.name])return de[o.name];const{type:e,...t}=o,n=e||"MeshStandardMaterial",s=new x[n]({...t});if(o.map){const i=new x.TextureLoader().load(o.map);s.map=i}return s.needsUpdate=!0,de[o.name]=s,s}class Fe{constructor(){this.stats={hits:0,misses:0,totalLoadTime:0,cacheSaveTime:0,errors:0},this.loadHistory=[]}recordHit(e){this.stats.hits++,this.stats.totalLoadTime+=e,this._recordHistory("hit",e)}recordMiss(e){this.stats.misses++,this.stats.totalLoadTime+=e,this._recordHistory("miss",e)}recordCacheSave(e){this.stats.cacheSaveTime+=e}recordError(e,t){this.stats.errors++,this._recordHistory("error",0,{path:e,error:t.message})}getHitRate(){const e=this.stats.hits+this.stats.misses;return e>0?(this.stats.hits/e*100).toFixed(2)+"%":"0%"}getAvgLoadTime(){const e=this.stats.hits+this.stats.misses;return e>0?(this.stats.totalLoadTime/e).toFixed(2)+"ms":"0ms"}getStats(){const e=this.stats.hits+this.stats.misses;return{命中率:this.getHitRate(),平均加载时间:this.getAvgLoadTime(),缓存命中数:this.stats.hits,缓存未命中数:this.stats.misses,总加载次数:e,总加载时间:this.stats.totalLoadTime.toFixed(2)+"ms",缓存保存时间:this.stats.cacheSaveTime.toFixed(2)+"ms",错误次数:this.stats.errors}}getHistory(e=10){return this.loadHistory.slice(-e)}reset(){this.stats={hits:0,misses:0,totalLoadTime:0,cacheSaveTime:0,errors:0},this.loadHistory=[]}_recordHistory(e,t,n={}){this.loadHistory.push({type:e,duration:t,timestamp:Date.now(),...n}),this.loadHistory.length>100&&this.loadHistory.shift()}logReport(){console.group("📊 缓存性能报告");const e=this.getStats();Object.entries(e).forEach(([t,n])=>{console.log(`${t}: ${n}`)}),console.groupEnd()}}const F=new Fe;class Q{static async retry(e,t={}){const{maxRetries:n=3,initialDelay:s=1e3,maxDelay:i=1e4,backoffFactor:r=2,shouldRetry:c=Q.defaultShouldRetry}=t;let a,l=s;for(let d=0;d<=n;d++)try{return await e()}catch(h){if(a=h,d===n||!c(h,d))throw h;console.warn(`[ RetryHelper ] 操作失败,第 ${d+1} 次尝试失败,${l}ms 后进行第 ${d+2} 次尝试...`,h),await Q.delay(l),l=Math.min(l*r,i)}throw a}static defaultShouldRetry(e,t){if(e.name==="TypeError"&&e.message.includes("fetch"))return!0;if(e.message.includes("HTTP error")){const n=e.message.match(/status:\s*(\d+)/);if(n){const s=parseInt(n[1],10);return s>=500||s===429||s===408}}return!1}static delay(e){return new Promise(t=>setTimeout(t,e))}}const te={NETWORK:"NETWORK",PARSE:"PARSE",VERSION_MISMATCH:"VERSION",UNKNOWN:"UNKNOWN"};class $ extends Error{constructor(e,t,n,s){super(e),this.name="ModelLoadError",this.type=t,this.path=n,this.originalError=s,this.timestamp=Date.now()}static networkError(e,t){return new $(`网络加载失败: ${e}`,te.NETWORK,e,t)}static parseError(e,t){return new $(`模型解析失败: ${e}`,te.PARSE,e,t)}static versionMismatchError(e,t,n){return new $(`版本不匹配: ${e} (期望: ${t}, 实际: ${n})`,te.VERSION_MISMATCH,e)}}const Pe=4;class ge{constructor(e="threeJsIDBCache",t={}){this.version=Pe,this.dbName=e,this.options={maxSize:t.maxSize||500*1024*1024,maxEntries:t.maxEntries||50,evictRatio:t.evictRatio||.2},this.dbInit()}dbInit(){this.db=new Ge(this.dbName),this.db.version(this.version).stores({models:"&path, version, timestamp, accessCount, size"}).upgrade(async e=>{console.log("[ IDBCache 版本更新 ] ====> version",Pe);const t=e.table("models"),n=await t.toArray();for(const s of n)s.data instanceof ArrayBuffer||await t.delete(s.path)})}getDatabase(){return this.db}async saveModel(e,t,n){await this.ensureCapacity(n.byteLength),await this.db.table("models").put({path:e,version:t,data:n,size:n.byteLength,timestamp:Date.now(),accessCount:0})}async ensureCapacity(e){const t=await this.db.table("models").toArray(),n=t.reduce((c,a)=>c+(a.size||0),0),s=t.length,i=n+e>this.options.maxSize,r=s>=this.options.maxEntries;(i||r)&&(console.log(`[ IDBCache ] ====> 容量不足,开始 LRU 淘汰. 总大小: ${(n/1024/1024).toFixed(2)}MB, 条目数: ${s}`),await this.evictLRU(t))}async evictLRU(e){const t=e.sort((c,a)=>(c.accessCount||0)!==(a.accessCount||0)?(c.accessCount||0)-(a.accessCount||0):(c.timestamp||0)-(a.timestamp||0)),n=Math.max(1,Math.floor(t.length*this.options.evictRatio)),s=t.slice(0,n),i=s.map(c=>c.path);await this.db.table("models").bulkDelete(i);const r=s.reduce((c,a)=>c+(a.size||0),0);console.log(`[ IDBCache ] ====> LRU 淘汰完成. 删除 ${n} 个条目,释放 ${(r/1024/1024).toFixed(2)}MB`)}async getModel(e,t){const n=await this.db.table("models").get(e);return n?n.version!==t?(console.log("模型版本不一致, 清除当前记录"),await this.db.table("models").delete(e),null):(await this.db.table("models").update(e,{accessCount:(n.accessCount||0)+1,timestamp:Date.now()}),n.data):(console.warn(`Model "${e}" not found in table models`),null)}async cacheModel(e,t,n){console.log("[ ] ====> path, modelData, version",e,t,n);try{this.db.table("models").put({version:n,path:e,data:t}).then(()=>{console.log(`Model "${e}" cached successfully in table models`)})}catch{console.log(" 缓存模型失败 =====> ")}return t}async loadCachedModel(e,t){let n=null;try{if(n=await this.db.table("models").get(e),!n)return console.warn(`Model "${t}" not found in table models`),null;if(n.version!==t)return console.log(" =====> 模型版本不一致, 清除当前记录"),await this.db.table("models").delete(e),null}catch{return console.log(" =====> 查询表中模型失败"),this.db.delete().then(()=>{this.init()}),null}return n.data}async getStats(){const e=await this.db.table("models").toArray(),t=e.reduce((s,i)=>s+(i.size||0),0),n=e.reduce((s,i)=>s+(i.accessCount||0),0);return{count:e.length,totalSize:t,totalSizeMB:(t/1024/1024).toFixed(2),maxEntries:this.options.maxEntries,maxSizeMB:(this.options.maxSize/1024/1024).toFixed(2),usagePercentage:(t/this.options.maxSize*100).toFixed(2),totalAccessCount:n,avgAccessCount:e.length>0?(n/e.length).toFixed(2):0}}async clear(){await this.db.table("models").clear(),console.log("[ IDBCache ] ====> 缓存已清空")}async deleteModel(e){await this.db.table("models").delete(e)}}function Te(o){const{geometries:e,materials:t,hierarchy:n}=o,s=new Map;e.forEach((a,l)=>{const d=ns(a);s.set(l,d)});const i=new Map;t.forEach((a,l)=>{const d=is(a);i.set(l,d)});const r=new x.Group;r.name="Scene";const c=new Map;return n.forEach(a=>{let l;if(a.type==="Mesh"){const d=a.geometryIndex>=0?s.get(a.geometryIndex):null,h=a.materialIndex>=0?i.get(a.materialIndex):null;l=new x.Mesh(d,h)}else a.type==="Group"?l=new x.Group:a.type==="Object3D"?l=new x.Object3D:l=new x.Object3D;l.name=a.name,l.position.fromArray(a.position),l.rotation.fromArray(a.rotation),l.scale.fromArray(a.scale),l.visible=a.visible,c.set(a.id,l)}),n.forEach(a=>{const l=c.get(a.id);if(a.parentId!==null){const d=c.get(a.parentId);d&&d.add(l)}else r.add(l)}),r}function ns(o){const e=new x.BufferGeometry;for(const t in o.attributes){const n=o.attributes[t],s=n.array;let i;if(s.byteLength===0){console.warn(`[ sceneRebuilder ] 属性 ${t} 的数组为空`);continue}if(s.buffer&&s.buffer.byteLength===0){console.warn(`[ sceneRebuilder ] 属性 ${t} 的 buffer 已被转移,尝试重建`);continue}i=s;const r=new x.BufferAttribute(i,n.itemSize);r.normalized=n.normalized,e.setAttribute(t,r)}if(o.index){const t=o.index,n=t.array;if(n&&n.byteLength>0){const s=new x.BufferAttribute(n,t.itemSize);e.setIndex(s)}}return e}function is(o){let e;const t={color:o.color!==void 0?o.color:16777215,opacity:o.opacity!==void 0?o.opacity:1,transparent:o.transparent!==void 0?o.transparent:!1,alphaTest:o.alphaTest!==void 0?o.alphaTest:0,side:o.side!==void 0?o.side:x.FrontSide,depthTest:o.depthTest!==void 0?o.depthTest:!0,depthWrite:o.depthWrite!==void 0?o.depthWrite:!0,wireframe:o.wireframe!==void 0?o.wireframe:!1,vertexColors:o.vertexColors!==void 0?o.vertexColors:!1};switch(o.type){case"MeshStandardMaterial":e=new x.MeshStandardMaterial({...t,roughness:o.roughness!==void 0?o.roughness:.5,metalness:o.metalness!==void 0?o.metalness:.5,emissive:o.emissive!==void 0?o.emissive:0,emissiveIntensity:o.emissiveIntensity!==void 0?o.emissiveIntensity:1});break;case"MeshBasicMaterial":e=new x.MeshBasicMaterial({...t});break;case"MeshPhongMaterial":e=new x.MeshPhongMaterial({...t,shininess:o.shininess!==void 0?o.shininess:30,specular:o.specular!==void 0?o.specular:1118481,emissive:o.emissive!==void 0?o.emissive:0,emissiveIntensity:o.emissiveIntensity!==void 0?o.emissiveIntensity:1});break;default:e=new x.MeshStandardMaterial(t)}return e.uuid=o.uuid,e}class rs{constructor(){this.geometries=[],this.materials=[],this.hierarchy=[],this.geometryMap=new Map,this.materialMap=new Map}addChunk(e){e.geometries&&e.geometries.forEach(t=>{const n=this.geometries.length;this.geometries.push(t),this.geometryMap.set(t.uuid,n)}),e.materials&&e.materials.forEach(t=>{const n=this.materials.length;this.materials.push(t),this.materialMap.set(t.uuid,n)}),e.hierarchy&&this.hierarchy.push(...e.hierarchy)}buildCurrent(){const e={geometries:this.geometries,materials:this.materials,hierarchy:this.hierarchy};return Te(e)}finalize(){return this.buildCurrent()}}function os(o){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/gltfParser.worker-D2lwod50.js").href:new URL("assets/gltfParser.worker-D2lwod50.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{name:o==null?void 0:o.name})}function as(o){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/gltfParserOptimized.worker-FT73rIOj.js").href:new URL("assets/gltfParserOptimized.worker-FT73rIOj.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{name:o==null?void 0:o.name})}let X;const fe="/draco/";let V,W,De=0;const B=new Map,v=new Map,Ue=(o={})=>{const{debug:e=!1}=o,t=new rt,n=new nt;n.setDecoderPath(fe),t.setDRACOLoader(n);const s={info:(...f)=>e&&console.log(...f),warn:(...f)=>e&&console.warn(...f),error:(...f)=>console.error(...f),time:f=>e&&console.time(f),timeEnd:f=>e&&console.timeEnd(f)};function i(f,p,y,w){return t.load(f,p,y,w)}function r(f,p){return new Promise((y,w)=>{t.load(f,y,p,w)})}async function c(f,p,y,w={}){const T=performance.now();let S=!1;const{maxRetries:M=3,optimizeMaterials:A=!1,simplifyGeometry:P=!1,simplifyRatio:D=.5,simplifyOptions:j={},useMemoryCache:J=!0}=w;if(J){const C=v.get(f);if(C&&C.has(p)){const k=C.get(p);s.info(`[ 内存缓存命中 ] ${f} (version: ${p})`),s.time("[ 内存缓存克隆耗时 ]");const z=k.clone(!0);return s.timeEnd("[ 内存缓存克隆耗时 ]"),F.recordHit(performance.now()-T),z}}try{let C=await l(f,p);if(C)s.info(`[ asyncFetch ] ====> IndexedDB 缓存命中: ${f}`),S=!0;else{s.info(`[ asyncFetch ] ====> 缓存未命中: ${f}`),s.time("[ fetchArrayBuffer ] 加载模型耗时"),C=await Q.retry(()=>a(f,y),{maxRetries:M,shouldRetry:_e=>!!(_e.name==="TypeError"||_e.message.includes("HTTP error! status: 5"))}),s.timeEnd("[ fetchArrayBuffer ] 加载模型耗时");const N=performance.now();await X.saveModel(f,p,C);const oe=performance.now()-N;F.recordCacheSave(oe),S=!1}s.time("[ 解析模型耗时 ]");let k=await d(C);if(s.timeEnd("[ 解析模型耗时 ]"),s.time("[ 模型优化耗时 ]"),A){s.info("🔧 [ 材质优化 ] 开始合并相同材质...");const{modelOptimizer:N}=await Promise.resolve().then(()=>require("./modelOptimizer-A0Cs6f9e.cjs"));k=N.optimizeMaterials(k)}if(P){s.info(`🔧 [ 几何体简化 ] 开始简化模型 (比例: ${D})...`);const{modelOptimizer:N}=await Promise.resolve().then(()=>require("./modelOptimizer-A0Cs6f9e.cjs")),oe={minFaceCount:100,preserveUVs:!0,...j};k=N.simplifyModel(k,D,oe)}if(s.timeEnd("[ 模型优化耗时 ]"),J){v.has(f)||v.set(f,new Map);const N=v.get(f);N.has(p)||(s.info(`[ 内存缓存 ] 存储模型 ${f} (version: ${p})`),N.set(p,k.clone(!0)))}const z=performance.now()-T;return S?F.recordHit(z):F.recordMiss(z),k}catch(C){throw s.error(`加载模型 ${f} 失败:`,C),F.recordError(f,C),C.name==="TypeError"&&C.message.includes("fetch")?$.networkError(f,C):C}}async function a(f,p){return new Promise((y,w)=>{fetch(f).then(T=>{if(!T.ok)throw new Error(`HTTP error! status: ${T.status}`);return T}).then(T=>{const S=T.headers.get("content-length"),M=S?parseInt(S,10):0;if(p&&M>0){const A=T.body.getReader();let P=0;const D=[],j=()=>{A.read().then(({done:J,value:C})=>{if(J){const k=new Uint8Array(P);let z=0;for(const N of D)k.set(N,z),z+=N.length;y(k.buffer);return}D.push(C),P+=C.length,p(Math.round(P/M*100)),j()}).catch(w)};j()}else return T.arrayBuffer()}).then(T=>y(T)).catch(T=>{w(T)})})}async function l(f,p){return X||(X=new ge),X.getModel(f,p)}async function d(f,p={}){if(!f)return null;const{useOptimizedParser:y=!0,useProgressive:w=!1}=p;if(y){const M=m();if(M)try{s.time("[ 优化解析 ] 使用 Transferable Objects 解析");const A=await g(M,f,w);return s.timeEnd("[ 优化解析 ] 使用 Transferable Objects 解析"),Te(A)}catch(A){s.warn("[ 优化解析 ] 失败,回退到标准解析",A)}}const T=h();if(T)try{const M=await _(T,f);return He(M)}catch(M){s.warn("[ GLTF Worker ] ====> 解析失败,回退到主线程解析",M)}return(await b(f)).scene}const h=()=>{if(typeof window>"u"||typeof Worker>"u")return null;if(!V)try{s.info("[GLTF Worker] 使用 ?worker 工厂函数创建 Worker..."),V=os(),s.info("[GLTF Worker] Worker 创建成功:",V),V.onmessage=f=>{const{id:p,data:y,error:w}=f.data||{};if(!p||!B.has(p))return;const{resolve:T,reject:S}=B.get(p);B.delete(p),w?S(new Error(w)):T(y)},V.onmessageerror=f=>{console.error("[ GLTF Worker ] ====> 消息解析失败",f)},V.onerror=f=>{console.error("[ GLTF Worker ] ====> 运行错误",f)}}catch(f){console.error("[GLTF Worker] 创建 Worker 失败:",f),console.error("[GLTF Worker] 错误堆栈:",f.stack)}return V},m=()=>{if(typeof window>"u"||typeof Worker>"u")return null;if(!W)try{s.info("[Optimized Worker] 使用 ?worker 工厂函数创建 Worker..."),W=as(),s.info("[Optimized Worker] Worker 创建成功:",W),W.onmessage=f=>{const{id:p,data:y,error:w,type:T}=f.data||{};if(!p||!B.has(p)||T==="progress")return;const{resolve:S,reject:M}=B.get(p);B.delete(p),w?M(new Error(w)):S(y)},W.onmessageerror=f=>{console.error("[ 优化 Worker ] ====> 消息解析失败",f)},W.onerror=f=>{console.error("[ 优化 Worker ] ====> 运行错误",f)}}catch(f){return s.warn("[ 优化 Worker ] ====> 创建失败,可能不支持模块化 Worker",f),null}return W},g=(f,p,y=!1)=>new Promise((w,T)=>{const S=++De;B.set(S,{resolve:w,reject:T});const M={id:S,arrayBuffer:p,dracoPath:fe,mode:y?"progressive":"standard"};f.postMessage(M,[p])}),_=(f,p)=>new Promise((y,w)=>{const T=++De;B.set(T,{resolve:y,reject:w}),f.postMessage({id:T,arrayBuffer:p,dracoPath:fe})}),b=f=>new Promise((p,y)=>{t.parse(f,"",p,y)});return{load:i,asyncLoad:r,asyncCacheLoad:c,asyncFetch:c,getCacheStats:()=>F.getStats(),getCache:()=>X||(X=new ge),logCacheReport:()=>F.logReport(),resetCacheStats:()=>F.reset(),clearMemoryCache:()=>{let f=0;for(const[p,y]of v.entries())f+=y.size,y.clear();return v.clear(),s.info(`[ 内存缓存 ] 已清空,释放了 ${f} 个模型`),f},getMemoryCacheInfo:()=>{const f=[];let p=0;for(const[y,w]of v.entries()){const T=Array.from(w.keys());p+=T.length,f.push({path:y,versions:T,count:T.length})}return{totalPaths:v.size,totalModels:p,details:f}},deleteMemoryCache:(f,p)=>{const y=v.get(f);if(!y)return!1;if(p){const w=y.delete(p);return y.size===0&&v.delete(f),s.info(`[ 内存缓存 ] 删除模型 ${f} (version: ${p})`),w}else{const w=y.size;return v.delete(f),s.info(`[ 内存缓存 ] 删除模型 ${f} 及其所有版本 (共 ${w} 个)`),w>0}}}};class je{constructor(e={}){this.options={maxPreloadCount:e.maxPreloadCount||5,preloadDelay:e.preloadDelay||1e3,enableLearning:e.enableLearning!==!1},this.loadHistory=new Map,this.loadSequence=[],this.associations=new Map,this.preloadQueue=new Set,this.isPreloading=!1,this.loader=null,this.getLoader=()=>(this.loader||(this.loader=Ue()),this.loader)}recordLoad(e,t){const n=Date.now(),s=this.loadHistory.get(e)||{count:0,lastLoadTime:0,versions:new Set};s.count++,s.lastLoadTime=n,s.versions.add(t),this.loadHistory.set(e,s),this.loadSequence.push({path:e,timestamp:n}),this.loadSequence.length>100&&this.loadSequence.shift(),this.options.enableLearning&&this.loadSequence.length>=2&&this._learnAssociations(e),this._triggerPredictivePreload(e,t)}_learnAssociations(e){const n=this.loadSequence.length-1;for(let s=Math.max(0,n-10);s<n;s++){const{path:i}=this.loadSequence[s];if(this.loadSequence[n].timestamp-this.loadSequence[s].timestamp<5*60*1e3&&i!==e){this.associations.has(i)||this.associations.set(i,new Map);const c=this.associations.get(i),a=c.get(e)||0;c.set(e,a+1)}}}_triggerPredictivePreload(e,t){setTimeout(()=>{const n=this.predictNext(e);this.preload(n,t)},this.options.preloadDelay)}predictNext(e){const t=new Map,n=this.associations.get(e);n&&n.forEach((c,a)=>{t.set(a,(t.get(a)||0)+c*2)});const s=Array.from(this.loadHistory.values()).reduce((c,a)=>c+a.count,0)/(this.loadHistory.size||1);this.loadHistory.forEach((c,a)=>{if(a!==e){const l=c.count/s;t.set(a,(t.get(a)||0)+l)}});const i=this.loadSequence.slice(-10);return new Set(i.map(c=>c.path)).forEach(c=>{c!==e&&t.set(c,(t.get(c)||0)+.5)}),Array.from(t.entries()).sort((c,a)=>a[1]-c[1]).slice(0,this.options.maxPreloadCount).map(([c])=>c)}async preload(e,t="latest"){if(this.isPreloading)return;this.isPreloading=!0;const{asyncFetch:n}=this.getLoader(),s=e.filter(i=>!this.preloadQueue.has(i)).slice(0,this.options.maxPreloadCount).map(async i=>{this.preloadQueue.add(i);try{console.log(`[ 智能预加载 ] 开始预加载: ${i}`),await n(i,t),console.log(`[ 智能预加载 ] 完成: ${i}`)}catch(r){console.warn(`[ 智能预加载 ] 失败: ${i}`,r)}finally{this.preloadQueue.delete(i)}});await Promise.all(s),this.isPreloading=!1}addAssociation(e,t){this.associations.has(e)||this.associations.set(e,new Map);const n=this.associations.get(e);t.forEach(s=>{const i=n.get(s)||0;n.set(s,i+10)})}getStats(){const e=Array.from(this.loadHistory.entries()).sort((t,n)=>n[1].count-t[1].count).slice(0,10).map(([t,n])=>({path:t,loadCount:n.count,lastLoadTime:new Date(n.lastLoadTime).toLocaleString()}));return{totalModelsLoaded:this.loadHistory.size,totalAssociations:this.associations.size,topModels:e,preloadQueueSize:this.preloadQueue.size}}clearHistory(){this.loadHistory.clear(),this.loadSequence=[],this.associations.clear()}exportAssociations(){const e={};return this.associations.forEach((t,n)=>{e[n]=Array.from(t.entries())}),e}importAssociations(e){Object.entries(e).forEach(([t,n])=>{const s=new Map(n);this.associations.set(t,s)})}}const cs=new je;exports.CSS3DRenderer=Kt;exports.CSS3DSprite=Bt;exports.CacheMonitor=Fe;exports.ErrorType=te;exports.IDBCache=ge;exports.ModelLoadError=$;exports.PredictiveLoader=je;exports.ProgressiveSceneBuilder=rs;exports.RetryHelper=Q;exports.Stats=q;exports.cacheMonitor=F;exports.createArrowHelper=Qt;exports.createAxesHelper=Zt;exports.createBox3Helper=Xt;exports.createCameraHelper=Vt;exports.createGridHelper=Wt;exports.createMapControls=qt;exports.createOrbitControl=Yt;exports.createRaycaster=$t;exports.createStats=Jt;exports.dataToObject3D=He;exports.dataToObject3DSync=ss;exports.disposeThreeObject=ve;exports.object3DToData=es;exports.object3DToDataSync=ts;exports.predictiveLoader=cs;exports.rebuildScene=Te;exports.useGLTFLoader=Ue;
1
+ "use strict";const u=require("three"),Be=require("dexie");function ze(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 x=ze(u),be={type:"change"},Te={type:"start"},ke={type:"end"},ee=new u.Ray,Ee=new u.Plane,Ke=Math.cos(70*u.MathUtils.DEG2RAD),L=new u.Vector3,O=2*Math.PI,R={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ae=1e-6;class Ie extends u.Controls{constructor(e,t=null){super(e,t),this.state=R.NONE,this.target=new u.Vector3,this.cursor=new u.Vector3,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:u.MOUSE.ROTATE,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.PAN},this.touches={ONE:u.TOUCH.ROTATE,TWO:u.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 u.Vector3,this._lastQuaternion=new u.Quaternion,this._lastTargetPosition=new u.Vector3,this._quat=new u.Quaternion().setFromUnitVectors(e.up,new u.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new u.Spherical,this._sphericalDelta=new u.Spherical,this._scale=1,this._panOffset=new u.Vector3,this._rotateStart=new u.Vector2,this._rotateEnd=new u.Vector2,this._rotateDelta=new u.Vector2,this._panStart=new u.Vector2,this._panEnd=new u.Vector2,this._panDelta=new u.Vector2,this._dollyStart=new u.Vector2,this._dollyEnd=new u.Vector2,this._dollyDelta=new u.Vector2,this._dollyDirection=new u.Vector3,this._mouse=new u.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=We.bind(this),this._onPointerDown=Ve.bind(this),this._onPointerUp=Xe.bind(this),this._onContextMenu=et.bind(this),this._onMouseWheel=$e.bind(this),this._onKeyDown=Ze.bind(this),this._onTouchStart=Qe.bind(this),this._onTouchMove=Je.bind(this),this._onMouseDown=Ye.bind(this),this._onMouseMove=qe.bind(this),this._interceptControlDown=tt.bind(this),this._interceptControlUp=st.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(be),this.update(),this.state=R.NONE}update(e=null){const t=this.object.position;L.copy(t).sub(this.target),L.applyQuaternion(this._quat),this._spherical.setFromVector3(L),this.autoRotate&&this.state===R.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,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=O:n>Math.PI&&(n-=O),s<-Math.PI?s+=O:s>Math.PI&&(s-=O),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,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 i=!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),i=r!=this._spherical.radius}if(L.setFromSpherical(this._spherical),L.applyQuaternion(this._quatInverse),t.copy(this.target).add(L),this.object.lookAt(this.target),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 c=L.length();r=this._clampDistance(c*this._scale);const a=c-r;this.object.position.addScaledVector(this._dollyDirection,a),this.object.updateMatrixWorld(),i=!!a}else if(this.object.isOrthographicCamera){const c=new u.Vector3(this._mouse.x,this._mouse.y,0);c.unproject(this.object);const a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=a!==this.object.zoom;const l=new u.Vector3(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(c),this.object.updateMatrixWorld(),r=L.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):(ee.origin.copy(this.object.position),ee.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ee.direction))<Ke?this.object.lookAt(this.target):(Ee.setFromNormalAndCoplanarPoint(this.object.up,this.target),ee.intersectPlane(Ee,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(),i=!0)}return this._scale=1,this._performCursorZoom=!1,i||this._lastPosition.distanceToSquared(this.object.position)>ae||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ae||this._lastTargetPosition.distanceToSquared(this.target)>ae?(this.dispatchEvent(be),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?O/60*this.autoRotateSpeed*e:O/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){L.setFromMatrixColumn(t,0),L.multiplyScalar(-e),this._panOffset.add(L)}_panUp(e,t){this.screenSpacePanning===!0?L.setFromMatrixColumn(t,1):(L.setFromMatrixColumn(t,0),L.crossVectors(this.object.up,L)),L.multiplyScalar(e),this._panOffset.add(L)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;L.copy(s).sub(this.target);let i=L.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/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(),s=e-n.left,i=t-n.top,r=n.width,c=n.height;this._mouse.x=s/r*2-1,this._mouse.y=-(i/c)*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(O*this._rotateDelta.x/t.clientHeight),this._rotateUp(O*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),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(O*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(-O*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(O*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(-O*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),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_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),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,i=Math.sqrt(n*n+s*s);this._dollyStart.set(0,i)}_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),s=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(O*this._rotateDelta.x/t.clientHeight),this._rotateUp(O*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),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}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,s=e.pageY-t.y,i=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,i),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,c=(e.pageY+t.y)*.5;this._updateZoomParameters(r,c)}_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 u.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 Ve(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 We(o){this.enabled!==!1&&(o.pointerType==="touch"?this._onTouchMove(o):this._onMouseMove(o))}function Xe(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(ke),this.state=R.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 Ye(o){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 u.MOUSE.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(o),this.state=R.DOLLY;break;case u.MOUSE.ROTATE:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=R.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=R.ROTATE}break;case u.MOUSE.PAN:if(o.ctrlKey||o.metaKey||o.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(o),this.state=R.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(o),this.state=R.PAN}break;default:this.state=R.NONE}this.state!==R.NONE&&this.dispatchEvent(Te)}function qe(o){switch(this.state){case R.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(o);break;case R.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(o);break;case R.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(o);break}}function $e(o){this.enabled===!1||this.enableZoom===!1||this.state!==R.NONE||(o.preventDefault(),this.dispatchEvent(Te),this._handleMouseWheel(this._customWheelEvent(o)),this.dispatchEvent(ke))}function Ze(o){this.enabled!==!1&&this._handleKeyDown(o)}function Qe(o){switch(this._trackPointer(o),this._pointers.length){case 1:switch(this.touches.ONE){case u.TOUCH.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(o),this.state=R.TOUCH_ROTATE;break;case u.TOUCH.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(o),this.state=R.TOUCH_PAN;break;default:this.state=R.NONE}break;case 2:switch(this.touches.TWO){case u.TOUCH.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(o),this.state=R.TOUCH_DOLLY_PAN;break;case u.TOUCH.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(o),this.state=R.TOUCH_DOLLY_ROTATE;break;default:this.state=R.NONE}break;default:this.state=R.NONE}this.state!==R.NONE&&this.dispatchEvent(Te)}function Je(o){switch(this._trackPointer(o),this.state){case R.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(o),this.update();break;case R.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(o),this.update();break;case R.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(o),this.update();break;case R.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(o),this.update();break;default:this.state=R.NONE}}function et(o){this.enabled!==!1&&o.preventDefault()}function tt(o){o.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function st(o){o.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class nt extends Ie{constructor(e,t){super(e,t),this.screenSpacePanning=!1,this.mouseButtons={LEFT:u.MOUSE.PAN,MIDDLE:u.MOUSE.DOLLY,RIGHT:u.MOUSE.ROTATE},this.touches={ONE:u.TOUCH.PAN,TWO:u.TOUCH.DOLLY_ROTATE}}}function Se(o,e){if(e===u.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),o;if(e===u.TriangleFanDrawMode||e===u.TriangleStripDrawMode){let t=o.getIndex();if(t===null){const r=[],c=o.getAttribute("position");if(c!==void 0){for(let a=0;a<c.count;a++)r.push(a);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,s=[];if(e===u.TriangleFanDrawMode)for(let r=1;r<=n;r++)s.push(t.getX(0)),s.push(t.getX(r)),s.push(t.getX(r+1));else for(let r=0;r<n;r++)r%2===0?(s.push(t.getX(r)),s.push(t.getX(r+1)),s.push(t.getX(r+2))):(s.push(t.getX(r+2)),s.push(t.getX(r+1)),s.push(t.getX(r)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=o.clone();return i.setIndex(s),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),o}const ce=new WeakMap;class it extends u.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,s){const i=new u.FileLoader(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{this.parse(r,t,s)},n,s)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,u.SRGBColorSpace,n).catch(n)}decodeDracoFile(e,t,n,s,i=u.LinearSRGBColorSpace,r=()=>{}){const c={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,c).then(t).catch(r)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ce.has(e)){const a=ce.get(e);if(a.key===n)return a.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 s;const i=this.workerNextTaskID++,r=e.byteLength,c=this._getWorker(i,r).then(a=>(s=a,new Promise((l,d)=>{s._callbacks[i]={resolve:l,reject:d},s.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(a=>this._createGeometry(a.geometry));return c.catch(()=>!0).then(()=>{s&&i&&this._releaseTask(s,i)}),ce.set(e,{key:n,promise:c}),c}_createGeometry(e){const t=new u.BufferGeometry;e.index&&t.setIndex(new u.BufferAttribute(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n],i=s.name,r=s.array,c=s.itemSize,a=new u.BufferAttribute(r,c);i==="color"&&(this._assignVertexColorSpace(a,s.vertexColorSpace),a.normalized=!(r instanceof Float32Array)),t.setAttribute(i,a)}return t}_assignVertexColorSpace(e,t){if(t!==u.SRGBColorSpace)return;const n=new u.Color;for(let s=0,i=e.count;s<i;s++)n.fromBufferAttribute(e,s),u.ColorManagement.colorSpaceToWorking(n,u.SRGBColorSpace),e.setXYZ(s,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new u.FileLoader(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((s,i)=>{n.load(e,s,void 0,i)})}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 s=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=rt.toString(),r=["/* draco decoder */",s,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
2
+ `);this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(i){const r=i.data;switch(r.type){case"decode":s._callbacks[r.id].resolve(r);break;case"error":s._callbacks[r.id].reject(r);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+r.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,i){return s._taskLoad>i._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 rt(){let o,e;onmessage=function(r){const c=r.data;switch(c.type){case"init":o=c.decoderConfig,e=new Promise(function(d){o.onModuleLoaded=function(h){d({draco:h})},DracoDecoderModule(o)});break;case"decode":const a=c.buffer,l=c.taskConfig;e.then(d=>{const h=d.draco,m=new h.Decoder;try{const g=t(h,m,new Int8Array(a),l),_=g.attributes.map(b=>b.array.buffer);g.index&&_.push(g.index.array.buffer),self.postMessage({type:"decode",id:c.id,geometry:g},_)}catch(g){console.error(g),self.postMessage({type:"error",id:c.id,error:g.message})}finally{h.destroy(m)}});break}};function t(r,c,a,l){const d=l.attributeIDs,h=l.attributeTypes;let m,g;const _=c.GetEncodedGeometryType(a);if(_===r.TRIANGULAR_MESH)m=new r.Mesh,g=c.DecodeArrayToMesh(a,a.byteLength,m);else if(_===r.POINT_CLOUD)m=new r.PointCloud,g=c.DecodeArrayToPointCloud(a,a.byteLength,m);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!g.ok()||m.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+g.error_msg());const b={index:null,attributes:[]};for(const f in d){const p=self[h[f]];let y,w;if(l.useUniqueIDs)w=d[f],y=c.GetAttributeByUniqueId(m,w);else{if(w=c.GetAttributeId(m,r[d[f]]),w===-1)continue;y=c.GetAttribute(m,w)}const T=s(r,c,m,f,p,y);f==="color"&&(T.vertexColorSpace=l.vertexColorSpace),b.attributes.push(T)}return _===r.TRIANGULAR_MESH&&(b.index=n(r,c,m)),r.destroy(m),b}function n(r,c,a){const d=a.num_faces()*3,h=d*4,m=r._malloc(h);c.GetTrianglesUInt32Array(a,h,m);const g=new Uint32Array(r.HEAPF32.buffer,m,d).slice();return r._free(m),{array:g,itemSize:1}}function s(r,c,a,l,d,h){const m=h.num_components(),_=a.num_points()*m,b=_*d.BYTES_PER_ELEMENT,f=i(r,d),p=r._malloc(b);c.GetAttributeDataArrayForAllPoints(a,h,f,b,p);const y=new d(r.HEAPF32.buffer,p,_).slice();return r._free(p),{name:l,array:y,itemSize:m}}function i(r,c){switch(c){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}}}class ot extends u.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ut(t)}),this.register(function(t){return new dt(t)}),this.register(function(t){return new bt(t)}),this.register(function(t){return new Et(t)}),this.register(function(t){return new St(t)}),this.register(function(t){return new pt(t)}),this.register(function(t){return new mt(t)}),this.register(function(t){return new gt(t)}),this.register(function(t){return new yt(t)}),this.register(function(t){return new ht(t)}),this.register(function(t){return new Tt(t)}),this.register(function(t){return new ft(t)}),this.register(function(t){return new wt(t)}),this.register(function(t){return new _t(t)}),this.register(function(t){return new ct(t)}),this.register(function(t){return new Mt(t)}),this.register(function(t){return new xt(t)})}load(e,t,n,s){const i=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const l=u.LoaderUtils.extractUrlBase(e);r=u.LoaderUtils.resolveURL(l,this.path)}else r=u.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const c=function(l){s?s(l):console.error(l),i.manager.itemError(e),i.manager.itemEnd(e)},a=new u.FileLoader(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(l){try{i.parse(l,r,function(d){t(d),i.manager.itemEnd(e)},c)}catch(d){c(d)}},n,c)}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,s){let i;const r={},c={},a=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(a.decode(new Uint8Array(e,0,4))===Ne){try{r[E.KHR_BINARY_GLTF]=new Rt(e)}catch(h){s&&s(h);return}i=JSON.parse(r[E.KHR_BINARY_GLTF].content)}else i=JSON.parse(a.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new Ut(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](l);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),c[h.name]=h,r[h.name]=!0}if(i.extensionsUsed)for(let d=0;d<i.extensionsUsed.length;++d){const h=i.extensionsUsed[d],m=i.extensionsRequired||[];switch(h){case E.KHR_MATERIALS_UNLIT:r[h]=new lt;break;case E.KHR_DRACO_MESH_COMPRESSION:r[h]=new At(i,this.dracoLoader);break;case E.KHR_TEXTURE_TRANSFORM:r[h]=new Lt;break;case E.KHR_MESH_QUANTIZATION:r[h]=new Ct;break;default:m.indexOf(h)>=0&&c[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}l.setExtensions(r),l.setPlugins(c),l.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,i){n.parse(e,t,s,i)})}}function at(){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 E={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 ct{constructor(e){this.parser=e,this.name=E.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let l;const d=new u.Color(16777215);a.color!==void 0&&d.setRGB(a.color[0],a.color[1],a.color[2],u.LinearSRGBColorSpace);const h=a.range!==void 0?a.range:0;switch(a.type){case"directional":l=new u.DirectionalLight(d),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new u.PointLight(d),l.distance=h;break;case"spot":l=new u.SpotLight(d),l.distance=h,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,l.angle=a.spot.outerConeAngle,l.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return l.position.set(0,0,0),U(l,a),a.intensity!==void 0&&(l.intensity=a.intensity),l.name=t.createUniqueName(a.name||"light_"+e),s=Promise.resolve(l),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],c=(i.extensions&&i.extensions[this.name]||{}).light;return c===void 0?null:this._loadLight(c).then(function(a){return n._getNodeRef(t.cache,c,a)})}}class lt{constructor(){this.name=E.KHR_MATERIALS_UNLIT}getMaterialType(){return u.MeshBasicMaterial}extendParams(e,t,n){const s=[];e.color=new u.Color(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const r=i.baseColorFactor;e.color.setRGB(r[0],r[1],r[2],u.LinearSRGBColorSpace),e.opacity=r[3]}i.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",i.baseColorTexture,u.SRGBColorSpace))}return Promise.all(s)}}class ht{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class ut{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];if(r.clearcoatFactor!==void 0&&(t.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){const c=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new u.Vector2(c,c)}return Promise.all(i)}}class dt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class ft{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return r.iridescenceFactor!==void 0&&(t.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&i.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&&i.push(n.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(i)}}class pt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new u.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const r=s.extensions[this.name];if(r.sheenColorFactor!==void 0){const c=r.sheenColorFactor;t.sheenColor.setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace)}return r.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",r.sheenColorTexture,u.SRGBColorSpace)),r.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(i)}}class mt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return r.transmissionFactor!==void 0&&(t.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(i)}}class gt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];t.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const c=r.attenuationColor||[1,1,1];return t.attenuationColor=new u.Color().setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace),Promise.all(i)}}class yt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class Tt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];t.specularIntensity=r.specularFactor!==void 0?r.specularFactor:1,r.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",r.specularTexture));const c=r.specularColorFactor||[1,1,1];return t.specularColor=new u.Color().setRGB(c[0],c[1],c[2],u.LinearSRGBColorSpace),r.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",r.specularColorTexture,u.SRGBColorSpace)),Promise.all(i)}}class _t{constructor(e){this.parser=e,this.name=E.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return t.bumpScale=r.bumpFactor!==void 0?r.bumpFactor:1,r.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(i)}}class wt{constructor(e){this.parser=e,this.name=E.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:u.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=[],r=s.extensions[this.name];return r.anisotropyStrength!==void 0&&(t.anisotropy=r.anisotropyStrength),r.anisotropyRotation!==void 0&&(t.anisotropyRotation=r.anisotropyRotation),r.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(i)}}class bt{constructor(e){this.parser=e,this.name=E.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const i=s.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,i.source,r)}}class Et{constructor(e){this.parser=e,this.name=E.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,i=s.textures[e];if(!i.extensions||!i.extensions[t])return null;const r=i.extensions[t],c=s.images[r.source];let a=n.textureLoader;if(c.uri){const l=n.options.manager.getHandler(c.uri);l!==null&&(a=l)}return n.loadTextureImage(e,r.source,a)}}class St{constructor(e){this.parser=e,this.name=E.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,i=s.textures[e];if(!i.extensions||!i.extensions[t])return null;const r=i.extensions[t],c=s.images[r.source];let a=n.textureLoader;if(c.uri){const l=n.options.manager.getHandler(c.uri);l!==null&&(a=l)}return n.loadTextureImage(e,r.source,a)}}class Mt{constructor(e){this.name=E.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 s=n.extensions[this.name],i=this.parser.getDependency("buffer",s.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 i.then(function(c){const a=s.byteOffset||0,l=s.byteLength||0,d=s.count,h=s.byteStride,m=new Uint8Array(c,a,l);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(d,h,m,s.mode,s.filter).then(function(g){return g.buffer}):r.ready.then(function(){const g=new ArrayBuffer(d*h);return r.decodeGltfBuffer(new Uint8Array(g),d,h,m,s.mode,s.filter),g})})}else return null}}class xt{constructor(e){this.name=E.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 s=t.meshes[n.mesh];for(const l of s.primitives)if(l.mode!==k.TRIANGLES&&l.mode!==k.TRIANGLE_STRIP&&l.mode!==k.TRIANGLE_FAN&&l.mode!==void 0)return null;const r=n.extensions[this.name].attributes,c=[],a={};for(const l in r)c.push(this.parser.getDependency("accessor",r[l]).then(d=>(a[l]=d,a[l])));return c.length<1?null:(c.push(this.parser.createNodeMesh(e)),Promise.all(c).then(l=>{const d=l.pop(),h=d.isGroup?d.children:[d],m=l[0].count,g=[];for(const _ of h){const b=new u.Matrix4,f=new u.Vector3,p=new u.Quaternion,y=new u.Vector3(1,1,1),w=new u.InstancedMesh(_.geometry,_.material,m);for(let T=0;T<m;T++)a.TRANSLATION&&f.fromBufferAttribute(a.TRANSLATION,T),a.ROTATION&&p.fromBufferAttribute(a.ROTATION,T),a.SCALE&&y.fromBufferAttribute(a.SCALE,T),w.setMatrixAt(T,b.compose(f,p,y));for(const T in a)if(T==="_COLOR_0"){const S=a[T];w.instanceColor=new u.InstancedBufferAttribute(S.array,S.itemSize,S.normalized)}else T!=="TRANSLATION"&&T!=="ROTATION"&&T!=="SCALE"&&_.geometry.setAttribute(T,a[T]);u.Object3D.prototype.copy.call(w,_),this.parser.assignFinalMaterial(w),g.push(w)}return d.isGroup?(d.clear(),d.add(...g),d):g[0]}))}}const Ne="glTF",Z=12,Me={JSON:1313821514,BIN:5130562};class Rt{constructor(e){this.name=E.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Z),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!==Ne)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-Z,i=new DataView(e,Z);let r=0;for(;r<s;){const c=i.getUint32(r,!0);r+=4;const a=i.getUint32(r,!0);if(r+=4,a===Me.JSON){const l=new Uint8Array(e,Z+r,c);this.content=n.decode(l)}else if(a===Me.BIN){const l=Z+r;this.body=e.slice(l,l+c)}r+=c}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class At{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=E.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,i=e.extensions[this.name].bufferView,r=e.extensions[this.name].attributes,c={},a={},l={};for(const d in r){const h=pe[d]||d.toLowerCase();c[h]=r[d]}for(const d in e.attributes){const h=pe[d]||d.toLowerCase();if(r[d]!==void 0){const m=n.accessors[e.attributes[d]],g=Y[m.componentType];l[h]=g.name,a[h]=m.normalized===!0}}return t.getDependency("bufferView",i).then(function(d){return new Promise(function(h,m){s.decodeDracoFile(d,function(g){for(const _ in g.attributes){const b=g.attributes[_],f=a[_];f!==void 0&&(b.normalized=f)}h(g)},c,l,u.LinearSRGBColorSpace,m)})})}}class Lt{constructor(){this.name=E.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 Ct{constructor(){this.name=E.KHR_MESH_QUANTIZATION}}class ve extends u.Interpolant{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,i=e*s*3+s;for(let r=0;r!==s;r++)t[r]=n[i+r];return t}interpolate_(e,t,n,s){const i=this.resultBuffer,r=this.sampleValues,c=this.valueSize,a=c*2,l=c*3,d=s-t,h=(n-t)/d,m=h*h,g=m*h,_=e*l,b=_-l,f=-2*g+3*m,p=g-m,y=1-f,w=p-m+h;for(let T=0;T!==c;T++){const S=r[b+T+c],M=r[b+T+a]*d,A=r[_+T+c],P=r[_+T]*d;i[T]=y*S+w*M+f*A+p*P}return i}}const Pt=new u.Quaternion;class Dt extends ve{interpolate_(e,t,n,s){const i=super.interpolate_(e,t,n,s);return Pt.fromArray(i).normalize().toArray(i),i}}const k={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Y={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},xe={9728:u.NearestFilter,9729:u.LinearFilter,9984:u.NearestMipmapNearestFilter,9985:u.LinearMipmapNearestFilter,9986:u.NearestMipmapLinearFilter,9987:u.LinearMipmapLinearFilter},Re={33071:u.ClampToEdgeWrapping,33648:u.MirroredRepeatWrapping,10497:u.RepeatWrapping},le={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},pe={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"},j={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Ot={CUBICSPLINE:void 0,LINEAR:u.InterpolateLinear,STEP:u.InterpolateDiscrete},he={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function kt(o){return o.DefaultMaterial===void 0&&(o.DefaultMaterial=new u.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:u.FrontSide})),o.DefaultMaterial}function K(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 U(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 It(o,e,t){let n=!1,s=!1,i=!1;for(let l=0,d=e.length;l<d;l++){const h=e[l];if(h.POSITION!==void 0&&(n=!0),h.NORMAL!==void 0&&(s=!0),h.COLOR_0!==void 0&&(i=!0),n&&s&&i)break}if(!n&&!s&&!i)return Promise.resolve(o);const r=[],c=[],a=[];for(let l=0,d=e.length;l<d;l++){const h=e[l];if(n){const m=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):o.attributes.position;r.push(m)}if(s){const m=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):o.attributes.normal;c.push(m)}if(i){const m=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):o.attributes.color;a.push(m)}}return Promise.all([Promise.all(r),Promise.all(c),Promise.all(a)]).then(function(l){const d=l[0],h=l[1],m=l[2];return n&&(o.morphAttributes.position=d),s&&(o.morphAttributes.normal=h),i&&(o.morphAttributes.color=m),o.morphTargetsRelative=!0,o})}function Nt(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,s=t.length;n<s;n++)o.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function vt(o){let e;const t=o.extensions&&o.extensions[E.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ue(t.attributes):e=o.indices+":"+ue(o.attributes)+":"+o.mode,o.targets!==void 0)for(let n=0,s=o.targets.length;n<s;n++)e+=":"+ue(o.targets[n]);return e}function ue(o){let e="";const t=Object.keys(o).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+o[t[n]]+";";return e}function me(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 Ht(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 Ft=new u.Matrix4;class Ut{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new at,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,s=-1,i=!1,r=-1;if(typeof navigator<"u"){const c=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(c)===!0;const a=c.match(/Version\/(\d+)/);s=n&&a?parseInt(a[1],10):-1,i=c.indexOf("Firefox")>-1,r=i?c.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||i&&r<98?this.textureLoader=new u.TextureLoader(this.options.manager):this.textureLoader=new u.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new u.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,s=this.json,i=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 c={scene:r[0][s.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:s.asset,parser:n,userData:{}};return K(i,c,s),U(c,s),Promise.all(n._invokeAll(function(a){return a.afterRoot&&a.afterRoot(c)})).then(function(){for(const a of c.scenes)a.updateMatrixWorld();e(c)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,i=t.length;s<i;s++){const r=t[s].joints;for(let c=0,a=r.length;c<a;c++)e[r[c]].isBone=!0}for(let s=0,i=e.length;s<i;s++){const r=e[s];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 s=n.clone(),i=(r,c)=>{const a=this.associations.get(r);a!=null&&this.associations.set(c,a);for(const[l,d]of r.children.entries())i(d,c.children[l])};return i(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const i=e(t[s]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":s=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(i,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[E.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(i,r){n.load(u.LoaderUtils.resolveURL(t.uri,s.path),i,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 s=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const r=le[s.type],c=Y[s.componentType],a=s.normalized===!0,l=new c(s.count*r);return Promise.resolve(new u.BufferAttribute(l,r,a))}const i=[];return s.bufferView!==void 0?i.push(this.getDependency("bufferView",s.bufferView)):i.push(null),s.sparse!==void 0&&(i.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(i).then(function(r){const c=r[0],a=le[s.type],l=Y[s.componentType],d=l.BYTES_PER_ELEMENT,h=d*a,m=s.byteOffset||0,g=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,_=s.normalized===!0;let b,f;if(g&&g!==h){const p=Math.floor(m/g),y="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+p+":"+s.count;let w=t.cache.get(y);w||(b=new l(c,p*g,s.count*g/d),w=new u.InterleavedBuffer(b,g/d),t.cache.add(y,w)),f=new u.InterleavedBufferAttribute(w,a,m%g/d,_)}else c===null?b=new l(s.count*a):b=new l(c,m,s.count*a),f=new u.BufferAttribute(b,a,_);if(s.sparse!==void 0){const p=le.SCALAR,y=Y[s.sparse.indices.componentType],w=s.sparse.indices.byteOffset||0,T=s.sparse.values.byteOffset||0,S=new y(r[1],w,s.sparse.count*p),M=new l(r[2],T,s.sparse.count*a);c!==null&&(f=new u.BufferAttribute(f.array.slice(),f.itemSize,f.normalized)),f.normalized=!1;for(let A=0,P=S.length;A<P;A++){const D=S[A];if(f.setX(D,M[A*a]),a>=2&&f.setY(D,M[A*a+1]),a>=3&&f.setZ(D,M[A*a+2]),a>=4&&f.setW(D,M[A*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}f.normalized=_}return f})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,r=t.images[i];let c=this.textureLoader;if(r.uri){const a=n.manager.getHandler(r.uri);a!==null&&(c=a)}return this.loadTextureImage(e,i,c)}loadTextureImage(e,t,n){const s=this,i=this.json,r=i.textures[e],c=i.images[t],a=(c.uri||c.bufferView)+":"+r.sampler;if(this.textureCache[a])return this.textureCache[a];const l=this.loadImageSource(t,n).then(function(d){d.flipY=!1,d.name=r.name||c.name||"",d.name===""&&typeof c.uri=="string"&&c.uri.startsWith("data:image/")===!1&&(d.name=c.uri);const m=(i.samplers||{})[r.sampler]||{};return d.magFilter=xe[m.magFilter]||u.LinearFilter,d.minFilter=xe[m.minFilter]||u.LinearMipmapLinearFilter,d.wrapS=Re[m.wrapS]||u.RepeatWrapping,d.wrapT=Re[m.wrapT]||u.RepeatWrapping,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==u.NearestFilter&&d.minFilter!==u.LinearFilter,s.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[a]=l,l}loadImageSource(e,t){const n=this,s=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const r=s.images[e],c=self.URL||self.webkitURL;let a=r.uri||"",l=!1;if(r.bufferView!==void 0)a=n.getDependency("bufferView",r.bufferView).then(function(h){l=!0;const m=new Blob([h],{type:r.mimeType});return a=c.createObjectURL(m),a});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(a).then(function(h){return new Promise(function(m,g){let _=m;t.isImageBitmapLoader===!0&&(_=function(b){const f=new u.Texture(b);f.needsUpdate=!0,m(f)}),t.load(u.LoaderUtils.resolveURL(h,i.path),_,void 0,g)})}).then(function(h){return l===!0&&c.revokeObjectURL(a),U(h,r),h.userData.mimeType=r.mimeType||Ht(r.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),h});return this.sourceCache[e]=d,d}assignTexture(e,t,n,s){const i=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),i.extensions[E.KHR_TEXTURE_TRANSFORM]){const c=n.extensions!==void 0?n.extensions[E.KHR_TEXTURE_TRANSFORM]:void 0;if(c){const a=i.associations.get(r);r=i.extensions[E.KHR_TEXTURE_TRANSFORM].extendTexture(r,c),i.associations.set(r,a)}}return s!==void 0&&(r.colorSpace=s),e[t]=r,r})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,r=t.attributes.normal===void 0;if(e.isPoints){const c="PointsMaterial:"+n.uuid;let a=this.cache.get(c);a||(a=new u.PointsMaterial,u.Material.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,a.sizeAttenuation=!1,this.cache.add(c,a)),n=a}else if(e.isLine){const c="LineBasicMaterial:"+n.uuid;let a=this.cache.get(c);a||(a=new u.LineBasicMaterial,u.Material.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,this.cache.add(c,a)),n=a}if(s||i||r){let c="ClonedMaterial:"+n.uuid+":";s&&(c+="derivative-tangents:"),i&&(c+="vertex-colors:"),r&&(c+="flat-shading:");let a=this.cache.get(c);a||(a=n.clone(),i&&(a.vertexColors=!0),r&&(a.flatShading=!0),s&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(c,a),this.associations.set(a,this.associations.get(n))),n=a}e.material=n}getMaterialType(){return u.MeshStandardMaterial}loadMaterial(e){const t=this,n=this.json,s=this.extensions,i=n.materials[e];let r;const c={},a=i.extensions||{},l=[];if(a[E.KHR_MATERIALS_UNLIT]){const h=s[E.KHR_MATERIALS_UNLIT];r=h.getMaterialType(),l.push(h.extendParams(c,i,t))}else{const h=i.pbrMetallicRoughness||{};if(c.color=new u.Color(1,1,1),c.opacity=1,Array.isArray(h.baseColorFactor)){const m=h.baseColorFactor;c.color.setRGB(m[0],m[1],m[2],u.LinearSRGBColorSpace),c.opacity=m[3]}h.baseColorTexture!==void 0&&l.push(t.assignTexture(c,"map",h.baseColorTexture,u.SRGBColorSpace)),c.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,c.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(c,"metalnessMap",h.metallicRoughnessTexture)),l.push(t.assignTexture(c,"roughnessMap",h.metallicRoughnessTexture))),r=this._invokeOne(function(m){return m.getMaterialType&&m.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(m){return m.extendMaterialParams&&m.extendMaterialParams(e,c)})))}i.doubleSided===!0&&(c.side=u.DoubleSide);const d=i.alphaMode||he.OPAQUE;if(d===he.BLEND?(c.transparent=!0,c.depthWrite=!1):(c.transparent=!1,d===he.MASK&&(c.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&r!==u.MeshBasicMaterial&&(l.push(t.assignTexture(c,"normalMap",i.normalTexture)),c.normalScale=new u.Vector2(1,1),i.normalTexture.scale!==void 0)){const h=i.normalTexture.scale;c.normalScale.set(h,h)}if(i.occlusionTexture!==void 0&&r!==u.MeshBasicMaterial&&(l.push(t.assignTexture(c,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(c.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&r!==u.MeshBasicMaterial){const h=i.emissiveFactor;c.emissive=new u.Color().setRGB(h[0],h[1],h[2],u.LinearSRGBColorSpace)}return i.emissiveTexture!==void 0&&r!==u.MeshBasicMaterial&&l.push(t.assignTexture(c,"emissiveMap",i.emissiveTexture,u.SRGBColorSpace)),Promise.all(l).then(function(){const h=new r(c);return i.name&&(h.name=i.name),U(h,i),t.associations.set(h,{materials:e}),i.extensions&&K(s,h,i),h})}createUniqueName(e){const t=u.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,s=this.primitiveCache;function i(c){return n[E.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(c,t).then(function(a){return Ae(a,c,t)})}const r=[];for(let c=0,a=e.length;c<a;c++){const l=e[c],d=vt(l),h=s[d];if(h)r.push(h.promise);else{let m;l.extensions&&l.extensions[E.KHR_DRACO_MESH_COMPRESSION]?m=i(l):m=Ae(new u.BufferGeometry,l,t),s[d]={primitive:l,promise:m},r.push(m)}}return Promise.all(r)}loadMesh(e){const t=this,n=this.json,s=this.extensions,i=n.meshes[e],r=i.primitives,c=[];for(let a=0,l=r.length;a<l;a++){const d=r[a].material===void 0?kt(this.cache):this.getDependency("material",r[a].material);c.push(d)}return c.push(t.loadGeometries(r)),Promise.all(c).then(function(a){const l=a.slice(0,a.length-1),d=a[a.length-1],h=[];for(let g=0,_=d.length;g<_;g++){const b=d[g],f=r[g];let p;const y=l[g];if(f.mode===k.TRIANGLES||f.mode===k.TRIANGLE_STRIP||f.mode===k.TRIANGLE_FAN||f.mode===void 0)p=i.isSkinnedMesh===!0?new u.SkinnedMesh(b,y):new u.Mesh(b,y),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),f.mode===k.TRIANGLE_STRIP?p.geometry=Se(p.geometry,u.TriangleStripDrawMode):f.mode===k.TRIANGLE_FAN&&(p.geometry=Se(p.geometry,u.TriangleFanDrawMode));else if(f.mode===k.LINES)p=new u.LineSegments(b,y);else if(f.mode===k.LINE_STRIP)p=new u.Line(b,y);else if(f.mode===k.LINE_LOOP)p=new u.LineLoop(b,y);else if(f.mode===k.POINTS)p=new u.Points(b,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+f.mode);Object.keys(p.geometry.morphAttributes).length>0&&Nt(p,i),p.name=t.createUniqueName(i.name||"mesh_"+e),U(p,i),f.extensions&&K(s,p,f),t.assignFinalMaterial(p),h.push(p)}for(let g=0,_=h.length;g<_;g++)t.associations.set(h[g],{meshes:e,primitives:g});if(h.length===1)return i.extensions&&K(s,h[0],i),h[0];const m=new u.Group;i.extensions&&K(s,m,i),t.associations.set(m,{meshes:e});for(let g=0,_=h.length;g<_;g++)m.add(h[g]);return m})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new u.PerspectiveCamera(u.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new u.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),U(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,i=t.joints.length;s<i;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const i=s.pop(),r=s,c=[],a=[];for(let l=0,d=r.length;l<d;l++){const h=r[l];if(h){c.push(h);const m=new u.Matrix4;i!==null&&m.fromArray(i.array,l*16),a.push(m)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new u.Skeleton(c,a)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],i=s.name?s.name:"animation_"+e,r=[],c=[],a=[],l=[],d=[];for(let h=0,m=s.channels.length;h<m;h++){const g=s.channels[h],_=s.samplers[g.sampler],b=g.target,f=b.node,p=s.parameters!==void 0?s.parameters[_.input]:_.input,y=s.parameters!==void 0?s.parameters[_.output]:_.output;b.node!==void 0&&(r.push(this.getDependency("node",f)),c.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",y)),l.push(_),d.push(b))}return Promise.all([Promise.all(r),Promise.all(c),Promise.all(a),Promise.all(l),Promise.all(d)]).then(function(h){const m=h[0],g=h[1],_=h[2],b=h[3],f=h[4],p=[];for(let y=0,w=m.length;y<w;y++){const T=m[y],S=g[y],M=_[y],A=b[y],P=f[y];if(T===void 0)continue;T.updateMatrix&&T.updateMatrix();const D=n._createAnimationTracks(T,S,M,A,P);if(D)for(let G=0;G<D.length;G++)p.push(D[G])}return new u.AnimationClip(i,void 0,p)})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(i){const r=n._getNodeRef(n.meshCache,s.mesh,i);return s.weights!==void 0&&r.traverse(function(c){if(c.isMesh)for(let a=0,l=s.weights.length;a<l;a++)c.morphTargetInfluences[a]=s.weights[a]}),r})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],i=n._loadNodeShallow(e),r=[],c=s.children||[];for(let l=0,d=c.length;l<d;l++)r.push(n.getDependency("node",c[l]));const a=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([i,Promise.all(r),a]).then(function(l){const d=l[0],h=l[1],m=l[2];m!==null&&d.traverse(function(g){g.isSkinnedMesh&&g.bind(m,Ft)});for(let g=0,_=h.length;g<_;g++)d.add(h[g]);return d})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],r=i.name?s.createUniqueName(i.name):"",c=[],a=s._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return a&&c.push(a),i.camera!==void 0&&c.push(s.getDependency("camera",i.camera).then(function(l){return s._getNodeRef(s.cameraCache,i.camera,l)})),s._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){c.push(l)}),this.nodeCache[e]=Promise.all(c).then(function(l){let d;if(i.isBone===!0?d=new u.Bone:l.length>1?d=new u.Group:l.length===1?d=l[0]:d=new u.Object3D,d!==l[0])for(let h=0,m=l.length;h<m;h++)d.add(l[h]);if(i.name&&(d.userData.name=i.name,d.name=r),U(d,i),i.extensions&&K(n,d,i),i.matrix!==void 0){const h=new u.Matrix4;h.fromArray(i.matrix),d.applyMatrix4(h)}else i.translation!==void 0&&d.position.fromArray(i.translation),i.rotation!==void 0&&d.quaternion.fromArray(i.rotation),i.scale!==void 0&&d.scale.fromArray(i.scale);if(!s.associations.has(d))s.associations.set(d,{});else if(i.mesh!==void 0&&s.meshCache.refs[i.mesh]>1){const h=s.associations.get(d);s.associations.set(d,{...h})}return s.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,i=new u.Group;n.name&&(i.name=s.createUniqueName(n.name)),U(i,n),n.extensions&&K(t,i,n);const r=n.nodes||[],c=[];for(let a=0,l=r.length;a<l;a++)c.push(s.getDependency("node",r[a]));return Promise.all(c).then(function(a){for(let d=0,h=a.length;d<h;d++)i.add(a[d]);const l=d=>{const h=new Map;for(const[m,g]of s.associations)(m instanceof u.Material||m instanceof u.Texture)&&h.set(m,g);return d.traverse(m=>{const g=s.associations.get(m);g!=null&&h.set(m,g)}),h};return s.associations=l(i),i})}_createAnimationTracks(e,t,n,s,i){const r=[],c=e.name?e.name:e.uuid,a=[];j[i.path]===j.weights?e.traverse(function(m){m.morphTargetInfluences&&a.push(m.name?m.name:m.uuid)}):a.push(c);let l;switch(j[i.path]){case j.weights:l=u.NumberKeyframeTrack;break;case j.rotation:l=u.QuaternionKeyframeTrack;break;case j.translation:case j.scale:l=u.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:l=u.NumberKeyframeTrack;break;case 2:case 3:default:l=u.VectorKeyframeTrack;break}break}const d=s.interpolation!==void 0?Ot[s.interpolation]:u.InterpolateLinear,h=this._getArrayFromAccessor(n);for(let m=0,g=a.length;m<g;m++){const _=new l(a[m]+"."+j[i.path],t.array,h,d);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(_),r.push(_)}return r}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=me(t.constructor),s=new Float32Array(t.length);for(let i=0,r=t.length;i<r;i++)s[i]=t[i]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof u.QuaternionKeyframeTrack?Dt:ve;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Gt(o,e,t){const n=e.attributes,s=new u.Box3;if(n.POSITION!==void 0){const c=t.json.accessors[n.POSITION],a=c.min,l=c.max;if(a!==void 0&&l!==void 0){if(s.set(new u.Vector3(a[0],a[1],a[2]),new u.Vector3(l[0],l[1],l[2])),c.normalized){const d=me(Y[c.componentType]);s.min.multiplyScalar(d),s.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const c=new u.Vector3,a=new u.Vector3;for(let l=0,d=i.length;l<d;l++){const h=i[l];if(h.POSITION!==void 0){const m=t.json.accessors[h.POSITION],g=m.min,_=m.max;if(g!==void 0&&_!==void 0){if(a.setX(Math.max(Math.abs(g[0]),Math.abs(_[0]))),a.setY(Math.max(Math.abs(g[1]),Math.abs(_[1]))),a.setZ(Math.max(Math.abs(g[2]),Math.abs(_[2]))),m.normalized){const b=me(Y[m.componentType]);a.multiplyScalar(b)}c.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(c)}o.boundingBox=s;const r=new u.Sphere;s.getCenter(r.center),r.radius=s.min.distanceTo(s.max)/2,o.boundingSphere=r}function Ae(o,e,t){const n=e.attributes,s=[];function i(r,c){return t.getDependency("accessor",r).then(function(a){o.setAttribute(c,a)})}for(const r in n){const c=pe[r]||r.toLowerCase();c in o.attributes||s.push(i(n[r],c))}if(e.indices!==void 0&&!o.index){const r=t.getDependency("accessor",e.indices).then(function(c){o.setIndex(c)});s.push(r)}return u.ColorManagement.workingColorSpace!==u.LinearSRGBColorSpace&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${u.ColorManagement.workingColorSpace}" not supported.`),U(o,e),Gt(o,e,t),Promise.all(s).then(function(){return e.targets!==void 0?It(o,e.targets,t):o})}const Le=new u.Vector3,jt=new u.Quaternion,Ce=new u.Vector3;class Bt extends u.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS3DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.addEventListener("removed",function(){this.traverse(function(t){t.element instanceof t.element.ownerDocument.defaultView.Element&&t.element.parentNode!==null&&t.element.remove()})})}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this}}class zt extends Bt{constructor(e){super(e),this.isCSS3DSprite=!0,this.rotation2D=0}copy(e,t){return super.copy(e,t),this.rotation2D=e.rotation2D,this}}const H=new u.Matrix4,Kt=new u.Matrix4;class Vt{constructor(e={}){const t=this;let n,s,i,r;const c={camera:{style:""},objects:new WeakMap},a=e.element!==void 0?e.element:document.createElement("div");a.style.overflow="hidden",this.domElement=a;const l=document.createElement("div");l.style.transformOrigin="0 0",l.style.pointerEvents="none",a.appendChild(l);const d=document.createElement("div");d.style.transformStyle="preserve-3d",l.appendChild(d),this.getSize=function(){return{width:n,height:s}},this.render=function(f,p){const y=p.projectionMatrix.elements[5]*r;p.view&&p.view.enabled?(l.style.transform=`translate( ${-p.view.offsetX*(n/p.view.width)}px, ${-p.view.offsetY*(s/p.view.height)}px )`,l.style.transform+=`scale( ${p.view.fullWidth/p.view.width}, ${p.view.fullHeight/p.view.height} )`):l.style.transform="",f.matrixWorldAutoUpdate===!0&&f.updateMatrixWorld(),p.parent===null&&p.matrixWorldAutoUpdate===!0&&p.updateMatrixWorld();let w,T;p.isOrthographicCamera&&(w=-(p.right+p.left)/2,T=(p.top+p.bottom)/2);const S=p.view&&p.view.enabled?p.view.height/p.view.fullHeight:1,M=p.isOrthographicCamera?`scale( ${S} )scale(`+y+")translate("+h(w)+"px,"+h(T)+"px)"+m(p.matrixWorldInverse):`scale( ${S} )translateZ(`+y+"px)"+m(p.matrixWorldInverse),P=(p.isPerspectiveCamera?"perspective("+y+"px) ":"")+M+"translate("+i+"px,"+r+"px)";c.camera.style!==P&&(d.style.transform=P,c.camera.style=P),b(f,f,p)},this.setSize=function(f,p){n=f,s=p,i=n/2,r=s/2,a.style.width=f+"px",a.style.height=p+"px",l.style.width=f+"px",l.style.height=p+"px",d.style.width=f+"px",d.style.height=p+"px"};function h(f){return Math.abs(f)<1e-10?0:f}function m(f){const p=f.elements;return"matrix3d("+h(p[0])+","+h(-p[1])+","+h(p[2])+","+h(p[3])+","+h(p[4])+","+h(-p[5])+","+h(p[6])+","+h(p[7])+","+h(p[8])+","+h(-p[9])+","+h(p[10])+","+h(p[11])+","+h(p[12])+","+h(-p[13])+","+h(p[14])+","+h(p[15])+")"}function g(f){const p=f.elements;return"translate(-50%,-50%)"+("matrix3d("+h(p[0])+","+h(p[1])+","+h(p[2])+","+h(p[3])+","+h(-p[4])+","+h(-p[5])+","+h(-p[6])+","+h(-p[7])+","+h(p[8])+","+h(p[9])+","+h(p[10])+","+h(p[11])+","+h(p[12])+","+h(p[13])+","+h(p[14])+","+h(p[15])+")")}function _(f){f.isCSS3DObject&&(f.element.style.display="none");for(let p=0,y=f.children.length;p<y;p++)_(f.children[p])}function b(f,p,y,w){if(f.visible===!1){_(f);return}if(f.isCSS3DObject){const T=f.layers.test(y.layers)===!0,S=f.element;if(S.style.display=T===!0?"":"none",T===!0){f.onBeforeRender(t,p,y);let M;f.isCSS3DSprite?(H.copy(y.matrixWorldInverse),H.transpose(),f.rotation2D!==0&&H.multiply(Kt.makeRotationZ(f.rotation2D)),f.matrixWorld.decompose(Le,jt,Ce),H.setPosition(Le),H.scale(Ce),H.elements[3]=0,H.elements[7]=0,H.elements[11]=0,H.elements[15]=1,M=g(H)):M=g(f.matrixWorld);const A=c.objects.get(f);if(A===void 0||A.style!==M){S.style.transform=M;const P={style:M};c.objects.set(f,P)}S.parentNode!==d&&d.appendChild(S),f.onAfterRender(t,p,y)}}for(let T=0,S=f.children.length;T<S;T++)b(f.children[T],p,y)}}}var q=function(){var o=0,e=document.createElement("div");e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",function(d){d.preventDefault(),n(++o%e.children.length)},!1);function t(d){return e.appendChild(d.dom),d}function n(d){for(var h=0;h<e.children.length;h++)e.children[h].style.display=h===d?"block":"none";o=d}var s=(performance||Date).now(),i=s,r=0,c=t(new q.Panel("FPS","#0ff","#002")),a=t(new q.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var l=t(new q.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:e,addPanel:t,showPanel:n,begin:function(){s=(performance||Date).now()},end:function(){r++;var d=(performance||Date).now();if(a.update(d-s,200),d>=i+1e3&&(c.update(r*1e3/(d-i),100),i=d,r=0,l)){var h=performance.memory;l.update(h.usedJSHeapSize/1048576,h.jsHeapSizeLimit/1048576)}return d},update:function(){s=this.end()},domElement:e,setMode:n}};q.Panel=function(o,e,t){var n=1/0,s=0,i=Math.round,r=i(window.devicePixelRatio||1),c=80*r,a=48*r,l=3*r,d=2*r,h=3*r,m=15*r,g=74*r,_=30*r,b=document.createElement("canvas");b.width=c,b.height=a,b.style.cssText="width:80px;height:48px";var f=b.getContext("2d");return f.font="bold "+9*r+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=t,f.fillRect(0,0,c,a),f.fillStyle=e,f.fillText(o,l,d),f.fillRect(h,m,g,_),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(h,m,g,_),{dom:b,update:function(p,y){n=Math.min(n,p),s=Math.max(s,p),f.fillStyle=t,f.globalAlpha=1,f.fillRect(0,0,c,m),f.fillStyle=e,f.fillText(i(p)+" "+o+" ("+i(n)+"-"+i(s)+")",l,d),f.drawImage(b,h+r,m,g-r,_,h,m,g-r,_),f.fillRect(h+g-r,m,r,_),f.fillStyle=t,f.globalAlpha=.9,f.fillRect(h+g-r,m,r,i((1-p/y)*_))}}};function Wt(o){return new u.CameraHelper(o)}function Xt(o=150,...e){return new u.GridHelper(o,o/10,...e)}function Yt(o){return new u.BoxHelper(o,16776960)}function qt(o,e){return new Ie(o,e)}function $t(o,e){return new nt(o,e)}function Zt(){const o=new u.Raycaster,e=new u.Vector2(0,0);return{raycaster:o,pointer:e}}function Qt(o=10){return new u.AxesHelper(o)}function Jt(o=new u.Vector3(1,1,1),e=new u.Vector3(10,10,10),t=5,n=16776960){return o.normalize(),new u.ArrowHelper(o,e,t,n)}function es(){const o=new q;return o.dom.style.cssText="position:absolute;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",o}const He=o=>{o.geometry&&o.geometry.dispose(),o.material&&(Array.isArray(o.material)?o.material.forEach(e=>{Pe(e)}):Pe(o.material)),o.children&&o.children.forEach(e=>He(e))};function Pe(o){for(const e in o)o[e]&&o[e].isTexture&&o[e].dispose();o.dispose()}const de={};async function ts(o,e=50){const t={type:o.type,name:o.name,position:o.position.toArray(),rotation:o.rotation.toArray(),scale:o.scale.toArray(),visible:o.visible,children:[],geometry:null,material:null,userData:o.userData};o.isMesh&&(t.geometry=se(o.geometry),t.material=ie(o.material));const n=[{object:o,parentData:t}];let s=0;for(;n.length>0;){const{object:i,parentData:r}=n.pop();for(const c of i.children){const a={type:c.type,name:c.name,position:c.position.toArray(),rotation:c.rotation.toArray(),scale:c.scale.toArray(),visible:c.visible,children:[],geometry:null,material:null,userData:c.userData};c.isMesh&&(a.geometry=se(c.geometry),a.material=ie(c.material)),r.children.push(a),n.push({object:c,parentData:a}),s++,s%e===0&&await new Promise(l=>requestAnimationFrame(l))}}return t}function ss(o){const e={type:o.type,name:o.name,position:o.position.toArray(),rotation:o.rotation.toArray(),scale:o.scale.toArray(),visible:o.visible,children:[],geometry:null,material:null,userData:o.userData};o.isMesh&&(e.geometry=se(o.geometry),e.material=ie(o.material));const t=[{object:o,parentData:e}];for(;t.length>0;){const{object:n,parentData:s}=t.pop();for(const i of n.children){const r={type:i.type,name:i.name,position:i.position.toArray(),rotation:i.rotation.toArray(),scale:i.scale.toArray(),visible:i.visible,children:[],geometry:null,material:null,userData:i.userData};i.isMesh&&(r.geometry=se(i.geometry),r.material=ie(i.material)),s.children.push(r),t.push({object:i,parentData:r})}}return e}async function Fe(o,e=50){const t=[];let n;switch(o.type){case"Mesh":const i=ne(o.geometry),r=re(o.material);n=new x.Mesh(i,r);break;case"Group":n=new x.Group;break;case"Object3D":n=new x.Object3D;break;default:return console.warn(`Unsupported object type: ${o.type}`),null}n.name=o.name,n.position.fromArray(o.position),n.rotation.fromArray(o.rotation),n.scale.fromArray(o.scale),n.visible=o.visible,n.userData=o.userData,t.push({data:o,object:n});let s=0;for(;t.length>0;){const{data:i,object:r}=t.pop();for(const c of[...i.children].reverse()){let a;switch(c.type){case"Mesh":const l=ne(c.geometry),d=re(c.material);a=new x.Mesh(l,d);break;case"Group":a=new x.Group;break;case"Object3D":a=new x.Object3D;break;default:console.warn(`Unsupported object type: ${c.type}`);continue}a&&(a.name=c.name,a.position.fromArray(c.position),a.rotation.fromArray(c.rotation),a.scale.fromArray(c.scale),a.visible=c.visible,a.userData=c.userData,r.add(a),t.push({data:c,object:a}),s++,s%e===0&&await new Promise(l=>requestAnimationFrame(l)))}}return n}function ns(o){const e=[];let t;switch(o.type){case"Mesh":const n=ne(o.geometry),s=re(o.material);t=new x.Mesh(n,s);break;case"Group":t=new x.Group;break;case"Object3D":t=new x.Object3D;break;default:return console.warn(`Unsupported object type: ${o.type}`),null}for(t.name=o.name,t.position.fromArray(o.position),t.rotation.fromArray(o.rotation),t.scale.fromArray(o.scale),t.visible=o.visible,t.userData=o.userData,e.push({data:o,object:t});e.length>0;){const{data:n,object:s}=e.pop();for(const i of[...n.children].reverse()){let r;switch(i.type){case"Mesh":const c=ne(i.geometry),a=re(i.material);r=new x.Mesh(c,a);break;case"Group":r=new x.Group;break;case"Object3D":r=new x.Object3D;break;default:console.warn(`Unsupported object type: ${i.type}`);continue}r&&(r.name=i.name,r.position.fromArray(i.position),r.rotation.fromArray(i.rotation),r.scale.fromArray(i.scale),r.visible=i.visible,r.userData=i.userData,s.add(r),e.push({data:i,object:r}))}}return t}function se(o){const e={},{attributes:t,index:n,type:s}=o;t.position&&(e.position={type:"Float32Array",array:Array.from(t.position.array),itemSize:3}),t.normal&&(e.normal={type:"Float32Array",array:Array.from(t.normal.array),itemSize:3}),t.uv&&(e.uv={type:"Float32Array",array:Array.from(t.uv.array),itemSize:2});const i={type:s,attributes:e};return n&&n.array&&(i.index={type:"Uint32Array",array:Array.from(n.array),itemSize:1}),i}function ne(o){const{type:e,attributes:t,index:n}=o,s=new x.BufferGeometry;for(const i in t)if(t.hasOwnProperty(i)){const{type:r,array:c,itemSize:a}=t[i];s.setAttribute(i,new x.BufferAttribute(new Float32Array(c),a))}return n&&s.setIndex(n.array),s}function ie(o){return{type:o.type,color:o.color.getHex(),map:o.map?o.map.image.src:null,opacity:o.opacity,name:o.name,depthTest:o.depthTest,depthWrite:o.depthWrite,transparent:o.transparent,side:o.side,roughness:o.roughness,metalness:o.metalness,emissive:o.emissive.getHex()}}function re(o){if(de[o.name])return de[o.name];const{type:e,...t}=o,n=e||"MeshStandardMaterial",s=new x[n]({...t});if(o.map){const i=new x.TextureLoader().load(o.map);s.map=i}return s.needsUpdate=!0,de[o.name]=s,s}class Ue{constructor(){this.stats={hits:0,misses:0,totalLoadTime:0,cacheSaveTime:0,errors:0},this.loadHistory=[]}recordHit(e){this.stats.hits++,this.stats.totalLoadTime+=e,this._recordHistory("hit",e)}recordMiss(e){this.stats.misses++,this.stats.totalLoadTime+=e,this._recordHistory("miss",e)}recordCacheSave(e){this.stats.cacheSaveTime+=e}recordError(e,t){this.stats.errors++,this._recordHistory("error",0,{path:e,error:t.message})}getHitRate(){const e=this.stats.hits+this.stats.misses;return e>0?(this.stats.hits/e*100).toFixed(2)+"%":"0%"}getAvgLoadTime(){const e=this.stats.hits+this.stats.misses;return e>0?(this.stats.totalLoadTime/e).toFixed(2)+"ms":"0ms"}getStats(){const e=this.stats.hits+this.stats.misses;return{命中率:this.getHitRate(),平均加载时间:this.getAvgLoadTime(),缓存命中数:this.stats.hits,缓存未命中数:this.stats.misses,总加载次数:e,总加载时间:this.stats.totalLoadTime.toFixed(2)+"ms",缓存保存时间:this.stats.cacheSaveTime.toFixed(2)+"ms",错误次数:this.stats.errors}}getHistory(e=10){return this.loadHistory.slice(-e)}reset(){this.stats={hits:0,misses:0,totalLoadTime:0,cacheSaveTime:0,errors:0},this.loadHistory=[]}_recordHistory(e,t,n={}){this.loadHistory.push({type:e,duration:t,timestamp:Date.now(),...n}),this.loadHistory.length>100&&this.loadHistory.shift()}logReport(){console.group("📊 缓存性能报告");const e=this.getStats();Object.entries(e).forEach(([t,n])=>{console.log(`${t}: ${n}`)}),console.groupEnd()}}const F=new Ue;class Q{static async retry(e,t={}){const{maxRetries:n=3,initialDelay:s=1e3,maxDelay:i=1e4,backoffFactor:r=2,shouldRetry:c=Q.defaultShouldRetry}=t;let a,l=s;for(let d=0;d<=n;d++)try{return await e()}catch(h){if(a=h,d===n||!c(h,d))throw h;console.warn(`[ RetryHelper ] 操作失败,第 ${d+1} 次尝试失败,${l}ms 后进行第 ${d+2} 次尝试...`,h),await Q.delay(l),l=Math.min(l*r,i)}throw a}static defaultShouldRetry(e,t){if(e.name==="TypeError"&&e.message.includes("fetch"))return!0;if(e.message.includes("HTTP error")){const n=e.message.match(/status:\s*(\d+)/);if(n){const s=parseInt(n[1],10);return s>=500||s===429||s===408}}return!1}static delay(e){return new Promise(t=>setTimeout(t,e))}}const te={NETWORK:"NETWORK",PARSE:"PARSE",VERSION_MISMATCH:"VERSION",UNKNOWN:"UNKNOWN"};class $ extends Error{constructor(e,t,n,s){super(e),this.name="ModelLoadError",this.type=t,this.path=n,this.originalError=s,this.timestamp=Date.now()}static networkError(e,t){return new $(`网络加载失败: ${e}`,te.NETWORK,e,t)}static parseError(e,t){return new $(`模型解析失败: ${e}`,te.PARSE,e,t)}static versionMismatchError(e,t,n){return new $(`版本不匹配: ${e} (期望: ${t}, 实际: ${n})`,te.VERSION_MISMATCH,e)}}const De=4;class ge{constructor(e="threeJsIDBCache",t={}){this.version=De,this.dbName=e,this.options={maxSize:t.maxSize||500*1024*1024,maxEntries:t.maxEntries||50,evictRatio:t.evictRatio||.2},this.dbInit()}dbInit(){this.db=new Be(this.dbName),this.db.version(this.version).stores({models:"&path, version, timestamp, accessCount, size"}).upgrade(async e=>{console.log("[ IDBCache 版本更新 ] ====> version",De);const t=e.table("models"),n=await t.toArray();for(const s of n)s.data instanceof ArrayBuffer||await t.delete(s.path)})}getDatabase(){return this.db}async saveModel(e,t,n){await this.ensureCapacity(n.byteLength),await this.db.table("models").put({path:e,version:t,data:n,size:n.byteLength,timestamp:Date.now(),accessCount:0})}async ensureCapacity(e){const t=await this.db.table("models").toArray(),n=t.reduce((c,a)=>c+(a.size||0),0),s=t.length,i=n+e>this.options.maxSize,r=s>=this.options.maxEntries;(i||r)&&(console.log(`[ IDBCache ] ====> 容量不足,开始 LRU 淘汰. 总大小: ${(n/1024/1024).toFixed(2)}MB, 条目数: ${s}`),await this.evictLRU(t))}async evictLRU(e){const t=e.sort((c,a)=>(c.accessCount||0)!==(a.accessCount||0)?(c.accessCount||0)-(a.accessCount||0):(c.timestamp||0)-(a.timestamp||0)),n=Math.max(1,Math.floor(t.length*this.options.evictRatio)),s=t.slice(0,n),i=s.map(c=>c.path);await this.db.table("models").bulkDelete(i);const r=s.reduce((c,a)=>c+(a.size||0),0);console.log(`[ IDBCache ] ====> LRU 淘汰完成. 删除 ${n} 个条目,释放 ${(r/1024/1024).toFixed(2)}MB`)}async getModel(e,t){const n=await this.db.table("models").get(e);return n?n.version!==t?(console.log("模型版本不一致, 清除当前记录"),await this.db.table("models").delete(e),null):(await this.db.table("models").update(e,{accessCount:(n.accessCount||0)+1,timestamp:Date.now()}),n.data):(console.warn(`Model "${e}" not found in table models`),null)}async cacheModel(e,t,n){console.log("[ ] ====> path, modelData, version",e,t,n);try{this.db.table("models").put({version:n,path:e,data:t}).then(()=>{console.log(`Model "${e}" cached successfully in table models`)})}catch{console.log(" 缓存模型失败 =====> ")}return t}async loadCachedModel(e,t){let n=null;try{if(n=await this.db.table("models").get(e),!n)return console.warn(`Model "${t}" not found in table models`),null;if(n.version!==t)return console.log(" =====> 模型版本不一致, 清除当前记录"),await this.db.table("models").delete(e),null}catch{return console.log(" =====> 查询表中模型失败"),this.db.delete().then(()=>{this.init()}),null}return n.data}async getStats(){const e=await this.db.table("models").toArray(),t=e.reduce((s,i)=>s+(i.size||0),0),n=e.reduce((s,i)=>s+(i.accessCount||0),0);return{count:e.length,totalSize:t,totalSizeMB:(t/1024/1024).toFixed(2),maxEntries:this.options.maxEntries,maxSizeMB:(this.options.maxSize/1024/1024).toFixed(2),usagePercentage:(t/this.options.maxSize*100).toFixed(2),totalAccessCount:n,avgAccessCount:e.length>0?(n/e.length).toFixed(2):0}}async clear(){await this.db.table("models").clear(),console.log("[ IDBCache ] ====> 缓存已清空")}async deleteModel(e){await this.db.table("models").delete(e)}}function _e(o){const{geometries:e,materials:t,hierarchy:n}=o,s=new Map;e.forEach((a,l)=>{const d=is(a);s.set(l,d)});const i=new Map;t.forEach((a,l)=>{const d=rs(a);i.set(l,d)});const r=new x.Group;r.name="Scene";const c=new Map;return n.forEach(a=>{let l;if(a.type==="Mesh"){const d=a.geometryIndex>=0?s.get(a.geometryIndex):null,h=a.materialIndex>=0?i.get(a.materialIndex):null;l=new x.Mesh(d,h)}else a.type==="Group"?l=new x.Group:a.type==="Object3D"?l=new x.Object3D:l=new x.Object3D;l.name=a.name,l.position.fromArray(a.position),l.rotation.fromArray(a.rotation),l.scale.fromArray(a.scale),l.visible=a.visible,l.userData=a.userData||{},c.set(a.id,l)}),n.forEach(a=>{const l=c.get(a.id);if(a.parentId!==null){const d=c.get(a.parentId);d&&d.add(l)}else r.add(l)}),r}function is(o){const e=new x.BufferGeometry;for(const t in o.attributes){const n=o.attributes[t],s=n.array;let i;if(s.byteLength===0){console.warn(`[ sceneRebuilder ] 属性 ${t} 的数组为空`);continue}if(s.buffer&&s.buffer.byteLength===0){console.warn(`[ sceneRebuilder ] 属性 ${t} 的 buffer 已被转移,尝试重建`);continue}i=s;const r=new x.BufferAttribute(i,n.itemSize);r.normalized=n.normalized,e.setAttribute(t,r)}if(o.index){const t=o.index,n=t.array;if(n&&n.byteLength>0){const s=new x.BufferAttribute(n,t.itemSize);e.setIndex(s)}}return e}function rs(o){let e;const t={color:o.color!==void 0?o.color:16777215,opacity:o.opacity!==void 0?o.opacity:1,transparent:o.transparent!==void 0?o.transparent:!1,alphaTest:o.alphaTest!==void 0?o.alphaTest:0,side:o.side!==void 0?o.side:x.FrontSide,depthTest:o.depthTest!==void 0?o.depthTest:!0,depthWrite:o.depthWrite!==void 0?o.depthWrite:!0,wireframe:o.wireframe!==void 0?o.wireframe:!1,vertexColors:o.vertexColors!==void 0?o.vertexColors:!1};switch(o.type){case"MeshStandardMaterial":e=new x.MeshStandardMaterial({...t,roughness:o.roughness!==void 0?o.roughness:.5,metalness:o.metalness!==void 0?o.metalness:.5,emissive:o.emissive!==void 0?o.emissive:0,emissiveIntensity:o.emissiveIntensity!==void 0?o.emissiveIntensity:1});break;case"MeshBasicMaterial":e=new x.MeshBasicMaterial({...t});break;case"MeshPhongMaterial":e=new x.MeshPhongMaterial({...t,shininess:o.shininess!==void 0?o.shininess:30,specular:o.specular!==void 0?o.specular:1118481,emissive:o.emissive!==void 0?o.emissive:0,emissiveIntensity:o.emissiveIntensity!==void 0?o.emissiveIntensity:1});break;default:e=new x.MeshStandardMaterial(t)}return e.uuid=o.uuid,e}class os{constructor(){this.geometries=[],this.materials=[],this.hierarchy=[],this.geometryMap=new Map,this.materialMap=new Map}addChunk(e){e.geometries&&e.geometries.forEach(t=>{const n=this.geometries.length;this.geometries.push(t),this.geometryMap.set(t.uuid,n)}),e.materials&&e.materials.forEach(t=>{const n=this.materials.length;this.materials.push(t),this.materialMap.set(t.uuid,n)}),e.hierarchy&&this.hierarchy.push(...e.hierarchy)}buildCurrent(){const e={geometries:this.geometries,materials:this.materials,hierarchy:this.hierarchy};return _e(e)}finalize(){return this.buildCurrent()}}function as(o){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/gltfParser.worker-D2lwod50.js").href:new URL("assets/gltfParser.worker-D2lwod50.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{name:o==null?void 0:o.name})}function cs(o){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/gltfParserOptimized.worker-yo8WMPFM.js").href:new URL("assets/gltfParserOptimized.worker-yo8WMPFM.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{name:o==null?void 0:o.name})}let X;const fe="/draco/";let V,W,Oe=0;const B=new Map,v=new Map;function ye(o){const e=o.clone(!1);o.userData&&typeof o.userData=="object"?e.userData=JSON.parse(JSON.stringify(o.userData)):e.userData=o.userData;for(const t of o.children){const n=ye(t);e.add(n)}return e}const Ge=(o={})=>{const{debug:e=!1}=o,t=new ot,n=new it;n.setDecoderPath(fe),t.setDRACOLoader(n);const s={info:(...f)=>e&&console.log(...f),warn:(...f)=>e&&console.warn(...f),error:(...f)=>console.error(...f),time:f=>e&&console.time(f),timeEnd:f=>e&&console.timeEnd(f)};function i(f,p,y,w){return t.load(f,p,y,w)}function r(f,p){return new Promise((y,w)=>{t.load(f,y,p,w)})}async function c(f,p,y,w={}){const T=performance.now();let S=!1;const{maxRetries:M=3,optimizeMaterials:A=!1,simplifyGeometry:P=!1,simplifyRatio:D=.5,simplifyOptions:G={},useMemoryCache:J=!0}=w;if(J){const C=v.get(f);if(C&&C.has(p)){const I=C.get(p);s.info(`[ 内存缓存命中 ] ${f} (version: ${p})`),s.time("[ 内存缓存克隆耗时 ]");const z=ye(I);return s.timeEnd("[ 内存缓存克隆耗时 ]"),F.recordHit(performance.now()-T),z}}try{let C=await l(f,p);if(C)s.info(`[ asyncFetch ] ====> IndexedDB 缓存命中: ${f}`),S=!0;else{s.info(`[ asyncFetch ] ====> 缓存未命中: ${f}`),s.time("[ fetchArrayBuffer ] 加载模型耗时"),C=await Q.retry(()=>a(f,y),{maxRetries:M,shouldRetry:we=>!!(we.name==="TypeError"||we.message.includes("HTTP error! status: 5"))}),s.timeEnd("[ fetchArrayBuffer ] 加载模型耗时");const N=performance.now();await X.saveModel(f,p,C);const oe=performance.now()-N;F.recordCacheSave(oe),S=!1}s.time("[ 解析模型耗时 ]");let I=await d(C);if(s.timeEnd("[ 解析模型耗时 ]"),s.time("[ 模型优化耗时 ]"),A){s.info("🔧 [ 材质优化 ] 开始合并相同材质...");const{modelOptimizer:N}=await Promise.resolve().then(()=>require("./modelOptimizer-A0Cs6f9e.cjs"));I=N.optimizeMaterials(I)}if(P){s.info(`🔧 [ 几何体简化 ] 开始简化模型 (比例: ${D})...`);const{modelOptimizer:N}=await Promise.resolve().then(()=>require("./modelOptimizer-A0Cs6f9e.cjs")),oe={minFaceCount:100,preserveUVs:!0,...G};I=N.simplifyModel(I,D,oe)}if(s.timeEnd("[ 模型优化耗时 ]"),J){v.has(f)||v.set(f,new Map);const N=v.get(f);N.has(p)||(s.info(`[ 内存缓存 ] 存储模型 ${f} (version: ${p})`),N.set(p,ye(I)))}const z=performance.now()-T;return S?F.recordHit(z):F.recordMiss(z),I}catch(C){throw s.error(`加载模型 ${f} 失败:`,C),F.recordError(f,C),C.name==="TypeError"&&C.message.includes("fetch")?$.networkError(f,C):C}}async function a(f,p){return new Promise((y,w)=>{fetch(f).then(T=>{if(!T.ok)throw new Error(`HTTP error! status: ${T.status}`);return T}).then(T=>{const S=T.headers.get("content-length"),M=S?parseInt(S,10):0;if(p&&M>0){const A=T.body.getReader();let P=0;const D=[],G=()=>{A.read().then(({done:J,value:C})=>{if(J){const I=new Uint8Array(P);let z=0;for(const N of D)I.set(N,z),z+=N.length;y(I.buffer);return}D.push(C),P+=C.length,p(Math.round(P/M*100)),G()}).catch(w)};G()}else return T.arrayBuffer()}).then(T=>y(T)).catch(T=>{w(T)})})}async function l(f,p){return X||(X=new ge),X.getModel(f,p)}async function d(f,p={}){if(!f)return null;const{useOptimizedParser:y=!0,useProgressive:w=!1}=p;if(y){const M=m();if(M)try{s.time("[ 优化解析 ] 使用 Transferable Objects 解析");const A=await g(M,f,w);return s.timeEnd("[ 优化解析 ] 使用 Transferable Objects 解析"),_e(A)}catch(A){s.warn("[ 优化解析 ] 失败,回退到标准解析",A)}}const T=h();if(T)try{const M=await _(T,f);return Fe(M)}catch(M){s.warn("[ GLTF Worker ] ====> 解析失败,回退到主线程解析",M)}return(await b(f)).scene}const h=()=>{if(typeof window>"u"||typeof Worker>"u")return null;if(!V)try{s.info("[GLTF Worker] 使用 ?worker 工厂函数创建 Worker..."),V=as(),s.info("[GLTF Worker] Worker 创建成功:",V),V.onmessage=f=>{const{id:p,data:y,error:w}=f.data||{};if(!p||!B.has(p))return;const{resolve:T,reject:S}=B.get(p);B.delete(p),w?S(new Error(w)):T(y)},V.onmessageerror=f=>{console.error("[ GLTF Worker ] ====> 消息解析失败",f)},V.onerror=f=>{console.error("[ GLTF Worker ] ====> 运行错误",f)}}catch(f){console.error("[GLTF Worker] 创建 Worker 失败:",f),console.error("[GLTF Worker] 错误堆栈:",f.stack)}return V},m=()=>{if(typeof window>"u"||typeof Worker>"u")return null;if(!W)try{s.info("[Optimized Worker] 使用 ?worker 工厂函数创建 Worker..."),W=cs(),s.info("[Optimized Worker] Worker 创建成功:",W),W.onmessage=f=>{const{id:p,data:y,error:w,type:T}=f.data||{};if(!p||!B.has(p)||T==="progress")return;const{resolve:S,reject:M}=B.get(p);B.delete(p),w?M(new Error(w)):S(y)},W.onmessageerror=f=>{console.error("[ 优化 Worker ] ====> 消息解析失败",f)},W.onerror=f=>{console.error("[ 优化 Worker ] ====> 运行错误",f)}}catch(f){return s.warn("[ 优化 Worker ] ====> 创建失败,可能不支持模块化 Worker",f),null}return W},g=(f,p,y=!1)=>new Promise((w,T)=>{const S=++Oe;B.set(S,{resolve:w,reject:T});const M={id:S,arrayBuffer:p,dracoPath:fe,mode:y?"progressive":"standard"};f.postMessage(M,[p])}),_=(f,p)=>new Promise((y,w)=>{const T=++Oe;B.set(T,{resolve:y,reject:w}),f.postMessage({id:T,arrayBuffer:p,dracoPath:fe})}),b=f=>new Promise((p,y)=>{t.parse(f,"",p,y)});return{load:i,asyncLoad:r,asyncCacheLoad:c,asyncFetch:c,getCacheStats:()=>F.getStats(),getCache:()=>X||(X=new ge),logCacheReport:()=>F.logReport(),resetCacheStats:()=>F.reset(),clearMemoryCache:()=>{let f=0;for(const[p,y]of v.entries())f+=y.size,y.clear();return v.clear(),s.info(`[ 内存缓存 ] 已清空,释放了 ${f} 个模型`),f},getMemoryCacheInfo:()=>{const f=[];let p=0;for(const[y,w]of v.entries()){const T=Array.from(w.keys());p+=T.length,f.push({path:y,versions:T,count:T.length})}return{totalPaths:v.size,totalModels:p,details:f}},deleteMemoryCache:(f,p)=>{const y=v.get(f);if(!y)return!1;if(p){const w=y.delete(p);return y.size===0&&v.delete(f),s.info(`[ 内存缓存 ] 删除模型 ${f} (version: ${p})`),w}else{const w=y.size;return v.delete(f),s.info(`[ 内存缓存 ] 删除模型 ${f} 及其所有版本 (共 ${w} 个)`),w>0}}}};class je{constructor(e={}){this.options={maxPreloadCount:e.maxPreloadCount||5,preloadDelay:e.preloadDelay||1e3,enableLearning:e.enableLearning!==!1},this.loadHistory=new Map,this.loadSequence=[],this.associations=new Map,this.preloadQueue=new Set,this.isPreloading=!1,this.loader=null,this.getLoader=()=>(this.loader||(this.loader=Ge()),this.loader)}recordLoad(e,t){const n=Date.now(),s=this.loadHistory.get(e)||{count:0,lastLoadTime:0,versions:new Set};s.count++,s.lastLoadTime=n,s.versions.add(t),this.loadHistory.set(e,s),this.loadSequence.push({path:e,timestamp:n}),this.loadSequence.length>100&&this.loadSequence.shift(),this.options.enableLearning&&this.loadSequence.length>=2&&this._learnAssociations(e),this._triggerPredictivePreload(e,t)}_learnAssociations(e){const n=this.loadSequence.length-1;for(let s=Math.max(0,n-10);s<n;s++){const{path:i}=this.loadSequence[s];if(this.loadSequence[n].timestamp-this.loadSequence[s].timestamp<5*60*1e3&&i!==e){this.associations.has(i)||this.associations.set(i,new Map);const c=this.associations.get(i),a=c.get(e)||0;c.set(e,a+1)}}}_triggerPredictivePreload(e,t){setTimeout(()=>{const n=this.predictNext(e);this.preload(n,t)},this.options.preloadDelay)}predictNext(e){const t=new Map,n=this.associations.get(e);n&&n.forEach((c,a)=>{t.set(a,(t.get(a)||0)+c*2)});const s=Array.from(this.loadHistory.values()).reduce((c,a)=>c+a.count,0)/(this.loadHistory.size||1);this.loadHistory.forEach((c,a)=>{if(a!==e){const l=c.count/s;t.set(a,(t.get(a)||0)+l)}});const i=this.loadSequence.slice(-10);return new Set(i.map(c=>c.path)).forEach(c=>{c!==e&&t.set(c,(t.get(c)||0)+.5)}),Array.from(t.entries()).sort((c,a)=>a[1]-c[1]).slice(0,this.options.maxPreloadCount).map(([c])=>c)}async preload(e,t="latest"){if(this.isPreloading)return;this.isPreloading=!0;const{asyncFetch:n}=this.getLoader(),s=e.filter(i=>!this.preloadQueue.has(i)).slice(0,this.options.maxPreloadCount).map(async i=>{this.preloadQueue.add(i);try{console.log(`[ 智能预加载 ] 开始预加载: ${i}`),await n(i,t),console.log(`[ 智能预加载 ] 完成: ${i}`)}catch(r){console.warn(`[ 智能预加载 ] 失败: ${i}`,r)}finally{this.preloadQueue.delete(i)}});await Promise.all(s),this.isPreloading=!1}addAssociation(e,t){this.associations.has(e)||this.associations.set(e,new Map);const n=this.associations.get(e);t.forEach(s=>{const i=n.get(s)||0;n.set(s,i+10)})}getStats(){const e=Array.from(this.loadHistory.entries()).sort((t,n)=>n[1].count-t[1].count).slice(0,10).map(([t,n])=>({path:t,loadCount:n.count,lastLoadTime:new Date(n.lastLoadTime).toLocaleString()}));return{totalModelsLoaded:this.loadHistory.size,totalAssociations:this.associations.size,topModels:e,preloadQueueSize:this.preloadQueue.size}}clearHistory(){this.loadHistory.clear(),this.loadSequence=[],this.associations.clear()}exportAssociations(){const e={};return this.associations.forEach((t,n)=>{e[n]=Array.from(t.entries())}),e}importAssociations(e){Object.entries(e).forEach(([t,n])=>{const s=new Map(n);this.associations.set(t,s)})}}const ls=new je;exports.CSS3DRenderer=Vt;exports.CSS3DSprite=zt;exports.CacheMonitor=Ue;exports.ErrorType=te;exports.IDBCache=ge;exports.ModelLoadError=$;exports.PredictiveLoader=je;exports.ProgressiveSceneBuilder=os;exports.RetryHelper=Q;exports.Stats=q;exports.cacheMonitor=F;exports.createArrowHelper=Jt;exports.createAxesHelper=Qt;exports.createBox3Helper=Yt;exports.createCameraHelper=Wt;exports.createGridHelper=Xt;exports.createMapControls=$t;exports.createOrbitControl=qt;exports.createRaycaster=Zt;exports.createStats=es;exports.dataToObject3D=Fe;exports.dataToObject3DSync=ns;exports.disposeThreeObject=He;exports.object3DToData=ts;exports.object3DToDataSync=ss;exports.predictiveLoader=ls;exports.rebuildScene=_e;exports.useGLTFLoader=Ge;