@splnlss/3d-story-viewer 0.7.0 → 0.8.1

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.
Files changed (37) hide show
  1. package/build/assets/viewer/{geojson.worker-QNi-d8kU.js → geojson.worker-D3uq_RbR.js} +1 -1
  2. package/build/assets/viewer/spark-a62bdfe36d20.wasm +0 -0
  3. package/build/assets/viewer/{spark-worker-5ec8a483b87c.js → spark-worker-c1a6c013b888.js} +194 -43
  4. package/build/computeElevation.cjs +1 -1
  5. package/build/computeElevation.js +2 -2
  6. package/build/index-D87IZDc6.cjs +1 -0
  7. package/build/{index-CsZhc21b.js → index-DaqGSC4W.js} +1302 -829
  8. package/build/main-CY1MzgxV.js +15888 -0
  9. package/build/main-DFAyOsl5.cjs +1 -0
  10. package/build/spark.module-BGYmUUum.js +18168 -0
  11. package/build/spark.module-Y1ABc5im.cjs +1 -0
  12. package/build/types/src/viewer/ContentLayer/GaussianSplatLayer.d.ts +4 -6
  13. package/build/types/src/viewer/ContentLayer/MeshLayer.d.ts +1 -1
  14. package/build/types/src/viewer/ContentLayer/TilesLayer.d.ts +2 -0
  15. package/build/types/src/viewer/ContentLayer/gaussianSplatUtils.d.ts +2 -1
  16. package/build/types/src/viewer/ContentLayer/index.d.ts +5 -3
  17. package/build/types/src/viewer/EnvironmentControls.d.ts +18 -12
  18. package/build/types/src/viewer/GlobeControls.d.ts +9 -6
  19. package/build/types/src/viewer/GlobeManager.d.ts +2 -0
  20. package/build/types/src/viewer/Sky.d.ts +5 -2
  21. package/build/types/src/viewer/TileDecoders.d.ts +11 -0
  22. package/build/types/src/viewer/TransitionControls.d.ts +2 -1
  23. package/build/types/src/viewer/index.d.ts +50 -18
  24. package/build/types/src/viewer/loadSpark.d.ts +1 -0
  25. package/build/types/src/viewer/mods.d.ts +1 -0
  26. package/build/types/src/viewer/shaders/chunks.d.ts +1 -0
  27. package/build/types/src/viewer/surfacePicking.d.ts +31 -0
  28. package/build/types/src/viewer/utils.d.ts +6 -4
  29. package/build/types/src/workers/geojson.worker.d.ts +2 -2
  30. package/build/types/utils/elevation/gltf.d.ts +2 -1
  31. package/build/viewer.cjs +1 -1
  32. package/build/viewer.js +5 -28044
  33. package/package.json +18 -16
  34. package/build/assets/viewer/spark-8b93f8c03d97.wasm +0 -0
  35. package/build/assets/viewer/spark-old-worker-932b4a2c87ca.js +0 -8168
  36. package/build/assets/viewer/spark-worker-015de49d2d00.wasm +0 -0
  37. package/build/index-wUFLgXbb.cjs +0 -1
@@ -0,0 +1 @@
1
+ "use strict";var e,t=Object.defineProperty,r=(e,r,i)=>((e,r,i)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i)(e,"symbol"!=typeof r?r+"":r,i);const i=require("./index-D87IZDc6.cjs");i.ShaderChunk.bayer_dither_hash_pars_fragment="#ifdef USE_HASH\nuniform float hashOpacity;varying float vCameraDistance;float bayerDitherPattern(vec2 p){float bayerMatrix[16];bayerMatrix[0]=0.0;bayerMatrix[1]=8.0;bayerMatrix[2]=2.0;bayerMatrix[3]=10.0;bayerMatrix[4]=12.0;bayerMatrix[5]=4.0;bayerMatrix[6]=14.0;bayerMatrix[7]=6.0;bayerMatrix[8]=3.0;bayerMatrix[9]=11.0;bayerMatrix[10]=1.0;bayerMatrix[11]=9.0;bayerMatrix[12]=15.0;bayerMatrix[13]=7.0;bayerMatrix[14]=13.0;bayerMatrix[15]=5.0;int x=int(mod(p.x,4.0));int y=int(mod(p.y,4.0));int index=x+y*4;return bayerMatrix[index]/16.0;}\n#endif\n",i.ShaderChunk.bayer_dither_hash_fragment="#ifdef USE_HASH\nfloat hashAmount=smoothstep(5e4,1e2,vCameraDistance)*0.75+0.1;float ditherValue=bayerDitherPattern(gl_FragCoord.xy);if(hashAmount<ditherValue){discard;}\n#endif\n",i.ShaderChunk.bayer_dither_hash_pars_vertex="#ifdef USE_HASH\nvarying float vCameraDistance;\n#endif\n",i.ShaderChunk.bayer_dither_hash_vertex="#ifdef USE_HASH\nvCameraDistance=-mvPosition.z;\n#endif\n";class s extends i.Object3D{constructor(e=document.createElement("div")){super(),this.isCSS2DObject=!0,this.element=e,this.element.style.position="absolute",this.element.style.userSelect="none",this.element.setAttribute("draggable",!1),this.center=new i.Vector2(.5,.5),this.rotation2D=0,this.addEventListener("removed",(function(){this.traverse((function(e){e.element&&e.element instanceof e.element.ownerDocument.defaultView.Element&&null!==e.element.parentNode&&e.element.remove()}))}))}copy(e,t){return super.copy(e,t),this.element=e.element.cloneNode(!0),this.center=e.center,this.rotation2D=e.rotation2D,this}}const n=new i.Vector3,a=new i.Matrix4,o=new i.Matrix4,l=new i.Vector3,c=new i.Vector3;class h{constructor(e={}){const t=this;let r,i,s,h;const u={objects:new WeakMap},d=void 0!==e.element?e.element:document.createElement("div");function p(e){e.isCSS2DObject&&(e.element.style.display="none");for(let t=0,r=e.children.length;t<r;t++)p(e.children[t])}function m(e,r,i){if(!1!==e.visible){if(e.isCSS2DObject){n.setFromMatrixPosition(e.matrixWorld),n.applyMatrix4(o);const a=n.z>=-1&&n.z<=1&&!0===e.layers.test(i.layers),l=e.element;if(l.style.display=!0===a?"":"none",!0===a){e.onBeforeRender(t,r,i);const a=100*e.center.x,o=100*e.center.y;l.style.transformOrigin=`${a}% ${o}%`;const c=-e.rotation2D,u=n.x*s+s,p=-n.y*h+h;l.style.transform=`translate(${-a}%, ${-o}%) translate(${u}px, ${p}px) rotate(${c}rad)`,l.parentNode!==d&&d.appendChild(l),e.onAfterRender(t,r,i)}const c={distanceToCameraSquared:f(i,e)};u.objects.set(e,c)}for(let t=0,s=e.children.length;t<s;t++)m(e.children[t],r,i)}else p(e)}function f(e,t){return l.setFromMatrixPosition(e.matrixWorld),c.setFromMatrixPosition(t.matrixWorld),l.distanceToSquared(c)}d.style.overflow="hidden",this.domElement=d,this.sortObjects=!0,this.getSize=function(){return{width:r,height:i}},this.render=function(e,t){!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),a.copy(t.matrixWorldInverse),o.multiplyMatrices(t.projectionMatrix,a),m(e,e,t),this.sortObjects&&function(e){const t=function(e){const t=[];return e.traverseVisible((function(e){e.isCSS2DObject&&t.push(e)})),t}(e).sort((function(e,t){if(e.renderOrder!==t.renderOrder)return t.renderOrder-e.renderOrder;return u.objects.get(e).distanceToCameraSquared-u.objects.get(t).distanceToCameraSquared})),r=t.length;for(let i=0,s=t.length;i<s;i++)t[i].element.style.zIndex=r-i}(e)},this.setSize=function(e,t){r=e,i=t,s=r/2,h=i/2,d.style.width=e+"px",d.style.height=t+"px"}}}let u=null;function d(){return u??(u=Promise.resolve().then((()=>require("./spark.module-Y1ABc5im.cjs"))).catch((e=>{throw u=null,e}))),u}class p{constructor(){this.listeners={}}addEventListener(e,t){const r=this.listeners;void 0===r[e]&&(r[e]=[]),-1===r[e].indexOf(t)&&r[e].push(t)}hasEventListener(e,t){const r=this.listeners;return void 0!==r[e]&&-1!==r[e].indexOf(t)}removeEventListener(e,t){const r=this.listeners[e];if(void 0!==r){const e=r.indexOf(t);-1!==e&&r.splice(e,1)}}dispatchEvent(e){const t=this.listeners[e.type];if(void 0!==t){e.target=this;const r=t.slice(0);for(let t=0,i=r.length;t<i;t+=1)r[t].call(this,e)}}}function m(e){return!(!e||"object"!=typeof e)&&0===Object.keys(e).length}function f(e,t){if(e===t)return!0;if(null===e||"object"!=typeof e||null===t||"object"!=typeof t)return!1;const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r)if(!i.includes(s)||!f(e[s],t[s]))return!1;return!0}const g="defined",y="updated",v="deleted";class T extends p{constructor(e){super(),this.initialValues={},this.values={},this.define(e)}define(e={},t=!0){const r={};for(const i in e)if(Object.hasOwnProperty.call(e,i)){const s=e[i];Object.hasOwnProperty.call(this.initialValues,i)?t&&(this.initialValues[i]=s,this.values[i]=s,r[i]=s):(this.initialValues[i]=s,this.values[i]=s,r[i]=s)}return m(r)||this.dispatchEvent({type:g,values:r}),r}update(e={},t={}){let r={};const i={},s=t.force||!1,n=t.dryrun||!1;for(const a in e)if(Object.hasOwnProperty.call(e,a)){let t=e[a];Object.hasOwnProperty.call(this.initialValues,a)&&(void 0===t&&(t=this.initialValues[a]),f(this.values[a],t)&&!s||(i[a]=this.values[a],n||(this.values[a]=t),r[a]=t))}return n||m(r)||this.dispatchEvent({type:y,values:this.values,changes:r,before:i}),r}get(e){let t={};if(e){Array.isArray(e)||(e=[e]);for(let r=0;r<e.length;r++){const i=e[r];Object.hasOwnProperty.call(this.values,i)&&(t[i]=this.values[i])}}else t={...this.values};return 1==e.length?t[e[0]]:t}reset(e){const t={},r={};if(e){Array.isArray(e)||(e=[e]);for(let i=0;i<e.length;i++){const s=e[i];Object.hasOwnProperty.call(this.initialValues,s)&&(r[s]=this.values[s],this.values[s]=this.initialValues[s],t[s]=this.initialValues[s])}}else for(const i in this.initialValues)Object.hasOwnProperty.call(this.initialValues,i)&&(this.values[i]=this.initialValues[i],t[i]=this.initialValues[i]);return m(t)||this.dispatchEvent({type:y,values:this.values,changes:t,before:r}),t}delete(e=[]){const t={};Array.isArray(e)||(e=[e]);for(let r=0;r<e.length;r++){const i=e[r];Object.hasOwnProperty.call(this.values,i)&&(t[i]=this.values[i],delete this.values[i],delete this.initialValues[i])}return m(t)||this.dispatchEvent({type:v,deleted:t}),t}clone(){const e=new T(this.initialValues);return e.update(this.values),e}}new T;class x extends i.Mesh{constructor(){super(new i.PlaneGeometry(0,0),new b),this.renderOrder=1/0}onBeforeRender(e){const t=this.material.uniforms;e.getSize(t.resolution.value)}updateMatrixWorld(){this.matrixWorld.makeTranslation(this.position)}dispose(){this.geometry.dispose(),this.material.dispose()}}class b extends i.ShaderMaterial{constructor(){super({depthWrite:!1,depthTest:!1,transparent:!0,uniforms:{resolution:{value:new i.Vector2},size:{value:15},thickness:{value:2},opacity:{value:1}},vertexShader:"\n\n\t\t\t\tuniform float size;\n\t\t\t\tuniform float thickness;\n\t\t\t\tuniform vec2 resolution;\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvUv = uv;\n\n\t\t\t\t\tfloat aspect = resolution.x / resolution.y;\n\t\t\t\t\tvec2 offset = uv * 2.0 - vec2( 1.0 );\n\t\t\t\t\toffset.y *= aspect;\n\n\t\t\t\t\tvec4 screenPoint = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\t\t\t\t\tscreenPoint.xy += offset * ( size + thickness ) * screenPoint.w / resolution.x;\n\n\t\t\t\t\tgl_Position = screenPoint;\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform float size;\n\t\t\t\tuniform float thickness;\n\t\t\t\tuniform float opacity;\n\n\t\t\t\tvarying vec2 vUv;\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tfloat ht = 0.5 * thickness;\n\t\t\t\t\tfloat planeDim = size + thickness;\n\t\t\t\t\tfloat offset = ( planeDim - ht - 2.0 ) / planeDim;\n\t\t\t\t\tfloat texelThickness = ht / planeDim;\n\n\t\t\t\t\tvec2 vec = vUv * 2.0 - vec2( 1.0 );\n\t\t\t\t\tfloat dist = abs( length( vec ) - offset );\n\t\t\t\t\tfloat fw = fwidth( dist ) * 0.5;\n\t\t\t\t\tfloat a = smoothstep( texelThickness - fw, texelThickness + fw, dist );\n\n\t\t\t\t\tgl_FragColor = vec4( 1, 1, 1, opacity * ( 1.0 - a ) );\n\n\t\t\t\t}\n\t\t\t"})}}const _=new i.Vector2,w=new i.Vector2;class M{constructor(){this.domElement=null,this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new i.Vector2,this.hoverSet=!1}reset(){this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new i.Vector2,this.hoverSet=!1}updateFrame(){const{previousPositions:e,pointerPositions:t}=this;for(const r in t)e[r].copy(t[r])}setHoverEvent(e){"mouse"!==e.pointerType&&"wheel"!==e.type||(this.getAdjustedPointer(e,this.hoverPosition),this.hoverSet=!0)}getLatestPoint(e){return null!==this.pointerType?(this.getCenterPoint(e),e):this.hoverSet?(e.copy(this.hoverPosition),e):null}getAdjustedPointer(e,t){const r=(this.domElement?this.domElement:e.target).getBoundingClientRect(),i=e.clientX-r.left,s=e.clientY-r.top;t.set(i,s)}addPointer(e){const t=e.pointerId,r=new i.Vector2;this.getAdjustedPointer(e,r),this.pointerOrder.push(t),this.pointerPositions[t]=r,this.previousPositions[t]=r.clone(),this.startPositions[t]=r.clone(),1===this.getPointerCount()&&(this.pointerType=e.pointerType,this.buttons=e.buttons)}updatePointer(e){const t=e.pointerId;return t in this.pointerPositions&&(this.getAdjustedPointer(e,this.pointerPositions[t]),!0)}deletePointer(e){const t=e.pointerId,r=this.pointerOrder;r.splice(r.indexOf(t),1),delete this.pointerPositions[t],delete this.previousPositions[t],delete this.startPositions[t],0===this.getPointerCount()&&(this.buttons=0,this.pointerType=null)}getPointerCount(){return this.pointerOrder.length}getCenterPoint(e,t=this.pointerPositions){const r=this.pointerOrder;if(1===this.getPointerCount()||"mouse"===this.getPointerType()){const i=r[0];return e.copy(t[i]),e}if(2===this.getPointerCount()){const r=this.pointerOrder[0],i=this.pointerOrder[1],s=t[r],n=t[i];return e.addVectors(s,n).multiplyScalar(.5),e}return null}getPreviousCenterPoint(e){return this.getCenterPoint(e,this.previousPositions)}getStartCenterPoint(e){return this.getCenterPoint(e,this.startPositions)}getMoveDistance(){return this.getCenterPoint(_),this.getPreviousCenterPoint(w),_.sub(w).length()}getTouchPointerDistance(e=this.pointerPositions){if(this.getPointerCount()<=1||"mouse"===this.getPointerType())return 0;const{pointerOrder:t}=this,r=t[0],i=t[1],s=e[r],n=e[i];return s.distanceTo(n)}getPreviousTouchPointerDistance(){return this.getTouchPointerDistance(this.previousPositions)}getStartTouchPointerDistance(){return this.getTouchPointerDistance(this.startPositions)}getPointerType(){return this.pointerType}isPointerTouch(){return"touch"===this.getPointerType()}getPointerButtons(){return this.buttons}isLeftClicked(){return Boolean(1&this.buttons)}isRightClicked(){return Boolean(2&this.buttons)}}const S=new i.Matrix4;function A(e,t,r){return r.makeTranslation(-e.x,-e.y,-e.z),S.makeRotationFromQuaternion(t),r.premultiply(S),S.makeTranslation(e.x,e.y,e.z),r.premultiply(S),r}function C(e,t,r){r.x=e.x/t.clientWidth*2-1,r.y=-e.y/t.clientHeight*2+1,r.isVector3&&(r.z=0)}function E(e,t,r){const s=e instanceof i.Ray?e:e.ray,{origin:n,direction:a}=s;n.set(t.x,t.y,-1).unproject(r),a.set(t.x,t.y,1).unproject(r).sub(n),e.isRay||(e.near=0,e.far=a.length(),e.camera=r),a.normalize()}const R=.05,P=.025,L=new i.Matrix4,U=new i.Matrix4,I=new i.Vector3,F=new i.Vector3,k=new i.Vector3,D=new i.Vector3,O=new i.Vector3,B=new i.Vector3,N=new i.Vector3,V=new i.Vector3,z=new i.Quaternion,G=new i.Plane,H=new i.Vector3,j=new i.Vector3,W=new i.Vector3,q=new i.Quaternion,X=new i.Ray,K=new i.Vector2,Y=new i.Vector2,Q=new i.Vector2,$=new i.Vector2,Z=new i.Vector2,J=new i.Vector2,ee={type:"change"},te={type:"start"},re={type:"end"};class ie extends i.EventDispatcher{get enabled(){return this._enabled}set enabled(e){e!==this.enabled&&(this._enabled=e,this.resetState(),this.pointerTracker.reset(),this.enabled||(this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0)))}constructor(e=null,t=null,r=null,s=null){super(),this.isEnvironmentControls=!0,this.domElement=null,this.camera=null,this.scene=null,this.tilesRenderer=null,this._enabled=!0,this.cameraRadius=5,this.rotationSpeed=1,this.minAltitude=0,this.maxAltitude=.45*Math.PI,this.minDistance=10,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.zoomSpeed=1,this.adjustHeight=!0,this.enableDamping=!1,this.dampingFactor=.15,this.fallbackPlane=new i.Plane(new i.Vector3(0,1,0),0),this.useFallbackPlane=!0,this.scaleZoomOrientationAtEdges=!1,this.autoAdjustCameraRotation=!0,this.state=0,this.pointerTracker=new M,this.needsUpdate=!1,this.actionHeightOffset=0,this.pivotPoint=new i.Vector3,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.zoomDirection=new i.Vector3,this.zoomPoint=new i.Vector3,this.zoomDelta=0,this.rotationInertiaPivot=new i.Vector3,this.rotationInertia=new i.Vector2,this.dragInertia=new i.Vector3,this.inertiaTargetDistance=1/0,this.inertiaStableFrames=0,this.pivotMesh=new x,this.pivotMesh.raycast=()=>{},this.pivotMesh.scale.setScalar(.25),this.raycaster=new i.Raycaster,this.raycaster.firstHitOnly=!0,this.up=new i.Vector3(0,1,0),this.clock=new i.Clock,this._detachCallback=null,this._upInitialized=!1,this._lastUsedState=0,this._zoomPointWasSet=!1,this._tilesOnChangeCallback=()=>this.zoomPointSet=!1,r&&this.attach(r),t&&this.setCamera(t),e&&this.setScene(e),s&&this.setTilesRenderer(s)}setScene(e){this.scene=e}setCamera(e){this.camera=e,this._upInitialized=!1,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.needsUpdate=!0,this.raycaster.camera=e,this.resetState()}setTilesRenderer(e){this.tilesRenderer=e,null!==this.tilesRenderer&&this.setScene(this.tilesRenderer.group)}attach(e){if(this.domElement)throw new Error("EnvironmentControls: Controls already attached to element");this.domElement=e,this.pointerTracker.domElement=e,e.style.touchAction="none";const t=e=>{this.enabled&&e.preventDefault()},r=e=>{if(!this.enabled)return;e.preventDefault();const{camera:t,raycaster:r,domElement:i,up:s,pivotMesh:n,pointerTracker:a,scene:o,pivotPoint:l,enabled:c}=this;if(a.addPointer(e),this.needsUpdate=!0,a.isPointerTouch())if(n.visible=!1,0===a.getPointerCount())i.setPointerCapture(e.pointerId);else if(a.getPointerCount()>2)return void this.resetState();a.getCenterPoint(Y),C(Y,i,Y),E(r,Y,t);const h=Math.abs(r.ray.direction.dot(s));if(h<R||h<P)return;const u=this._raycast(r);u&&(2===a.getPointerCount()||a.isRightClicked()||a.isLeftClicked()&&e.shiftKey?(this.setState(a.isPointerTouch()?4:2),l.copy(u.point),n.position.copy(u.point),n.visible=!a.isPointerTouch()&&c,n.updateMatrixWorld(),o.add(n)):a.isLeftClicked()&&(this.setState(1),l.copy(u.point),n.position.copy(u.point),n.updateMatrixWorld(),o.add(n)))};let i=!1;const s=e=>{const{pointerTracker:t}=this;if(!this.enabled)return;e.preventDefault();const{pivotMesh:r,enabled:s}=this;this.zoomDirectionSet=!1,this.zoomPointSet=!1,0!==this.state&&(this.needsUpdate=!0),t.setHoverEvent(e),t.updatePointer(e)&&(t.isPointerTouch()&&2===t.getPointerCount()&&(i||(i=!0,queueMicrotask((()=>{i=!1,t.getCenterPoint(Z);const e=t.getStartTouchPointerDistance(),n=t.getTouchPointerDistance(),a=n-e;if(0===this.state||4===this.state){t.getCenterPoint(Z),t.getStartCenterPoint(J);const e=2*window.devicePixelRatio,r=Z.distanceTo(J);(Math.abs(a)>e||r>e)&&(Math.abs(a)>r?(this.setState(3),this.zoomDirectionSet=!1):this.setState(2))}if(3===this.state){const e=t.getPreviousTouchPointerDistance();this.zoomDelta+=n-e,r.visible=!1}else 2===this.state&&(r.visible=s)})))),this.dispatchEvent(ee))},n=t=>{const{pointerTracker:r}=this;this.enabled&&0!==r.getPointerCount()&&(r.deletePointer(t),"touch"===r.getPointerType()&&0===r.getPointerCount()&&e.releasePointerCapture(t.pointerId),this.resetState(),this.needsUpdate=!0)},a=e=>{if(!this.enabled)return;e.preventDefault();const{pointerTracker:t}=this;let r;switch(t.setHoverEvent(e),t.updatePointer(e),this.dispatchEvent(te),e.deltaMode){case 2:r=800*e.deltaY;break;case 1:r=40*e.deltaY;break;case 0:r=e.deltaY}const i=Math.sign(r),s=Math.abs(r);this.zoomDelta-=.25*i*s,this.needsUpdate=!0,this._lastUsedState=3,this.dispatchEvent(re)},o=e=>{this.enabled&&this.resetState()};e.addEventListener("contextmenu",t),e.addEventListener("pointerdown",r),e.addEventListener("wheel",a,{passive:!1});const l=e.getRootNode();l.addEventListener("pointermove",s),l.addEventListener("pointerup",n),l.addEventListener("pointerleave",o),this._detachCallback=()=>{e.removeEventListener("contextmenu",t),e.removeEventListener("pointerdown",r),e.removeEventListener("wheel",a),l.removeEventListener("pointermove",s),l.removeEventListener("pointerup",n),l.removeEventListener("pointerleave",o)}}detach(){this.domElement=null,this._detachCallback&&(this._detachCallback(),this._detachCallback=null,this.pointerTracker.reset())}getUpDirection(e,t){t.copy(this.up)}getCameraUpDirection(e){this.getUpDirection(this.camera.position,e)}getPivotPoint(e){let t=null;3===this._lastUsedState?this._zoomPointWasSet&&(t=e.copy(this.zoomPoint)):2!==this._lastUsedState&&1!==this._lastUsedState||(t=e.copy(this.pivotPoint));const{camera:r,raycaster:i}=this;null!==t&&(F.copy(t).project(r),(F.x<-1||F.x>1||F.y<-1||F.y>1)&&(t=null)),E(i,{x:0,y:0},r);const s=this._raycast(i);return s&&(null===t||s.distance<t.distanceTo(i.ray.origin))&&(t=e.copy(s.point)),t}resetState(){0!==this.state&&this.dispatchEvent(re),this.state=0,this.pivotMesh.removeFromParent(),this.pivotMesh.visible=this.enabled,this.actionHeightOffset=0,this.pointerTracker.reset()}setState(e=this.state,t=!0){this.state!==e&&(0===this.state&&t&&this.dispatchEvent(te),this.pivotMesh.visible=this.enabled,this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0),this.inertiaStableFrames=0,this.state=e,0!==e&&4!==e&&(this._lastUsedState=e))}update(e=Math.min(this.clock.getDelta(),.064)){if(!this.enabled||!this.camera||0===e)return;const{camera:t,cameraRadius:r,pivotPoint:i,up:s,state:n,adjustHeight:a,autoAdjustCameraRotation:o}=this;t.updateMatrixWorld(),this.getCameraUpDirection(H),this._upInitialized||(this._upInitialized=!0,this.up.copy(H)),this.zoomPointSet=!1;const l=this._inertiaNeedsUpdate(),c=this.needsUpdate||l;if(this.needsUpdate||l){const r=this.zoomDelta;this._updateZoom(),this._updatePosition(e),this._updateRotation(e),1===n||2===n?(O.set(0,0,-1).transformDirection(t.matrixWorld),this.inertiaTargetDistance=F.copy(i).sub(t.position).dot(O)):0===n&&this._updateInertia(e),(0!==n||0!==r||l)&&this.dispatchEvent(ee),this.needsUpdate=!1}const h=t.isOrthographicCamera?null:a&&this._getPointBelowCamera()||null;if(this.getCameraUpDirection(H),this._setFrame(H),(1===this.state||2===this.state)&&0!==this.actionHeightOffset){const{actionHeightOffset:e}=this;t.position.addScaledVector(s,-e),i.addScaledVector(s,-e),h&&(h.distance-=e)}if(this.actionHeightOffset=0,h){const e=h.distance;if(e<r){const n=r-e;t.position.addScaledVector(s,n),i.addScaledVector(s,n),this.actionHeightOffset=n}}this.pointerTracker.updateFrame(),c&&o&&(this.getCameraUpDirection(H),this._alignCameraUp(H,1),this.getCameraUpDirection(H),this._clampRotation(H))}adjustCamera(e){const{adjustHeight:t,cameraRadius:r}=this;if(e.isPerspectiveCamera){this.getUpDirection(e.position,H);const i=t&&this._getPointBelowCamera(e.position,H)||null;if(i){const t=i.distance;t<r&&e.position.addScaledVector(H,r-t)}}}dispose(){this.detach()}_updateInertia(e){const{rotationInertia:t,pivotPoint:r,dragInertia:i,enableDamping:s,dampingFactor:n,camera:a,cameraRadius:o,minDistance:l,inertiaTargetDistance:c}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return i.set(0,0,0),void t.set(0,0,0);const h=Math.pow(2,-e/n),u=Math.max(a.near,o,l,c),d=25e-5;if(t.lengthSq()>0){E(X,F.set(0,0,-1),a),X.applyMatrix4(a.matrixWorldInverse),X.direction.normalize(),X.recast(-X.direction.dot(X.origin)).at(u/X.direction.z,F),F.applyMatrix4(a.matrixWorld),E(X,I.set(d,d,-1),a),X.applyMatrix4(a.matrixWorldInverse),X.direction.normalize(),X.recast(-X.direction.dot(X.origin)).at(u/X.direction.z,I),I.applyMatrix4(a.matrixWorld),F.sub(r).normalize(),I.sub(r).normalize();const i=F.angleTo(I)/e;t.multiplyScalar(h),(t.lengthSq()<i**2||!s)&&t.set(0,0)}if(i.lengthSq()>0){E(X,F.set(0,0,-1),a),X.applyMatrix4(a.matrixWorldInverse),X.direction.normalize(),X.recast(-X.direction.dot(X.origin)).at(u/X.direction.z,F),F.applyMatrix4(a.matrixWorld),E(X,I.set(d,d,-1),a),X.applyMatrix4(a.matrixWorldInverse),X.direction.normalize(),X.recast(-X.direction.dot(X.origin)).at(u/X.direction.z,I),I.applyMatrix4(a.matrixWorld);const t=F.distanceTo(I)/e;i.multiplyScalar(h),(i.lengthSq()<t**2||!s)&&i.set(0,0,0)}t.lengthSq()>0&&this._applyRotation(t.x*e,t.y*e,r),i.lengthSq()>0&&(a.position.addScaledVector(i,e),a.updateMatrixWorld())}_inertiaNeedsUpdate(){const{rotationInertia:e,dragInertia:t}=this;return 0!==e.lengthSq()||0!==t.lengthSq()}_updateZoom(){const{zoomPoint:e,zoomDirection:t,camera:r,minDistance:i,maxDistance:s,pointerTracker:n,domElement:a,minZoom:o,maxZoom:l,zoomSpeed:c,state:h}=this;let u=this.zoomDelta;if(this.zoomDelta=0,n.getLatestPoint(Y)&&(0!==u||3===h))if(this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),r.isOrthographicCamera){this._updateZoomDirection();const e=this.zoomPointSet||this._updateZoomPoint();j.unproject(r);const t=Math.pow(.95,Math.abs(.05*u));let i=u>0?1/Math.abs(t):t;i*=c,i>1?l<r.zoom*i&&(i=1):o>r.zoom*i&&(i=1),r.zoom*=i,r.updateProjectionMatrix(),e&&(C(Y,a,W),W.unproject(r),r.position.sub(W).add(j),r.updateMatrixWorld())}else{this._updateZoomDirection();const n=F.copy(t);if(this.zoomPointSet||this._updateZoomPoint()){const n=e.distanceTo(r.position);if(u<0){const e=Math.min(0,n-s);u=u*n*c*.0025,u=Math.max(u,e)}else{const e=Math.max(0,n-i);u=u*Math.max(n-i,0)*c*.0025,u=Math.min(u,e)}r.position.addScaledVector(t,u),r.updateMatrixWorld()}else{const e=this._getPointBelowCamera();if(e){const t=e.distance;n.set(0,0,-1).transformDirection(r.matrixWorld),r.position.addScaledVector(n,u*t*.01),r.updateMatrixWorld()}}}}_updateZoomDirection(){if(this.zoomDirectionSet)return;const{domElement:e,raycaster:t,camera:r,zoomDirection:i,pointerTracker:s}=this;s.getLatestPoint(Y),C(Y,e,j),E(t,j,r),i.copy(t.ray.direction).normalize(),this.zoomDirectionSet=!0}_updateZoomPoint(){const{camera:e,zoomDirectionSet:t,zoomDirection:r,raycaster:i,zoomPoint:s,pointerTracker:n,domElement:a}=this;if(this._zoomPointWasSet=!1,!t)return!1;e.isOrthographicCamera&&n.getLatestPoint(K)?(C(K,a,K),E(i,K,e)):(i.ray.origin.copy(e.position),i.ray.direction.copy(r),i.near=0,i.far=1/0);const o=this._raycast(i);return!!o&&(s.copy(o.point),this.zoomPointSet=!0,this._zoomPointWasSet=!0,!0)}_getPointBelowCamera(e=this.camera.position,t=this.up){const{raycaster:r}=this;r.ray.direction.copy(t).multiplyScalar(-1),r.ray.origin.copy(e).addScaledVector(t,1e5),r.near=0,r.far=1/0;const i=this._raycast(r);return i&&(i.distance-=1e5),i}_updatePosition(e){const{raycaster:t,camera:r,pivotPoint:i,up:s,pointerTracker:n,domElement:a,state:o,dragInertia:l}=this;if(1===o){if(n.getCenterPoint(Y),C(Y,a,Y),G.setFromNormalAndCoplanarPoint(s,i),E(t,Y,r),Math.abs(t.ray.direction.dot(s))<R){const e=Math.acos(R);V.crossVectors(t.ray.direction,s).normalize(),t.ray.direction.copy(s).applyAxisAngle(V,e).multiplyScalar(-1)}if(this.getUpDirection(i,H),Math.abs(t.ray.direction.dot(H))<P){const e=Math.acos(P);V.crossVectors(t.ray.direction,H).normalize(),t.ray.direction.copy(H).applyAxisAngle(V,e).multiplyScalar(-1)}t.ray.intersectPlane(G,F)&&(I.subVectors(i,F),r.position.add(I),r.updateMatrixWorld(),I.multiplyScalar(1/e),n.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(l.copy(I),this.inertiaStableFrames=0))}}_updateRotation(e){const{pivotPoint:t,pointerTracker:r,domElement:i,state:s,rotationInertia:n}=this;2===s&&(r.getCenterPoint(Y),r.getPreviousCenterPoint(Q),$.subVectors(Y,Q).multiplyScalar(2*Math.PI/i.clientHeight),this._applyRotation($.x,$.y,t),$.multiplyScalar(1/e),r.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(n.copy($),this.inertiaStableFrames=0))}_applyRotation(e,t,r){if(0===e&&0===t)return;const{camera:i,minAltitude:s,maxAltitude:n,rotationSpeed:a}=this,o=-e*a;let l,c=t*a;if(O.set(0,0,1).transformDirection(i.matrixWorld),B.set(1,0,0).transformDirection(i.matrixWorld),this.getUpDirection(r,H),H.dot(O)>1-1e-10)l=0;else{F.crossVectors(H,O).normalize();l=Math.sign(F.dot(B))*H.angleTo(O)}c>0?(c=Math.min(l-s,c),c=Math.max(0,c)):(c=Math.max(l-n,c),c=Math.min(0,c)),z.setFromAxisAngle(H,o),A(r,z,L),i.matrixWorld.premultiply(L),B.set(1,0,0).transformDirection(i.matrixWorld),z.setFromAxisAngle(B,-c),A(r,z,L),i.matrixWorld.premultiply(L),i.matrixWorld.decompose(i.position,i.quaternion,F)}_setFrame(e){const{up:t,camera:r,zoomPoint:s,zoomDirectionSet:n,zoomPointSet:a,scaleZoomOrientationAtEdges:o}=this;if(n&&(a||this._updateZoomPoint())){if(z.setFromUnitVectors(t,e),o){this.getUpDirection(s,F);let e=Math.max(F.dot(t)-.6,0)/.4;e=i.MathUtils.mapLinear(e,0,.5,0,1),e=Math.min(e,1),r.isOrthographicCamera&&(e*=.1),z.slerp(q,1-e)}A(s,z,L),r.updateMatrixWorld(),r.matrixWorld.premultiply(L),r.matrixWorld.decompose(r.position,r.quaternion,F),this.zoomDirectionSet=!1,this._updateZoomDirection()}t.copy(e),r.updateMatrixWorld()}_raycast(e){const{scene:t,useFallbackPlane:r,fallbackPlane:i}=this,s=e.intersectObject(t)[0]||null;if(s)return s;if(r){const t=i;if(e.ray.intersectPlane(t,F)){return{point:F.clone(),distance:e.ray.origin.distanceTo(F)}}}return null}_alignCameraUp(e,t=1){const{camera:r,state:s,pivotPoint:n,zoomPoint:a,zoomPointSet:o}=this;r.updateMatrixWorld(),O.set(0,0,-1).transformDirection(r.matrixWorld),B.set(-1,0,0).transformDirection(r.matrixWorld);let l=i.MathUtils.mapLinear(1-Math.abs(O.dot(e)),0,.2,0,1);l=i.MathUtils.clamp(l,0,1),t*=l,N.crossVectors(e,O),N.lerp(B,1-t).normalize(),z.setFromUnitVectors(B,N),r.quaternion.premultiply(z);let c=null;1===s||2===s?c=k.copy(n):o&&(c=k.copy(a)),c&&(U.copy(r.matrixWorld).invert(),F.copy(c).applyMatrix4(U),r.updateMatrixWorld(),F.applyMatrix4(r.matrixWorld),D.subVectors(c,F),r.position.add(D)),r.updateMatrixWorld()}_clampRotation(e){const{camera:t,minAltitude:r,maxAltitude:i,state:s,pivotPoint:n,zoomPoint:a,zoomPointSet:o}=this;let l,c;if(t.updateMatrixWorld(),O.set(0,0,1).transformDirection(t.matrixWorld),B.set(1,0,0).transformDirection(t.matrixWorld),e.dot(O)>1-1e-10)l=0;else{F.crossVectors(e,O);l=Math.sign(F.dot(B))*e.angleTo(O)}if(l>i)c=i;else{if(!(l<r))return;c=r}O.copy(e),z.setFromAxisAngle(B,c),O.applyQuaternion(z).normalize(),F.crossVectors(O,B).normalize(),L.makeBasis(B,F,O),t.quaternion.setFromRotationMatrix(L);let h=null;1===s||2===s?h=k.copy(n):o&&(h=k.copy(a)),h&&(U.copy(t.matrixWorld).invert(),F.copy(h).applyMatrix4(U),t.updateMatrixWorld(),F.applyMatrix4(t.matrixWorld),D.subVectors(h,F),t.position.add(D)),t.updateMatrixWorld()}}function se(e){if(!e)return null;let t=e.length,r=e.indexOf("?"),i=e.indexOf("#");-1!==r&&(t=Math.min(t,r)),-1!==i&&(t=Math.min(t,i));let s=e.lastIndexOf(".",t),n=e.lastIndexOf("/",t),a=e.indexOf("://");return-1!==a&&a+2===n||-1===s||s<n?null:e.substring(s+1,t)||null}var ne=(r(e=class{static setXRSession(e){e!==this.session&&(this.flushPending(),this.session=e)}static requestAnimationFrame(e){let t,{session:r,pending:i}=this,s=()=>{i.delete(t),e()};return t=r?r.requestAnimationFrame(s):requestAnimationFrame(s),i.set(t,e),t}static cancelAnimationFrame(e){let{pending:t,session:r}=this;t.delete(e),r?r.cancelAnimationFrame(e):cancelAnimationFrame(e)}static flushPending(){this.pending.forEach(((e,t)=>{e(),this.cancelAnimationFrame(t)}))}},"pending",new Map),r(e,"session",null),e),ae=2**30,oe=class{get unloadPriorityCallback(){return this._unloadPriorityCallback}set unloadPriorityCallback(e){1===e.length?this._unloadPriorityCallback=(t,r)=>{let i=e(t),s=e(r);return i<s?-1:+(i>s)}:this._unloadPriorityCallback=e}constructor(){this.minSize=6e3,this.maxSize=8e3,this.minBytesSize=.3*ae,this.maxBytesSize=.4*ae,this.unloadPercent=.05,this.autoMarkUnused=!0,this.cachedBytes=0,this.itemSet=new Map,this.itemList=[],this.usedSet=new Set,this.callbacks=new Map,this.unloadingHandle=-1,this.bytesMap=new Map,this.loadedSet=new Set,this._unloadPriorityCallback=null;let e=this.itemSet;this.defaultPriorityCallback=t=>e.get(t)}isFull(){return this.itemSet.size>=this.maxSize||this.cachedBytes>=this.maxBytesSize}getMemoryUsage(e){return this.bytesMap.get(e)||0}setMemoryUsage(e,t){let{bytesMap:r,itemSet:i}=this;i.has(e)&&(this.cachedBytes-=r.get(e)||0,r.set(e,t),this.cachedBytes+=t)}add(e,t){let r=this.itemSet;if(r.has(e)||this.isFull())return!1;let i=this.usedSet,s=this.itemList,n=this.callbacks;return s.push(e),i.add(e),r.set(e,Date.now()),n.set(e,t),!0}has(e){return this.itemSet.has(e)}remove(e){let t=this.usedSet,r=this.itemSet,i=this.itemList,s=this.bytesMap,n=this.callbacks,a=this.loadedSet;if(r.has(e)){this.cachedBytes-=s.get(e)||0,s.delete(e),n.get(e)(e);let o=i.indexOf(e);return i.splice(o,1),t.delete(e),r.delete(e),n.delete(e),a.delete(e),!0}return!1}setLoaded(e,t){let{itemSet:r,loadedSet:i}=this;r.has(e)&&(!0===t?i.add(e):i.delete(e))}markUsed(e){let t=this.itemSet,r=this.usedSet;t.has(e)&&!r.has(e)&&(t.set(e,Date.now()),r.add(e))}markUnused(e){this.usedSet.delete(e)}markAllUnused(){this.usedSet.clear()}isUsed(e){return this.usedSet.has(e)}unloadUnusedContent(){let{unloadPercent:e,minSize:t,maxSize:r,itemList:i,itemSet:s,usedSet:n,loadedSet:a,callbacks:o,bytesMap:l,minBytesSize:c,maxBytesSize:h}=this,u=i.length-n.size,d=i.length-a.size,p=Math.max(Math.min(i.length-t,u),0),m=this.cachedBytes-c,f=this.unloadPriorityCallback||this.defaultPriorityCallback,g=!1,y=p>0&&u>0||d&&i.length>r;if(u&&this.cachedBytes>c||d&&this.cachedBytes>h||y){i.sort(((e,t)=>{let r=n.has(e);if(r===n.has(t)){let r=a.has(e);return r===a.has(t)?-f(e,t):r?1:-1}return r?1:-1}));let d=Math.max(t*e,p*e),y=Math.ceil(Math.min(d,u,p)),v=Math.max(e*m,e*c),T=Math.min(v,m),x=0,b=0;for(;this.cachedBytes-b>h||i.length-x>r;){let e=i[x],t=l.get(e)||0;if(n.has(e)&&a.has(e)||this.cachedBytes-b-t<h&&i.length-x<=r)break;b+=t,x++}for(;b<T||x<y;){let e=i[x],t=l.get(e)||0;if(n.has(e)||this.cachedBytes-b-t<c&&x>=y)break;b+=t,x++}i.splice(0,x).forEach((e=>{this.cachedBytes-=l.get(e)||0,o.get(e)(e),l.delete(e),s.delete(e),o.delete(e),a.delete(e),n.delete(e)})),g=x<p||b<m&&x<u,g&&(g=x>0)}g&&(this.unloadingHandle=ne.requestAnimationFrame((()=>this.scheduleUnload())))}scheduleUnload(){ne.cancelAnimationFrame(this.unloadingHandle),this.scheduled||(this.scheduled=!0,queueMicrotask((()=>{this.scheduled=!1,this.unloadUnusedContent()})))}},le=class extends DOMException{constructor(){super("PriorityQueue: Item removed","AbortError")}},ce=class{get running(){return 0!==this.items.length||0!==this.currJobs}constructor(){this.maxJobs=6,this.items=[],this.callbacks=new Map,this.currJobs=0,this.scheduled=!1,this.autoUpdate=!0,this.priorityCallback=null,this._schedulingCallback=e=>{ne.requestAnimationFrame(e)},this._runjobs=()=>{this.scheduled=!1,this.tryRunJobs()}}sort(){let e=this.priorityCallback,t=this.items;null!==e&&t.sort(e)}has(e){return this.callbacks.has(e)}add(e,t){let r={callback:t,reject:null,resolve:null,promise:null};return r.promise=new Promise(((t,i)=>{let s=this.items,n=this.callbacks;r.resolve=t,r.reject=i,s.unshift(e),n.set(e,r),this.autoUpdate&&this.scheduleJobRun()})),r.promise}remove(e){let t=this.items,r=this.callbacks,i=t.indexOf(e);if(-1!==i){let s=r.get(e);s.promise.catch((e=>{if("AbortError"!==e.name)throw e})),s.reject(new le),t.splice(i,1),r.delete(e)}}removeByFilter(e){let{items:t}=this;for(let r=0;r<t.length;r++){let i=t[r];e(i)&&(this.remove(i),r--)}}tryRunJobs(){this.sort();let e=this.items,t=this.callbacks,r=this.maxJobs,i=0,s=()=>{this.currJobs--,this.autoUpdate&&this.scheduleJobRun()};for(;r>this.currJobs&&e.length>0&&i<r;){this.currJobs++,i++;let r,a=e.pop(),{callback:o,resolve:l,reject:c}=t.get(a);t.delete(a);try{r=o(a)}catch(n){c(n),s();continue}r instanceof Promise?r.then(l).catch(c).finally(s):(l(r),s())}}flush(e){let{items:t,callbacks:r}=this,i=t.indexOf(e);if(!r.has(e))return;let s,{callback:n,resolve:a,reject:o}=r.get(e);r.delete(e),t.splice(i,1);try{s=n(e)}catch(l){return void o(l)}return s instanceof Promise?s.then(a).catch(o):a(s),s}scheduleJobRun(){this.scheduled||(this.scheduled=(this._schedulingCallback(this._runjobs),!0))}},he=6378137,ue={inView:!1,error:1/0,distanceFromCamera:1/0};function de(e){return 4===e||-1===e}function pe(e,t){return me(e)&&e.traversal.lastFrameVisited===t&&e.traversal.used}function me(e){return!!e.traversal}function fe(e){let{children:t}=e,r=0===t.length||me(t[t.length-1]),i=!e.internal.hasUnrenderableContent||de(e.internal.loadingState);return r&&i}function ge(e){return e.traversal.unconditionallyRefine}function ye(e,t){if(me(e)&&(t.ensureChildrenArePreprocessed(e),e.traversal.lastFrameVisited!==t.frameCount&&(e.traversal.wasInFrustum=e.traversal.inFrustum,e.traversal.wasSetActive=e.traversal.active,e.traversal.wasSetVisible=e.traversal.visible,e.traversal.usedLastFrame=e.traversal.used,e.traversal.lastFrameVisited=t.frameCount,e.traversal.used=!1,e.traversal.inFrustum=!1,e.traversal.isLeaf=!1,e.traversal.visible=!1,e.traversal.active=!1,e.traversal.error=1/0,e.traversal.distanceFromCamera=1/0,e.traversal.allChildrenReady=!1,e.traversal.allChildrenLoaded=!1,e.traversal.kicked=!1,e.traversal.allUsedChildrenProcessed=!1,t.calculateTileViewErrorWithPlugin(e,ue),e.traversal.inFrustum=ue.inView,e.traversal.error=ue.error,e.traversal.distanceFromCamera=ue.distanceFromCamera,e.traversal.unconditionallyRefine=e.internal.hasUnrenderableContent,!e.traversal.unconditionallyRefine))){let t=e.parent;for(;t&&t.traversal.unconditionallyRefine;)t=t.parent;t&&t.geometricError<=e.geometricError&&(e.traversal.unconditionallyRefine=!0)}}function ve(e,t,r=!1){if(ye(e,t),r?t.markTileUsed(e):xe(e),ge(e)&&fe(e)){let i=e.children;for(let e=0,s=i.length;e<s;e++)ve(i[e],t,r)}}function Te(e,t){if(ye(e,t),e.traversal.usedLastFrame&&(xe(e),e.traversal.wasSetActive&&(e.traversal.active=!0),(!e.traversal.active||ge(e))&&fe(e))){let r=e.children;for(let e=0,i=r.length;e<i;e++)Te(r[e],t)}}function xe(e){e.traversal.used=!0}function be(e,t){let{frameCount:r}=t,{children:i}=e;for(let s=0,n=i.length;s<n;s++){let e=i[s];pe(e,r)&&(e.traversal.active&&(e.traversal.kicked=!0,e.traversal.active=!1),be(e,t))}}function _e(e){return!ge(e)&&(!e.internal.hasContent||de(e.internal.loadingState))}function we(e,t){if(ye(e,t),!e.traversal.inFrustum)return;let r=e.parent;if(r&&"ADD"===r.refine&&e.geometricError>0&&e.traversal.error*(r.geometricError/e.geometricError)<=t.errorTarget)return;if(!function(e,t){return!(e.traversal.error<=t.errorTarget&&!ge(e)||t.maxDepth>0&&e.internal.depth+1>=t.maxDepth||!fe(e))}(e,t))return void xe(e);let i=!1,s=!1,n=e.children;for(let a=0,o=n.length;a<o;a++){let e=n[a];we(e,t),i||(i=pe(e,t.frameCount)),s||(s=e.traversal.inFrustum)}if("REPLACE"!==e.refine||s||0===n.length){if(xe(e),"REPLACE"===e.refine&&i&&(t.loadSiblings||t.loadAncestors))for(let a=0,o=n.length;a<o;a++)ve(n[a],t)}else{e.traversal.inFrustum=!1,t.markTileUsed(e);for(let e=0,r=n.length;e<r;e++)ve(n[e],t,!0)}}function Me(e,t){let r=t.frameCount;if(!pe(e,r))return;let i=e.children,s=!1;for(let a=0,o=i.length;a<o;a++){let e=i[a];s||(s=pe(e,r))}if(s){for(let e=0,r=i.length;e<r;e++)Me(i[e],t);let s=!0;for(let e=0,t=i.length;e<t;e++){let t=i[e];if(pe(t,r)){let e=!ge(t),r=!t.internal.hasContent||de(t.internal.loadingState);e&&r||t.traversal.allChildrenLoaded||(s=!1)}}e.traversal.allChildrenLoaded=s}else e.traversal.isLeaf=!0;let n=!0;for(let a=0,o=i.length;a<o;a++){let e=i[a];pe(e,t.frameCount)&&!e.traversal.allUsedChildrenProcessed&&(n=!1)}e.traversal.allUsedChildrenProcessed=n&&fe(e)}function Se(e,t){if(!pe(e,t.frameCount))return;let r=e.children;if("REPLACE"===e.refine&&t.loadAncestors&&!e.traversal.allChildrenLoaded&&!ge(e)&&(e.traversal.isLeaf=!0),e.traversal.isLeaf){if(!ge(e)&&(e.traversal.active=!0,fe(e)&&e.internal.hasContent&&!de(e.internal.loadingState)))for(let e=0,i=r.length;e<i;e++)Te(r[e],t);return}let i=r.length>0;for(let s=0,n=r.length;s<n;s++){let e=r[s];Se(e,t),pe(e,t.frameCount)&&(!e.traversal.active||!_e(e))&&!e.traversal.allChildrenReady&&(i=!1)}e.traversal.allChildrenReady=i,"REPLACE"===e.refine&&!i&&e.traversal.wasSetActive&&_e(e)&&(e.traversal.active=!0,be(e,t))}function Ae(e,t){ye(e,t);let r=pe(e,t.frameCount);if(r&&(e.internal.hasUnrenderableContent&&(t.markTileUsed(e),t.queueTileForDownload(e)),e.internal.hasRenderableContent&&"ADD"===e.refine&&(e.traversal.active=!0),(e.traversal.active||e.traversal.kicked)&&e.internal.hasContent&&(t.markTileUsed(e),e.traversal.allUsedChildrenProcessed&&t.queueTileForDownload(e),4!==e.internal.loadingState&&(e.traversal.active=!1)),t.loadAncestors&&e.internal.hasContent&&(t.markTileUsed(e),t.queueTileForDownload(e)),e.internal.virtualChildCount>0&&e.internal.hasContent&&t.markTileUsed(e),e.traversal.visible=e.internal.hasRenderableContent&&e.traversal.active&&e.traversal.inFrustum&&4===e.internal.loadingState,t.stats.used++,e.traversal.inFrustum&&t.stats.inFrustum++),r||me(e)&&e.traversal.usedLastFrame){let i=!1,s=!1;r?(i=e.traversal.active,s=t.displayActiveTiles&&e.traversal.active||e.traversal.visible):ye(e,t),e.internal.hasRenderableContent&&4===e.internal.loadingState?(i&&t.stats.active++,s&&t.stats.visible++,e.traversal.wasSetActive!==i&&t.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,i))),e.traversal.wasSetVisible!==s&&t.invokeOnePlugin((t=>t.setTileVisible&&t.setTileVisible(e,s)))):e.internal.hasRenderableContent||(s=e.traversal.isLeaf,e.traversal.wasSetVisible!==s&&t.invokeOnePlugin((t=>t.setEmptyTileVisible&&t.setEmptyTileVisible(e,s)))),e.traversal.visible=s,e.traversal.active=i;let n=e.children;for(let e=0,r=n.length;e<r;e++){Ae(n[e],t)}}}function Ce(e,t){we(e,t),Me(e,t),Se(e,t),Ae(e,t)}function Ee(e,t=null,r=null){let i=[];for(i.push(e),i.push(null),i.push(0);i.length>0;){let e=i.pop(),s=i.pop(),n=i.pop();if(t&&t(n,s,e))return void(r&&r(n,s,e));let a=n.children;if(a)for(let t=a.length-1;t>=0;t--)i.push(a[t]),i.push(n),i.push(e+1);r&&r(n,s,e)}}var Re=Symbol("PLUGIN_REGISTERED"),Pe={inView:!0,error:0,distance:1/0},Le=(e,t)=>{let r=e.priority??1/0,i=t.priority??1/0;if(r!==i)return r>i?1:-1;if(!e.internal||!t.internal)return 0;let s=e.internal.renderer,n=t.internal.renderer,a=!s.loadAncestors,o=!n.loadAncestors;return a&&o?((e,t)=>e.traversal.used===t.traversal.used?e.traversal.inFrustum===t.traversal.inFrustum?e.internal.hasUnrenderableContent===t.internal.hasUnrenderableContent?e.traversal.distanceFromCamera===t.traversal.distanceFromCamera?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?0:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?-1:1:e.traversal.distanceFromCamera>t.traversal.distanceFromCamera?-1:1:e.internal.hasUnrenderableContent?1:-1:e.traversal.inFrustum?1:-1:e.traversal.used?1:-1)(e,t):((e,t)=>{let r=e.priority||0,i=t.priority||0;return r===i?e.traversal&&t.traversal?e.traversal.used===t.traversal.used?e.traversal.error===t.traversal.error?e.traversal.distanceFromCamera===t.traversal.distanceFromCamera?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?0:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?-1:1:e.traversal.distanceFromCamera>t.traversal.distanceFromCamera?-1:1:e.traversal.error>t.traversal.error?1:-1:e.traversal.used?1:-1:0:r>i?1:-1})(e,t)},Ue=new oe;Ue.unloadPriorityCallback=(e,t)=>e.traversal.lastFrameVisited===t.traversal.lastFrameVisited?e.internal.depthFromRenderedParent===t.internal.depthFromRenderedParent?e.internal.loadingState===t.internal.loadingState?e.internal.hasUnrenderableContent===t.internal.hasUnrenderableContent?e.traversal.error===t.traversal.error?0:e.traversal.error>t.traversal.error?-1:1:e.internal.hasUnrenderableContent?-1:1:e.internal.loadingState>t.internal.loadingState?-1:1:e.internal.depthFromRenderedParent>t.internal.depthFromRenderedParent?1:-1:e.traversal.lastFrameVisited>t.traversal.lastFrameVisited?-1:1;var Ie=new class{get running(){for(let e of this.originQueues.values())if(e.running)return!0;return!1}get maxJobsPerOrigin(){return this._maxJobsPerOrigin}set maxJobsPerOrigin(e){this._maxJobsPerOrigin=e,this.originQueues.forEach((t=>t.maxJobs=e))}get maxJobs(){return this.maxJobsPerOrigin}set maxJobs(e){this.maxJobsPerOrigin=e}get priorityCallback(){return this._priorityCallback}set priorityCallback(e){this._priorityCallback=e,this.originQueues.forEach((t=>t.priorityCallback=e))}constructor(){this.originQueues=new Map,this._itemQueues=new WeakMap,this._maxJobsPerOrigin=6,this._priorityCallback=null}add(e,t,r,i=null){this.originQueues.forEach(((e,t)=>{e.running||this.originQueues.delete(t)}));let s=null===e?null:function(e){try{let t=typeof location<"u"?location.href:void 0;return new URL(e,t).origin}catch{return null}}(e),n=this.originQueues.get(s);n||(n=new ce,n.maxJobs=this._maxJobsPerOrigin,n.priorityCallback=this._priorityCallback,this.originQueues.set(s,n));let a=this._itemQueues.get(t);if(a&&a!==n&&a.has(t))throw Error("DownloadPriorityQueue: Item is already queued with a different url origin.");this._itemQueues.set(t,n);let o=n.add(t,r);return null!==i&&(i.aborted?this.remove(t):i.addEventListener("abort",(()=>this.remove(t)),{once:!0})),o}remove(e){let t=this._itemQueues.get(e);t&&(t.remove(e),this._itemQueues.delete(e))}has(e){let t=this._itemQueues.get(e);return!(!t||!t.has(e))}};Ie.maxJobsPerOrigin=25,Ie.priorityCallback=Le;var Fe=new ce;Fe.maxJobs=5,Fe.priorityCallback=Le;var ke=new ce;ke.maxJobs=25,ke.priorityCallback=(e,t)=>{let r=e.parent,i=t.parent;return r===i?0:r?i?Le(r,i):-1:1};var De=class{get root(){let e=this.rootTileset;return e?e.root:null}get loadProgress(){let{stats:e,isLoading:t}=this,r=e.queued+e.downloading+e.parsing,i=e.inCacheSinceLoad+ +!!t;return 0===i?1:1-r/i}get downloadQueue(){return this._downloadQueue}set downloadQueue(e){e instanceof ce||(this._downloadQueue=e)}constructor(e=null){this.rootLoadingState=0,this.rootTileset=null,this.rootURL=e,this.fetchOptions={},this.plugins=[],this.queuedTiles=[],this.cachedSinceLoadComplete=new Set,this.isLoading=!1,this.processedTiles=new WeakSet,this.visibleTiles=new Set,this.activeTiles=new Set,this.usedSet=new Set,this.loadingTiles=new Set,this.lruCache=Ue,this.downloadQueue=Ie,this.parseQueue=Fe,this.processNodeQueue=ke,this.stats={inCacheSinceLoad:0,inCache:0,queued:0,downloading:0,parsing:0,loaded:0,failed:0,inFrustum:0,used:0,active:0,visible:0,tilesProcessed:0},this.frameCount=0,this._dispatchNeedsUpdateEvent=function(e){let t=null;return()=>{null===t&&(t=ne.requestAnimationFrame((()=>{t=null,e()})))}}((()=>{this.dispatchEvent({type:"needs-update"})})),this.errorTarget=16,this.errorFalloff=0,this.errorFalloffDensity=2e-4,this.displayActiveTiles=!1,this.maxDepth=1/0,this.loadSiblings=!0,this.loadAncestors=!0,this.maxTilesProcessed=250}registerPlugin(e){if(!0===e[Re])throw Error("TilesRendererBase: A plugin can only be registered to a single tileset");let t=this.plugins,r=e.priority||0,i=t.length;for(let s=0;s<t.length;s++)if((t[s].priority||0)>r){i=s;break}t.splice(i,0,e),e[Re]=!0,e.init&&e.init(this)}unregisterPlugin(e){let t=this.plugins;if("string"==typeof e&&(e=this.getPluginByName(e)),t.includes(e)){let r=t.indexOf(e);return t.splice(r,1),e.dispose&&e.dispose(),!0}return!1}getPluginByName(e){return this.plugins.find((t=>t.name===e))||null}invokeOnePlugin(e){let t=[...this.plugins,this];for(let r=0;r<t.length;r++){let i=e(t[r]);if(i)return i}return null}invokeAllPlugins(e){let t=[...this.plugins,this],r=[];for(let i=0;i<t.length;i++){let s=e(t[i]);s&&r.push(s)}return 0===r.length?null:Promise.all(r)}traverse(e,t,r=!0){this.root&&Ee(this.root,((t,...i)=>(r&&this.ensureChildrenArePreprocessed(t,!0),!!e&&e(t,...i))),t)}getAttributions(e=[]){return this.invokeAllPlugins((t=>t!==this&&t.getAttributions&&t.getAttributions(e))),e}update(){let{lruCache:e,usedSet:t,stats:r,root:i,downloadQueue:s,parseQueue:n,processNodeQueue:a}=this;if(0===this.rootLoadingState&&(this.rootLoadingState=2,this.invokeOnePlugin((e=>e.loadRootTileset&&e.loadRootTileset())).then((e=>{let t=this.rootURL;null!==t&&this.invokeAllPlugins((e=>t=e.preprocessURL?e.preprocessURL(t,null):t)),this.rootLoadingState=4,this.rootTileset=e,this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-tileset",tileset:e,url:t}),this.dispatchEvent({type:"load-root-tileset",tileset:e,url:t})})).catch((e=>{this.rootLoadingState=-1,this.rootTileset=null,this.dispatchEvent({type:"load-error",tile:null,error:e,url:this.rootURL})}))),!i)return;let o=null;if(this.invokeAllPlugins((e=>{if(e.doTilesNeedUpdate){let t=e.doTilesNeedUpdate();o=null===o?t:!(!o&&!t)}})),!1===o)return this.dispatchEvent({type:"update-before"}),void this.dispatchEvent({type:"update-after"});this.dispatchEvent({type:"update-before"}),r.inFrustum=0,r.used=0,r.active=0,r.visible=0,r.tilesProcessed=0,this.frameCount++,t.forEach((t=>e.markUnused(t))),t.clear(),this.prepareForTraversal(),Ce(i,this),this.removeUnusedPendingTiles();let l=this.queuedTiles;l.sort(e.unloadPriorityCallback);for(let c=0,h=l.length;c<h&&!e.isFull();c++)this.requestTileContents(l[c]);l.length=0,e.scheduleUnload(),!1===(s.running||n.running||a.running)&&!0===this.isLoading&&(this.cachedSinceLoadComplete.clear(),r.inCacheSinceLoad=0,this.dispatchEvent({type:"tiles-load-end"}),this.isLoading=!1),this.dispatchEvent({type:"update-after"})}resetFailedTiles(){-1===this.rootLoadingState&&(this.rootLoadingState=0);let e=this.stats;0!==e.failed&&(this.traverse((e=>{-1===e.internal.loadingState&&(e.internal.loadingState=0)}),null,!1),e.failed=0)}calculateTileViewErrorWithPlugin(e,t){this.calculateTileViewError(e,t);let{errorFalloff:r,errorFalloffDensity:i}=this;if(r>0&&Number.isFinite(t.distanceFromCamera)){let e=t.distanceFromCamera*i;t.error-=r*(1-Math.exp(-e*e))}let s=null,n=0,a=1/0;this.invokeAllPlugins((t=>{t!==this&&t.calculateTileViewError&&(Pe.inView=!0,Pe.error=0,Pe.distance=1/0,t.calculateTileViewError(e,Pe)&&(null===s&&(s=!0),s&&(s=Pe.inView),Pe.inView&&(a=Math.min(a,Pe.distance),n=Math.max(n,Pe.error))))})),t.inView&&!1!==s?(t.error=Math.max(t.error,n),t.distanceFromCamera=Math.min(t.distanceFromCamera,a)):s?(t.inView=!0,t.error=n,t.distanceFromCamera=a):t.inView=!1}dispose(){[...this.plugins].forEach((e=>{this.unregisterPlugin(e)}));let e=this.lruCache,t=[];this.traverse((e=>(t.push(e),!1)),null,!1);for(let r=0,i=t.length;r<i;r++)e.remove(t[r]);this.stats={queued:0,parsing:0,downloading:0,failed:0,inFrustum:0,traversed:0,used:0,active:0,visible:0},this.frameCount=0,this.loadingTiles.clear()}calculateBytesUsed(e,t){return 0}dispatchEvent(e){}addEventListener(e,t){}removeEventListener(e,t){}parseTile(e,t,r){return null}prepareForTraversal(){}disposeTile(e){e.traversal.visible&&(e.internal.hasRenderableContent?this.invokeOnePlugin((t=>t.setTileVisible&&t.setTileVisible(e,!1))):this.invokeOnePlugin((t=>t.setEmptyTileVisible&&t.setEmptyTileVisible(e,!1))),e.traversal.visible=!1),e.traversal.active&&e.internal.hasRenderableContent&&this.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,!1))),e.traversal.active=!1;let{scene:t}=e.engineData;t&&this.dispatchEvent({type:"dispose-model",scene:t,tile:e})}preprocessNode(e,t,r=null){var i;if(this.processedTiles.add(e),this.stats.tilesProcessed++,e.content&&(!("uri"in e.content)&&"url"in e.content&&(e.content.uri=e.content.url,delete e.content.url),e.content.boundingVolume&&!("box"in e.content.boundingVolume||"sphere"in e.content.boundingVolume||"region"in e.content.boundingVolume)&&delete e.content.boundingVolume),e.parent=r,e.children=e.children||[],e.internal={hasContent:!1,hasRenderableContent:!1,hasUnrenderableContent:!1,loadingState:0,basePath:t,depth:-1,depthFromRenderedParent:-1,isVirtual:!1,virtualChildCount:0,renderer:this,...e.internal},null==(i=e.content)?void 0:i.uri){let t=se(e.content.uri),r=!(!t||!/json$/.test(t));e.internal.hasContent=!0,e.internal.hasUnrenderableContent=r,e.internal.hasRenderableContent=!r}else e.internal.hasContent=!1,e.internal.hasUnrenderableContent=!1,e.internal.hasRenderableContent=!1;r?(e.internal.depth=r.internal.depth+1,e.internal.depthFromRenderedParent=r.internal.depthFromRenderedParent+ +!!e.internal.hasRenderableContent):(e.internal.depth=0,e.internal.depthFromRenderedParent=+!!e.internal.hasRenderableContent),e.traversal={distanceFromCamera:1/0,error:1/0,inFrustum:!1,wasInFrustum:!1,isLeaf:!1,used:!1,usedLastFrame:!1,visible:!1,wasSetVisible:!1,active:!1,wasSetActive:!1,allChildrenReady:!1,allChildrenLoaded:!1,kicked:!1,allUsedChildrenProcessed:!1,lastFrameVisited:-1},e.refine=null===r?e.refine||"REPLACE":e.refine||r.refine,e.engineData={scene:null,metadata:null,boundingVolume:null},Object.defineProperty(e,"cached",{get(){return this.engineData},enumerable:!1,configurable:!0}),this.invokeAllPlugins((i=>{i!==this&&i.preprocessNode&&i.preprocessNode(e,t,r)}))}setTileActive(e,t){t?this.activeTiles.add(e):this.activeTiles.delete(e)}setTileVisible(e,t){t?this.visibleTiles.add(e):this.visibleTiles.delete(e),this.dispatchEvent({type:"tile-visibility-change",scene:e.engineData.scene,tile:e,visible:t})}calculateTileViewError(e,t){}removeUnusedPendingTiles(){let{lruCache:e,loadingTiles:t}=this,r=[];for(let i of t)!e.isUsed(i)&&1===i.internal.loadingState&&r.push(i);for(let i=0;i<r.length;i++)e.remove(r[i])}queueTileForDownload(e){0!==e.internal.loadingState||this.lruCache.isFull()||this.queuedTiles.push(e)}markTileUsed(e){this.usedSet.add(e),this.lruCache.markUsed(e)}fetchData(e,t){return fetch(e,t)}ensureChildrenArePreprocessed(e,t=this.stats.tilesProcessed<this.maxTilesProcessed){let r=e.children;if(0===r.length||r[r.length-1].traversal)return;let i=t=>{for(let r=0,i=t.length;r<i;r++){let i=t[r];i&&!i.traversal&&this.preprocessNode(i,e.internal.basePath,e)}};t?(this.processNodeQueue.remove(e),i(r)):this.processNodeQueue.has(e)||this.processNodeQueue.add(e,(e=>{i(e.children),this._dispatchNeedsUpdateEvent()}))}getBytesUsed(e){let t=0;return this.invokeAllPlugins((r=>{r.calculateBytesUsed&&(t+=r.calculateBytesUsed(e,e.engineData.scene)||0)})),t}recalculateBytesUsed(e=null){let{lruCache:t,processedTiles:r}=this;null===e?t.itemSet.forEach((e=>{r.has(e)&&t.setMemoryUsage(e,this.getBytesUsed(e))})):t.setMemoryUsage(e,this.getBytesUsed(e))}preprocessTileset(e,t,r=null){let[i,s]=e.asset.version.split(".").map((e=>parseInt(e))),n=t.replace(/\/[^/]*$/,"");n=new URL(n,window.location.href).toString(),this.preprocessNode(e.root,n,r)}loadRootTileset(){let e=this.rootURL;return this.invokeAllPlugins((t=>e=t.preprocessURL?t.preprocessURL(e,null):e)),this.invokeOnePlugin((t=>t.fetchData&&t.fetchData(e,this.fetchOptions))).then((t=>{if(!(t instanceof Response))return t;if(t.ok)return t.json();throw Error(`TilesRenderer: Failed to load tileset "${e}" with status ${t.status} : ${t.statusText}`)})).then((t=>(this.preprocessTileset(t,e),t)))}requestTileContents(e){if(0!==e.internal.loadingState)return;let t=!1,r=null,i=new URL(e.content.uri,e.internal.basePath+"/").toString();this.invokeAllPlugins((t=>i=t.preprocessURL?t.preprocessURL(i,e):i));let s=this.stats,n=this.lruCache,a=this.downloadQueue,o=this.parseQueue,l=this.loadingTiles,c=se(i),h=new AbortController,u=h.signal;return n.add(e,(r=>{h.abort(),t?r.children.length=0:this.invokeAllPlugins((e=>{e.disposeTile&&e.disposeTile(r)})),s.inCache--,this.cachedSinceLoadComplete.has(e)&&(this.cachedSinceLoadComplete.delete(e),s.inCacheSinceLoad--),1===r.internal.loadingState?s.queued--:2===r.internal.loadingState?s.downloading--:3===r.internal.loadingState?s.parsing--:4===r.internal.loadingState&&s.loaded--,r.internal.loadingState=0,o.remove(r),a.remove(r),l.delete(r)}))?(this.isLoading||(this.isLoading=!0,this.dispatchEvent({type:"tiles-load-start"})),n.setMemoryUsage(e,this.getBytesUsed(e)),this.cachedSinceLoadComplete.add(e),s.inCacheSinceLoad++,s.inCache++,s.queued++,e.internal.loadingState=1,l.add(e),a.add(i,e,(t=>{if(u.aborted)return Promise.resolve();e.internal.loadingState=2,s.downloading++,s.queued--;let r=this.invokeOnePlugin((e=>e.fetchData&&e.fetchData(i,{...this.fetchOptions,signal:u})));return this.dispatchEvent({type:"tile-download-start",tile:e,url:i,get uri(){return this.url}}),r})).then((e=>{if(!u.aborted){if(!(e instanceof Response))return e;if(e.ok)return"json"===c?e.json():e.arrayBuffer();throw Error(`Failed to load model with error code ${e.status}`)}})).then((n=>{if(!u.aborted)return s.downloading--,s.parsing++,e.internal.loadingState=3,o.add(e,(s=>u.aborted?Promise.resolve():"json"===c&&n.root?(this.preprocessTileset(n,i,e),e.children.push(n.root),r=n,t=!0,Promise.resolve()):this.invokeOnePlugin((e=>e.parseTile&&e.parseTile(n,s,c,i,u)))))})).then((()=>{if(u.aborted)return;s.parsing--,s.loaded++,e.internal.loadingState=4,l.delete(e),n.setLoaded(e,!0);let a=this.getBytesUsed(e);0===n.getMemoryUsage(e)&&a>0&&n.isFull()?n.remove(e):(n.setMemoryUsage(e,a),this.dispatchEvent({type:"needs-update"}),t&&this.dispatchEvent({type:"load-tileset",tileset:r,url:i}),e.engineData.scene&&this.dispatchEvent({type:"load-model",scene:e.engineData.scene,tile:e,url:i}))})).catch((t=>{u.aborted||("AbortError"===t.name?n.remove(e):(o.remove(e),a.remove(e),1===e.internal.loadingState?s.queued--:2===e.internal.loadingState?s.downloading--:3===e.internal.loadingState?s.parsing--:4===e.internal.loadingState&&s.loaded--,s.failed++,e.internal.loadingState=-1,l.delete(e),n.setLoaded(e,!0),this.dispatchEvent({type:"load-error",tile:e,error:t,url:i})))}))):void 0}};function Oe(e){if(null===e||e.byteLength<4)return"";let t;if(t=e instanceof DataView?e:new DataView(e),"{"===String.fromCharCode(t.getUint8(0)))return null;let r="";for(let i=0;i<4;i++)r+=String.fromCharCode(t.getUint8(i));return r}var Be=new TextDecoder;function Ne(e){return Be.decode(e)}function Ve(e){return e.replace(/[\\/][^\\/]+$/,"")+"/"}var ze=class{constructor(){this.fetchOptions={},this.workingPath=""}loadAsync(e){return fetch(e,this.fetchOptions).then((t=>{if(!t.ok)throw Error(`Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()})).then((t=>(""===this.workingPath&&(this.workingPath=Ve(e)),this.parse(t))))}resolveExternalURL(e){return new URL(e,this.workingPath).href}parse(e){throw Error("LoaderBase: Parse not implemented.")}};function Ge(e,t,r,i,s,n){let a;switch(i){case"SCALAR":a=1;break;case"VEC2":a=2;break;case"VEC3":a=3;break;case"VEC4":a=4;break;default:throw Error(`FeatureTable : Feature type not provided for "${n}".`)}let o,l=r*a;switch(s){case"BYTE":o=new Int8Array(e,t,l);break;case"UNSIGNED_BYTE":o=new Uint8Array(e,t,l);break;case"SHORT":o=new Int16Array(e,t,l);break;case"UNSIGNED_SHORT":o=new Uint16Array(e,t,l);break;case"INT":o=new Int32Array(e,t,l);break;case"UNSIGNED_INT":o=new Uint32Array(e,t,l);break;case"FLOAT":o=new Float32Array(e,t,l);break;case"DOUBLE":o=new Float64Array(e,t,l);break;default:throw Error(`FeatureTable : Feature component type not provided for "${n}".`)}return o}var He=class{constructor(e,t,r,i){this.buffer=e,this.binOffset=t+r,this.binLength=i;let s=null;if(0!==r){let i=new Uint8Array(e,t,r);s=JSON.parse(Ne(i))}else s={};this.header=s}getKeys(){return Object.keys(this.header).filter((e=>"extensions"!==e))}getData(e,t,r=null,i=null){let s=this.header;if(!(e in s))return null;let n=s[e];if(!(n instanceof Object)||Array.isArray(n))return n;{let{buffer:s,binOffset:a,binLength:o}=this,l=n.byteOffset||0,c=n.type||i,h=n.componentType||r;if("type"in n&&i&&n.type!==i)throw Error("FeatureTable: Specified type does not match expected type.");let u=a+l,d=Ge(s,u,t,c,h,e);if(u+d.byteLength>a+o)throw Error("FeatureTable: Feature data read outside binary body length.");return d}}getBuffer(e,t){let{buffer:r,binOffset:i}=this;return r.slice(i+e,i+e+t)}},je=class{constructor(e){this.batchTable=e;let t=e.header.extensions["3DTILES_batch_table_hierarchy"];this.classes=t.classes;for(let i of this.classes){let e=i.instances;for(let t in e)i.instances[t]=this._parseProperty(e[t],i.length,t)}if(this.instancesLength=t.instancesLength,this.classIds=this._parseProperty(t.classIds,this.instancesLength,"classIds"),t.parentCounts?this.parentCounts=this._parseProperty(t.parentCounts,this.instancesLength,"parentCounts"):this.parentCounts=Array(this.instancesLength).fill(1),t.parentIds){let e=this.parentCounts.reduce(((e,t)=>e+t),0);this.parentIds=this._parseProperty(t.parentIds,e,"parentIds")}else this.parentIds=null;this.instancesIds=[];let r={};for(let i of this.classIds)r[i]=r[i]??0,this.instancesIds.push(r[i]),r[i]++}_parseProperty(e,t,r){if(Array.isArray(e))return e;{let{buffer:i,binOffset:s}=this.batchTable;return Ge(i,s+e.byteOffset,t,"SCALAR",e.componentType||"UNSIGNED_SHORT",r)}}getDataFromId(e,t={}){let r=this.parentCounts[e];if(this.parentIds&&r>0){let i=0;for(let t=0;t<e;t++)i+=this.parentCounts[t];for(let s=0;s<r;s++){let r=this.parentIds[i+s];r!==e&&this.getDataFromId(r,t)}}let i=this.classIds[e],s=this.classes[i].instances,n=this.classes[i].name,a=this.instancesIds[e];for(let o in s)t[n]=t[n]||{},t[n][o]=s[o][a];return t}},We=class extends He{constructor(e,t,r,i,s){super(e,r,i,s),this.count=t,this.extensions={};let n=this.header.extensions;n&&n["3DTILES_batch_table_hierarchy"]&&(this.extensions["3DTILES_batch_table_hierarchy"]=new je(this))}getDataFromId(e,t={}){if(e<0||e>=this.count)throw Error(`BatchTable: id value "${e}" out of bounds for "${this.count}" features number.`);for(let r of this.getKeys())t[r]=super.getData(r,this.count)[e];for(let r in this.extensions){let i=this.extensions[r];i.getDataFromId instanceof Function&&(t[r]=t[r]||{},i.getDataFromId(e,t[r]))}return t}getPropertyArray(e){return super.getData(e,this.count)}},qe=class extends ze{parse(e){let t=new DataView(e),r=(Oe(t),t.getUint32(4,!0)),i=t.getUint32(8,!0),s=t.getUint32(12,!0),n=t.getUint32(16,!0),a=t.getUint32(20,!0),o=t.getUint32(24,!0),l=new He(e.slice(28,28+s+n),0,s,n),c=28+s+n,h=new We(e.slice(c,c+a+o),l.getData("BATCH_LENGTH"),0,a,o),u=c+a+o;return{version:r,featureTable:l,batchTable:h,glbBytes:new Uint8Array(e,u,i-u)}}},Xe=class extends ze{parse(e){let t=new DataView(e),r=(Oe(t),t.getUint32(4,!0)),i=t.getUint32(8,!0),s=t.getUint32(12,!0),n=t.getUint32(16,!0),a=t.getUint32(20,!0),o=t.getUint32(24,!0),l=t.getUint32(28,!0),c=new He(e.slice(32,32+s+n),0,s,n),h=32+s+n,u=new We(e.slice(h,h+a+o),c.getData("INSTANCES_LENGTH"),0,a,o),d=h+a+o,p=new Uint8Array(e,d,i-d),m=null,f=null,g=null;if(l)m=p,f=Promise.resolve();else{let e=this.resolveExternalURL(Ne(p));g=Ve(e),f=fetch(e,this.fetchOptions).then((t=>{if(!t.ok)throw Error(`I3DMLoaderBase : Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()})).then((e=>{m=new Uint8Array(e)}))}return f.then((()=>({version:r,featureTable:c,batchTable:u,glbBytes:m,gltfWorkingPath:g})))}},Ke=class extends ze{parse(e){let t=new DataView(e),r=(Oe(t),t.getUint32(4,!0)),i=(t.getUint32(8,!0),t.getUint32(12,!0)),s=t.getUint32(16,!0),n=t.getUint32(20,!0),a=t.getUint32(24,!0),o=new He(e.slice(28,28+i+s),0,i,s),l=28+i+s,c=new We(e.slice(l,l+n+a),o.getData("BATCH_LENGTH")||o.getData("POINTS_LENGTH"),0,n,a);return Promise.resolve({version:r,featureTable:o,batchTable:c})}},Ye=class extends ze{parse(e){let t=new DataView(e),r=(Oe(t),t.getUint32(4,!0)),i=(t.getUint32(8,!0),t.getUint32(12,!0)),s=[],n=16;for(let a=0;a<i;a++){let t=new DataView(e,n,12),r=Oe(t),i=t.getUint32(4,!0),a=t.getUint32(8,!0),o=new Uint8Array(e,n,a);s.push({type:r,buffer:o,version:i}),n+=a}return{version:r,tiles:s}}};function Qe(e,t){if(t===i.TrianglesDrawMode)return e;if(t===i.TriangleFanDrawMode||t===i.TriangleStripDrawMode){let r=e.getIndex();if(null===r){const t=[],i=e.getAttribute("position");if(void 0===i)return e;for(let e=0;e<i.count;e++)t.push(e);e.setIndex(t),r=e.getIndex()}const s=r.count-2,n=[];if(t===i.TriangleFanDrawMode)for(let e=1;e<=s;e++)n.push(r.getX(0)),n.push(r.getX(e)),n.push(r.getX(e+1));else for(let e=0;e<s;e++)e%2==0?(n.push(r.getX(e)),n.push(r.getX(e+1)),n.push(r.getX(e+2))):(n.push(r.getX(e+2)),n.push(r.getX(e+1)),n.push(r.getX(e)));return n.length,e.setIndex(n),e.clearGroups(),e}return e}function $e(e){const t=new Map,r=new Map,i=e.clone();return Ze(e,i,(function(e,i){t.set(i,e),r.set(e,i)})),i.traverse((function(e){if(!e.isSkinnedMesh)return;const i=e,s=t.get(e),n=s.skeleton.bones;i.skeleton=s.skeleton.clone(),i.bindMatrix.copy(s.bindMatrix),i.skeleton.bones=n.map((function(e){return r.get(e)})),i.bind(i.skeleton,i.bindMatrix)})),i}function Ze(e,t,r){r(e,t);for(let i=0;i<e.children.length;i++)Ze(e.children[i],t.children[i],r)}class Je extends i.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register((function(e){return new at(e)})),this.register((function(e){return new ot(e)})),this.register((function(e){return new gt(e)})),this.register((function(e){return new yt(e)})),this.register((function(e){return new vt(e)})),this.register((function(e){return new ct(e)})),this.register((function(e){return new ht(e)})),this.register((function(e){return new ut(e)})),this.register((function(e){return new dt(e)})),this.register((function(e){return new nt(e)})),this.register((function(e){return new pt(e)})),this.register((function(e){return new lt(e)})),this.register((function(e){return new ft(e)})),this.register((function(e){return new mt(e)})),this.register((function(e){return new it(e)})),this.register((function(e){return new Tt(e,rt.EXT_MESHOPT_COMPRESSION)})),this.register((function(e){return new Tt(e,rt.KHR_MESHOPT_COMPRESSION)})),this.register((function(e){return new xt(e)}))}load(e,t,r,s){const n=this;let a;if(""!==this.resourcePath)a=this.resourcePath;else if(""!==this.path){const t=i.LoaderUtils.extractUrlBase(e);a=i.LoaderUtils.resolveURL(t,this.path)}else a=i.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const o=function(t){s&&s(t),n.manager.itemError(e),n.manager.itemEnd(e)},l=new i.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,(function(r){try{n.parse(r,a,(function(r){t(r),n.manager.itemEnd(e)}),o)}catch(i){o(i)}}),r,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,r,i){let s;const n={},a={},o=new TextDecoder;if("string"==typeof e)s=JSON.parse(e);else if(e instanceof ArrayBuffer){if(o.decode(new Uint8Array(e,0,4))===bt){try{n[rt.KHR_BINARY_GLTF]=new Mt(e)}catch(c){return void(i&&i(c))}s=JSON.parse(n[rt.KHR_BINARY_GLTF].content)}else s=JSON.parse(o.decode(e))}else s=e;if(void 0===s.asset||s.asset.version[0]<2)return void(i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const l=new Yt(s,{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 h=0;h<this.pluginCallbacks.length;h++){const e=this.pluginCallbacks[h](l);e.name,a[e.name]=e,n[e.name]=!0}if(s.extensionsUsed)for(let h=0;h<s.extensionsUsed.length;++h){const e=s.extensionsUsed[h],t=s.extensionsRequired||[];switch(e){case rt.KHR_MATERIALS_UNLIT:n[e]=new st;break;case rt.KHR_DRACO_MESH_COMPRESSION:n[e]=new St(s,this.dracoLoader);break;case rt.KHR_TEXTURE_TRANSFORM:n[e]=new At;break;case rt.KHR_MESH_QUANTIZATION:n[e]=new Ct;break;default:t.indexOf(e)>=0&&a[e]}}l.setExtensions(n),l.setPlugins(a),l.parse(r,i)}parseAsync(e,t){const r=this;return new Promise((function(i,s){r.parse(e,t,i,s)}))}}function et(){let e={};return{get:function(t){return e[t]},add:function(t,r){e[t]=r},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function tt(e,t,r){const i=e.json.materials[t];return i.extensions&&i.extensions[r]?i.extensions[r]:null}const rt={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",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class it{constructor(e){this.parser=e,this.name=rt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let r=0,i=t.length;r<i;r++){const i=t[r];i.extensions&&i.extensions[this.name]&&void 0!==i.extensions[this.name].light&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,r="light:"+e;let s=t.cache.get(r);if(s)return s;const n=t.json,a=((n.extensions&&n.extensions[this.name]||{}).lights||[])[e];let o;const l=new i.Color(16777215);void 0!==a.color&&l.setRGB(a.color[0],a.color[1],a.color[2],i.LinearSRGBColorSpace);const c=void 0!==a.range?a.range:0;switch(a.type){case"directional":o=new i.DirectionalLight(l),o.target.position.set(0,0,-1),o.add(o.target);break;case"point":o=new i.PointLight(l),o.distance=c;break;case"spot":o=new i.SpotLight(l),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=void 0!==a.spot.innerConeAngle?a.spot.innerConeAngle:0,a.spot.outerConeAngle=void 0!==a.spot.outerConeAngle?a.spot.outerConeAngle:Math.PI/4,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return o.position.set(0,0,0),Ht(o,a),void 0!==a.intensity&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||"light_"+e),s=Promise.resolve(o),t.cache.add(r,s),s}getDependency(e,t){if("light"===e)return this._loadLight(t)}createNodeAttachment(e){const t=this,r=this.parser,i=r.json.nodes[e],s=(i.extensions&&i.extensions[this.name]||{}).light;return void 0===s?null:this._loadLight(s).then((function(e){return r._getNodeRef(t.cache,s,e)}))}}let st=class{constructor(){this.name=rt.KHR_MATERIALS_UNLIT}getMaterialType(){return i.MeshBasicMaterial}extendParams(e,t,r){const s=[];e.color=new i.Color(1,1,1),e.opacity=1;const n=t.pbrMetallicRoughness;if(n){if(Array.isArray(n.baseColorFactor)){const t=n.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],i.LinearSRGBColorSpace),e.opacity=t[3]}void 0!==n.baseColorTexture&&s.push(r.assignTexture(e,"map",n.baseColorTexture,i.SRGBColorSpace))}return Promise.all(s)}},nt=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);return null===r||void 0!==r.emissiveStrength&&(t.emissiveIntensity=r.emissiveStrength),Promise.resolve()}},at=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const s=[];if(void 0!==r.clearcoatFactor&&(t.clearcoat=r.clearcoatFactor),void 0!==r.clearcoatTexture&&s.push(this.parser.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),void 0!==r.clearcoatRoughnessFactor&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),void 0!==r.clearcoatRoughnessTexture&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),void 0!==r.clearcoatNormalTexture&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),void 0!==r.clearcoatNormalTexture.scale)){const e=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new i.Vector2(e,e)}return Promise.all(s)}},ot=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_DISPERSION}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);return null===r||(t.dispersion=void 0!==r.dispersion?r.dispersion:0),Promise.resolve()}},lt=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const i=[];return void 0!==r.iridescenceFactor&&(t.iridescence=r.iridescenceFactor),void 0!==r.iridescenceTexture&&i.push(this.parser.assignTexture(t,"iridescenceMap",r.iridescenceTexture)),void 0!==r.iridescenceIor&&(t.iridescenceIOR=r.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==r.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),void 0!==r.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),void 0!==r.iridescenceThicknessTexture&&i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(i)}},ct=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_SHEEN}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const s=[];if(t.sheenColor=new i.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,void 0!==r.sheenColorFactor){const e=r.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],i.LinearSRGBColorSpace)}return void 0!==r.sheenRoughnessFactor&&(t.sheenRoughness=r.sheenRoughnessFactor),void 0!==r.sheenColorTexture&&s.push(this.parser.assignTexture(t,"sheenColorMap",r.sheenColorTexture,i.SRGBColorSpace)),void 0!==r.sheenRoughnessTexture&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(s)}},ht=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const i=[];return void 0!==r.transmissionFactor&&(t.transmission=r.transmissionFactor),void 0!==r.transmissionTexture&&i.push(this.parser.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(i)}},ut=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_VOLUME}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const s=[];t.thickness=void 0!==r.thicknessFactor?r.thicknessFactor:0,void 0!==r.thicknessTexture&&s.push(this.parser.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;const n=r.attenuationColor||[1,1,1];return t.attenuationColor=(new i.Color).setRGB(n[0],n[1],n[2],i.LinearSRGBColorSpace),Promise.all(s)}},dt=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_IOR}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);return null===r||(t.ior=void 0!==r.ior?r.ior:1.5,0===t.ior&&(t.ior=1e3)),Promise.resolve()}},pt=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_SPECULAR}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const s=[];t.specularIntensity=void 0!==r.specularFactor?r.specularFactor:1,void 0!==r.specularTexture&&s.push(this.parser.assignTexture(t,"specularIntensityMap",r.specularTexture));const n=r.specularColorFactor||[1,1,1];return t.specularColor=(new i.Color).setRGB(n[0],n[1],n[2],i.LinearSRGBColorSpace),void 0!==r.specularColorTexture&&s.push(this.parser.assignTexture(t,"specularColorMap",r.specularColorTexture,i.SRGBColorSpace)),Promise.all(s)}},mt=class{constructor(e){this.parser=e,this.name=rt.EXT_MATERIALS_BUMP}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const i=[];return t.bumpScale=void 0!==r.bumpFactor?r.bumpFactor:1,void 0!==r.bumpTexture&&i.push(this.parser.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(i)}},ft=class{constructor(e){this.parser=e,this.name=rt.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return null!==tt(this.parser,e,this.name)?i.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const r=tt(this.parser,e,this.name);if(null===r)return Promise.resolve();const i=[];return void 0!==r.anisotropyStrength&&(t.anisotropy=r.anisotropyStrength),void 0!==r.anisotropyRotation&&(t.anisotropyRotation=r.anisotropyRotation),void 0!==r.anisotropyTexture&&i.push(this.parser.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(i)}};class gt{constructor(e){this.parser=e,this.name=rt.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,r=t.json,i=r.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const s=i.extensions[this.name],n=t.options.ktx2Loader;if(!n){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,n)}}class yt{constructor(e){this.parser=e,this.name=rt.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,r=this.parser,i=r.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const n=s.extensions[t],a=i.images[n.source];let o=r.textureLoader;if(a.uri){const e=r.options.manager.getHandler(a.uri);null!==e&&(o=e)}return r.loadTextureImage(e,n.source,o)}}class vt{constructor(e){this.parser=e,this.name=rt.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,r=this.parser,i=r.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const n=s.extensions[t],a=i.images[n.source];let o=r.textureLoader;if(a.uri){const e=r.options.manager.getHandler(a.uri);null!==e&&(o=e)}return r.loadTextureImage(e,n.source,o)}}class Tt{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const e=r.extensions[this.name],i=this.parser.getDependency("buffer",e.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.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(t){const r=e.byteOffset||0,i=e.byteLength||0,n=e.count,a=e.byteStride,o=new Uint8Array(t,r,i);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(n,a,o,e.mode,e.filter).then((function(e){return e.buffer})):s.ready.then((function(){const t=new ArrayBuffer(n*a);return s.decodeGltfBuffer(new Uint8Array(t),n,a,o,e.mode,e.filter),t}))}))}return null}}let xt=class{constructor(e){this.name=rt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||void 0===r.mesh)return null;const s=t.meshes[r.mesh];for(const i of s.primitives)if(i.mode!==Lt.TRIANGLES&&i.mode!==Lt.TRIANGLE_STRIP&&i.mode!==Lt.TRIANGLE_FAN&&void 0!==i.mode)return null;const n=r.extensions[this.name].attributes,a=[],o={};for(const i in n)a.push(this.parser.getDependency("accessor",n[i]).then((e=>(o[i]=e,o[i]))));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then((e=>{const t=e.pop(),r=t.isGroup?t.children:[t],s=e[0].count,n=[];for(const a of r){const e=new i.Matrix4,t=new i.Vector3,r=new i.Quaternion,l=new i.Vector3(1,1,1),c=new i.InstancedMesh(a.geometry,a.material,s);for(let i=0;i<s;i++)o.TRANSLATION&&t.fromBufferAttribute(o.TRANSLATION,i),o.ROTATION&&r.fromBufferAttribute(o.ROTATION,i),o.SCALE&&l.fromBufferAttribute(o.SCALE,i),c.setMatrixAt(i,e.compose(t,r,l));let h=null;for(const s in o)if("_COLOR_0"===s){const e=o[s];c.instanceColor=new i.InstancedBufferAttribute(e.array,e.itemSize,e.normalized)}else if("TRANSLATION"!==s&&"ROTATION"!==s&&"SCALE"!==s){if(null===h){const e=c.geometry;h=new i.BufferGeometry,h.name=e.name;for(const t in e.attributes)h.setAttribute(t,e.attributes[t]);for(const t in e.morphAttributes)h.morphAttributes[t]=e.morphAttributes[t];null!==e.index&&h.setIndex(e.index),h.morphTargetsRelative=e.morphTargetsRelative;for(const t of e.groups)h.addGroup(t.start,t.count,t.materialIndex);null!==e.boundingBox&&(h.boundingBox=e.boundingBox.clone()),null!==e.boundingSphere&&(h.boundingSphere=e.boundingSphere.clone()),h.drawRange.start=e.drawRange.start,h.drawRange.count=e.drawRange.count,h.userData=Object.assign({},e.userData),c.geometry=h}const e=o[s];h.setAttribute(s,new i.InstancedBufferAttribute(e.array,e.itemSize,e.normalized))}i.Object3D.prototype.copy.call(c,a),this.parser.assignFinalMaterial(c),n.push(c)}return t.isGroup?(t.clear(),t.add(...n),t):n[0]})))}};const bt="glTF",_t=1313821514,wt=5130562;class Mt{constructor(e){this.name=rt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==bt)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-12,s=new DataView(e,12);let n=0;for(;n<i;){const t=s.getUint32(n,!0);n+=4;const i=s.getUint32(n,!0);if(n+=4,i===_t){const i=new Uint8Array(e,12+n,t);this.content=r.decode(i)}else if(i===wt){const r=12+n;this.body=e.slice(r,r+t)}n+=t}if(null===this.content)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class St{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=rt.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const r=this.json,s=this.dracoLoader,n=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const i in a){const e=Dt[i]||i.toLowerCase();o[e]=a[i]}for(const i in e.attributes){const t=Dt[i]||i.toLowerCase();if(void 0!==a[i]){const s=r.accessors[e.attributes[i]],n=Ut[s.componentType];c[t]=n.name,l[t]=!0===s.normalized}}return t.getDependency("bufferView",n).then((function(e){return new Promise((function(t,r){s.decodeDracoFile(e,(function(e){for(const t in e.attributes){const r=e.attributes[t],i=l[t];void 0!==i&&(r.normalized=i)}t(e)}),o,c,i.LinearSRGBColorSpace,r)}))}))}}class At{constructor(){this.name=rt.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){if((void 0===t.texCoord||t.texCoord===e.channel)&&void 0===t.offset&&void 0===t.rotation&&void 0===t.scale)return e;if(e=e.clone(),void 0!==t.texCoord&&(e.channel=t.texCoord),void 0!==t.offset&&e.offset.fromArray(t.offset),void 0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.scale&&e.repeat.fromArray(t.scale),void 0!==t.rotation){const t=Math.cos(e.rotation),r=Math.sin(e.rotation);e.matrix.set(e.repeat.x*t,e.repeat.y*r,e.offset.x,-e.repeat.x*r,e.repeat.y*t,e.offset.y,0,0,1),e.matrixAutoUpdate=!1}return e.needsUpdate=!0,e}}class Ct{constructor(){this.name=rt.KHR_MESH_QUANTIZATION}}class Et extends i.Interpolant{constructor(e,t,r,i){super(e,t,r,i)}copySampleValue_(e){const t=this.resultBuffer,r=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let n=0;n!==i;n++)t[n]=r[s+n];return t}interpolate_(e,t,r,i){const s=this.resultBuffer,n=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=i-t,h=(r-t)/c,u=h*h,d=u*h,p=e*l,m=p-l,f=-2*d+3*u,g=d-u,y=1-f,v=g-u+h;for(let T=0;T!==a;T++){const e=n[m+T+a],t=n[m+T+o]*c,r=n[p+T+a],i=n[p+T]*c;s[T]=y*e+v*t+f*r+g*i}return s}}const Rt=new i.Quaternion;class Pt extends Et{interpolate_(e,t,r,i){const s=super.interpolate_(e,t,r,i);return Rt.fromArray(s).normalize().toArray(s),s}}const Lt={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Ut={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},It={9728:i.NearestFilter,9729:i.LinearFilter,9984:i.NearestMipmapNearestFilter,9985:i.LinearMipmapNearestFilter,9986:i.NearestMipmapLinearFilter,9987:i.LinearMipmapLinearFilter},Ft={33071:i.ClampToEdgeWrapping,33648:i.MirroredRepeatWrapping,10497:i.RepeatWrapping},kt={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Dt={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"},Ot={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Bt={CUBICSPLINE:void 0,LINEAR:i.InterpolateLinear,STEP:i.InterpolateDiscrete},Nt="OPAQUE",Vt="MASK",zt="BLEND";function Gt(e,t,r){for(const i in r.extensions)void 0===e[i]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[i]=r.extensions[i])}function Ht(e,t){void 0!==t.extras&&"object"==typeof t.extras&&Object.assign(e.userData,t.extras)}function jt(e,t){if(e.updateMorphTargets(),void 0!==t.weights)for(let r=0,i=t.weights.length;r<i;r++)e.morphTargetInfluences[r]=t.weights[r];if(t.extras&&Array.isArray(t.extras.targetNames)){const r=t.extras.targetNames;if(e.morphTargetInfluences.length===r.length){e.morphTargetDictionary={};for(let t=0,i=r.length;t<i;t++)e.morphTargetDictionary[r[t]]=t}}}function Wt(e){let t;const r=e.extensions&&e.extensions[rt.KHR_DRACO_MESH_COMPRESSION];if(t=r?"draco:"+r.bufferView+":"+r.indices+":"+qt(r.attributes):e.indices+":"+qt(e.attributes)+":"+e.mode,void 0!==e.targets)for(let i=0,s=e.targets.length;i<s;i++)t+=":"+qt(e.targets[i]);return t}function qt(e){let t="";const r=Object.keys(e).sort();for(let i=0,s=r.length;i<s;i++)t+=r[i]+":"+e[r[i]]+";";return t}function Xt(e){switch(e){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.")}}const Kt=new i.Matrix4;class Yt{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new et,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 r=!1,s=-1,n=!1,a=-1;if("undefined"!=typeof navigator&&void 0!==navigator.userAgent){const e=navigator.userAgent;r=!0===/^((?!chrome|android).)*safari/i.test(e);const t=e.match(/Version\/(\d+)/);s=r&&t?parseInt(t[1],10):-1,n=e.indexOf("Firefox")>-1,a=n?e.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||r&&s<17||n&&a<98?this.textureLoader=new i.TextureLoader(this.options.manager):this.textureLoader=new i.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new i.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const r=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll((function(e){return e._markDefs&&e._markDefs()})),Promise.all(this._invokeAll((function(e){return e.beforeRoot&&e.beforeRoot()}))).then((function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])})).then((function(t){const n={scene:t[0][i.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:i.asset,parser:r,userData:{}};return Gt(s,n,i),Ht(n,i),Promise.all(r._invokeAll((function(e){return e.afterRoot&&e.afterRoot(n)}))).then((function(){for(const e of n.scenes)e.updateMatrixWorld();e(n)}))})).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],r=this.json.meshes||[];for(let i=0,s=t.length;i<s;i++){const r=t[i].joints;for(let t=0,i=r.length;t<i;t++)e[r[t]].isBone=!0}for(let i=0,s=e.length;i<s;i++){const t=e[i];void 0!==t.mesh&&(this._addNodeRef(this.meshCache,t.mesh),void 0!==t.skin&&(r[t.mesh].isSkinnedMesh=!0)),void 0!==t.camera&&this._addNodeRef(this.cameraCache,t.camera)}}_addNodeRef(e,t){void 0!==t&&(void 0===e.refs[t]&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,r){if(e.refs[t]<=1)return r;const i=r.clone(),s=(e,t)=>{const r=this.associations.get(e);null!=r&&this.associations.set(t,r);for(const[i,n]of e.children.entries())s(n,t.children[i])};return s(r,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){const i=e(t[r]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const r=[];for(let i=0;i<t.length;i++){const s=e(t[i]);s&&r.push(s)}return r}getDependency(e,t){const r=e+":"+t;let i=this.cache.get(r);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne((function(e){return e.loadNode&&e.loadNode(t)}));break;case"mesh":i=this._invokeOne((function(e){return e.loadMesh&&e.loadMesh(t)}));break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne((function(e){return e.loadBufferView&&e.loadBufferView(t)}));break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne((function(e){return e.loadMaterial&&e.loadMaterial(t)}));break;case"texture":i=this._invokeOne((function(e){return e.loadTexture&&e.loadTexture(t)}));break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne((function(e){return e.loadAnimation&&e.loadAnimation(t)}));break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne((function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)})),!i)throw new Error("Unknown type: "+e)}this.cache.add(r,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const r=this,i=this.json[e+("mesh"===e?"es":"s")]||[];t=Promise.all(i.map((function(t,i){return r.getDependency(e,i)}))),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],r=this.fileLoader;if(t.type&&"arraybuffer"!==t.type)throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(void 0===t.uri&&0===e)return Promise.resolve(this.extensions[rt.KHR_BINARY_GLTF].body);const s=this.options;return new Promise((function(e,n){r.load(i.LoaderUtils.resolveURL(t.uri,s.path),e,void 0,(function(){n(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(e){const r=t.byteLength||0,i=t.byteOffset||0;return e.slice(i,i+r)}))}loadAccessor(e){const t=this,r=this.json,s=this.json.accessors[e];if(void 0===s.bufferView&&void 0===s.sparse){const e=kt[s.type],t=Ut[s.componentType],r=!0===s.normalized,n=new t(s.count*e);return Promise.resolve(new i.BufferAttribute(n,e,r))}const n=[];return void 0!==s.bufferView?n.push(this.getDependency("bufferView",s.bufferView)):n.push(null),void 0!==s.sparse&&(n.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),n.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(n).then((function(e){const n=e[0],a=kt[s.type],o=Ut[s.componentType],l=o.BYTES_PER_ELEMENT,c=l*a,h=s.byteOffset||0,u=void 0!==s.bufferView?r.bufferViews[s.bufferView].byteStride:void 0,d=!0===s.normalized;let p,m;if(u&&u!==c){const e=Math.floor(h/u),r="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+e+":"+s.count;let c=t.cache.get(r);c||(p=new o(n,e*u,s.count*u/l),c=new i.InterleavedBuffer(p,u/l),t.cache.add(r,c)),m=new i.InterleavedBufferAttribute(c,a,h%u/l,d)}else p=null===n?new o(s.count*a):new o(n,h,s.count*a),m=new i.BufferAttribute(p,a,d);if(void 0!==s.sparse){const t=kt.SCALAR,r=Ut[s.sparse.indices.componentType],l=s.sparse.indices.byteOffset||0,c=s.sparse.values.byteOffset||0,h=new r(e[1],l,s.sparse.count*t),u=new o(e[2],c,s.sparse.count*a);null!==n&&(m=new i.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let e=0,i=h.length;e<i;e++){const t=h[e];if(m.setX(t,u[e*a]),a>=2&&m.setY(t,u[e*a+1]),a>=3&&m.setZ(t,u[e*a+2]),a>=4&&m.setW(t,u[e*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=d}return m}))}loadTexture(e){const t=this.json,r=this.options,i=t.textures[e].source,s=t.images[i];let n=this.textureLoader;if(s.uri){const e=r.manager.getHandler(s.uri);null!==e&&(n=e)}return this.loadTextureImage(e,i,n)}loadTextureImage(e,t,r){const s=this,n=this.json,a=n.textures[e],o=n.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,r).then((function(t){t.flipY=!1,t.name=a.name||o.name||"",""===t.name&&"string"==typeof o.uri&&!1===o.uri.startsWith("data:image/")&&(t.name=o.uri);const r=(n.samplers||{})[a.sampler]||{};return t.magFilter=It[r.magFilter]||i.LinearFilter,t.minFilter=It[r.minFilter]||i.LinearMipmapLinearFilter,t.wrapS=Ft[r.wrapS]||i.RepeatWrapping,t.wrapT=Ft[r.wrapT]||i.RepeatWrapping,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==i.NearestFilter&&t.minFilter!==i.LinearFilter,s.associations.set(t,{textures:e}),t})).catch((function(){return null}));return this.textureCache[l]=c,c}loadImageSource(e,t){const r=this,s=this.json,n=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then((e=>e.clone()));const a=s.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(void 0!==a.bufferView)l=r.getDependency("bufferView",a.bufferView).then((function(e){c=!0;const t=new Blob([e],{type:a.mimeType});return l=o.createObjectURL(t),l}));else if(void 0===a.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(l).then((function(e){return new Promise((function(r,s){let a=r;!0===t.isImageBitmapLoader&&(a=function(e){const t=new i.Texture(e);t.needsUpdate=!0,r(t)}),t.load(i.LoaderUtils.resolveURL(e,n.path),a,void 0,s)}))})).then((function(e){var t;return!0===c&&o.revokeObjectURL(l),Ht(e,a),e.userData.mimeType=a.mimeType||((t=a.uri).search(/\.jpe?g($|\?)/i)>0||0===t.search(/^data\:image\/jpeg/)?"image/jpeg":t.search(/\.webp($|\?)/i)>0||0===t.search(/^data\:image\/webp/)?"image/webp":t.search(/\.ktx2($|\?)/i)>0||0===t.search(/^data\:image\/ktx2/)?"image/ktx2":"image/png"),e})).catch((function(e){throw e}));return this.sourceCache[e]=h,h}assignTexture(e,t,r,i){const s=this;return this.getDependency("texture",r.index).then((function(n){if(!n)return null;if(void 0!==r.texCoord&&r.texCoord>0&&((n=n.clone()).channel=r.texCoord),s.extensions[rt.KHR_TEXTURE_TRANSFORM]){const e=void 0!==r.extensions?r.extensions[rt.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=s.associations.get(n);n=s.extensions[rt.KHR_TEXTURE_TRANSFORM].extendTexture(n,e),s.associations.set(n,t)}}return void 0!==i&&(n.colorSpace=i),e[t]=n,n}))}assignFinalMaterial(e){const t=e.geometry;let r=e.material;const s=void 0===t.attributes.tangent,n=void 0!==t.attributes.color,a=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+r.uuid;let t=this.cache.get(e);t||(t=new i.PointsMaterial,i.Material.prototype.copy.call(t,r),t.color.copy(r.color),t.map=r.map,t.sizeAttenuation=!1,this.cache.add(e,t)),r=t}else if(e.isLine){const e="LineBasicMaterial:"+r.uuid;let t=this.cache.get(e);t||(t=new i.LineBasicMaterial,i.Material.prototype.copy.call(t,r),t.color.copy(r.color),t.map=r.map,this.cache.add(e,t)),r=t}if(s||n||a){let e="ClonedMaterial:"+r.uuid+":";s&&(e+="derivative-tangents:"),n&&(e+="vertex-colors:"),a&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=r.clone(),n&&(t.vertexColors=!0),a&&(t.flatShading=!0),s&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(r))),r=t}e.material=r}getMaterialType(){return i.MeshStandardMaterial}loadMaterial(e){const t=this,r=this.json,s=this.extensions,n=r.materials[e];let a;const o={},l=[];if((n.extensions||{})[rt.KHR_MATERIALS_UNLIT]){const e=s[rt.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),l.push(e.extendParams(o,n,t))}else{const r=n.pbrMetallicRoughness||{};if(o.color=new i.Color(1,1,1),o.opacity=1,Array.isArray(r.baseColorFactor)){const e=r.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],i.LinearSRGBColorSpace),o.opacity=e[3]}void 0!==r.baseColorTexture&&l.push(t.assignTexture(o,"map",r.baseColorTexture,i.SRGBColorSpace)),o.metalness=void 0!==r.metallicFactor?r.metallicFactor:1,o.roughness=void 0!==r.roughnessFactor?r.roughnessFactor:1,void 0!==r.metallicRoughnessTexture&&(l.push(t.assignTexture(o,"metalnessMap",r.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",r.metallicRoughnessTexture))),a=this._invokeOne((function(t){return t.getMaterialType&&t.getMaterialType(e)})),l.push(Promise.all(this._invokeAll((function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)}))))}!0===n.doubleSided&&(o.side=i.DoubleSide);const c=n.alphaMode||Nt;if(c===zt?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,c===Vt&&(o.alphaTest=void 0!==n.alphaCutoff?n.alphaCutoff:.5)),void 0!==n.normalTexture&&a!==i.MeshBasicMaterial&&(l.push(t.assignTexture(o,"normalMap",n.normalTexture)),o.normalScale=new i.Vector2(1,1),void 0!==n.normalTexture.scale)){const e=n.normalTexture.scale;o.normalScale.set(e,e)}if(void 0!==n.occlusionTexture&&a!==i.MeshBasicMaterial&&(l.push(t.assignTexture(o,"aoMap",n.occlusionTexture)),void 0!==n.occlusionTexture.strength&&(o.aoMapIntensity=n.occlusionTexture.strength)),void 0!==n.emissiveFactor&&a!==i.MeshBasicMaterial){const e=n.emissiveFactor;o.emissive=(new i.Color).setRGB(e[0],e[1],e[2],i.LinearSRGBColorSpace)}return void 0!==n.emissiveTexture&&a!==i.MeshBasicMaterial&&l.push(t.assignTexture(o,"emissiveMap",n.emissiveTexture,i.SRGBColorSpace)),Promise.all(l).then((function(){const r=new a(o);return n.name&&(r.name=n.name),Ht(r,n),t.associations.set(r,{materials:e}),n.extensions&&Gt(s,r,n),r}))}createUniqueName(e){const t=i.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,r=this.extensions,s=this.primitiveCache;function n(e){return r[rt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(r){return Qt(r,e,t)}))}const a=[];for(let o=0,l=e.length;o<l;o++){const r=e[o],l=Wt(r),c=s[l];if(c)a.push(c.promise);else{let e;e=r.extensions&&r.extensions[rt.KHR_DRACO_MESH_COMPRESSION]?n(r):Qt(new i.BufferGeometry,r,t),r.mode===Lt.TRIANGLE_STRIP?e=e.then((e=>Qe(e,i.TriangleStripDrawMode))):r.mode===Lt.TRIANGLE_FAN&&(e=e.then((e=>Qe(e,i.TriangleFanDrawMode)))),s[l]={primitive:r,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){const t=this,r=this.json,s=this.extensions,n=r.meshes[e],a=n.primitives,o=[];for(let c=0,h=a.length;c<h;c++){const e=void 0===a[c].material?(void 0===(l=this.cache).DefaultMaterial&&(l.DefaultMaterial=new i.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:i.FrontSide})),l.DefaultMaterial):this.getDependency("material",a[c].material);o.push(e)}var l;return o.push(t.loadGeometries(a)),Promise.all(o).then((async function(r){const o=r.slice(0,r.length-1),l=r[r.length-1],c=[];for(let u=0,d=l.length;u<d;u++){const r=l[u],h=a[u];let d;const p=o[u];if(h.mode===Lt.TRIANGLES||h.mode===Lt.TRIANGLE_STRIP||h.mode===Lt.TRIANGLE_FAN||void 0===h.mode){const e=!0===n.isSkinnedMesh,t=r.hasAttribute("skinIndex")&&r.hasAttribute("skinWeight");d=e&&t?new i.SkinnedMesh(r,p):new i.Mesh(r,p),!0===d.isSkinnedMesh&&d.normalizeSkinWeights()}else if(h.mode===Lt.LINES)d=new i.LineSegments(r,p);else if(h.mode===Lt.LINE_STRIP)d=new i.Line(r,p);else if(h.mode===Lt.LINE_LOOP)d=new i.LineLoop(r,p);else{if(h.mode!==Lt.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+h.mode);d=new i.Points(r,p)}Object.keys(d.geometry.morphAttributes).length>0&&jt(d,n),d.name=t.createUniqueName(n.name||"mesh_"+e),Ht(d,n),h.extensions&&Gt(s,d,h),t.assignFinalMaterial(d),c.push(d)}for(let i=0,s=c.length;i<s;i++)t.associations.set(c[i],{meshes:e,primitives:i});if(1===c.length)return n.extensions&&Gt(s,c[0],n),c[0];const h=new i.Group;n.extensions&&Gt(s,h,n),t.associations.set(h,{meshes:e});for(let e=0,t=c.length;e<t;e++)h.add(c[e]);return h}))}loadCamera(e){let t;const r=this.json.cameras[e],s=r[r.type];if(s)return"perspective"===r.type?t=new i.PerspectiveCamera(i.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):"orthographic"===r.type&&(t=new i.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),Ht(t,r),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],r=[];for(let i=0,s=t.joints.length;i<s;i++)r.push(this._loadNodeShallow(t.joints[i]));return void 0!==t.inverseBindMatrices?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then((function(e){const t=e.pop(),r=e,s=[],n=[];for(let a=0,o=r.length;a<o;a++){const e=r[a];if(e){s.push(e);const r=new i.Matrix4;null!==t&&r.fromArray(t.array,16*a),n.push(r)}}return new i.Skeleton(s,n)}))}loadAnimation(e){const t=this.json,r=this,s=t.animations[e],n=s.name?s.name:"animation_"+e,a=[],o=[],l=[],c=[],h=[];for(let i=0,u=s.channels.length;i<u;i++){const e=s.channels[i],t=s.samplers[e.sampler],r=e.target,n=r.node,u=void 0!==s.parameters?s.parameters[t.input]:t.input,d=void 0!==s.parameters?s.parameters[t.output]:t.output;void 0!==r.node&&(a.push(this.getDependency("node",n)),o.push(this.getDependency("accessor",u)),l.push(this.getDependency("accessor",d)),c.push(t),h.push(r))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(h)]).then((function(e){const t=e[0],a=e[1],o=e[2],l=e[3],c=e[4],h=[];for(let i=0,s=t.length;i<s;i++){const e=t[i],s=a[i],n=o[i],u=l[i],d=c[i];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const p=r._createAnimationTracks(e,s,n,u,d);if(p)for(let t=0;t<p.length;t++)h.push(p[t])}const u=new i.AnimationClip(n,void 0,h);return Ht(u,s),u}))}createNodeMesh(e){const t=this.json,r=this,i=t.nodes[e];return void 0===i.mesh?null:r.getDependency("mesh",i.mesh).then((function(e){const t=r._getNodeRef(r.meshCache,i.mesh,e);return void 0!==i.weights&&t.traverse((function(e){if(e.isMesh)for(let t=0,r=i.weights.length;t<r;t++)e.morphTargetInfluences[t]=i.weights[t]})),t}))}loadNode(e){const t=this,r=this.json.nodes[e],s=t._loadNodeShallow(e),n=[],a=r.children||[];for(let i=0,l=a.length;i<l;i++)n.push(t.getDependency("node",a[i]));const o=void 0===r.skin?Promise.resolve(null):t.getDependency("skin",r.skin);return Promise.all([s,Promise.all(n),o]).then((function(e){const t=e[0],r=e[1],s=e[2];null!==s&&t.traverse((function(e){e.isSkinnedMesh&&e.bind(s,Kt)}));for(let i=0,n=r.length;i<n;i++)t.add(r[i]);if(void 0!==t.userData.pivot&&r.length>0){const e=t.userData.pivot,s=r[0];t.pivot=(new i.Vector3).fromArray(e),t.position.x-=e[0],t.position.y-=e[1],t.position.z-=e[2],s.position.set(0,0,0),delete t.userData.pivot}return t}))}_loadNodeShallow(e){const t=this.json,r=this.extensions,s=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const n=t.nodes[e],a=n.name?s.createUniqueName(n.name):"",o=[],l=s._invokeOne((function(t){return t.createNodeMesh&&t.createNodeMesh(e)}));return l&&o.push(l),void 0!==n.camera&&o.push(s.getDependency("camera",n.camera).then((function(e){return s._getNodeRef(s.cameraCache,n.camera,e)}))),s._invokeAll((function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)})).forEach((function(e){o.push(e)})),this.nodeCache[e]=Promise.all(o).then((function(t){let o;if(o=!0===n.isBone?new i.Bone:t.length>1?new i.Group:1===t.length?t[0]:new i.Object3D,o!==t[0])for(let e=0,r=t.length;e<r;e++)o.add(t[e]);if(n.name&&(o.userData.name=n.name,o.name=a),Ht(o,n),n.extensions&&Gt(r,o,n),void 0!==n.matrix){const e=new i.Matrix4;e.fromArray(n.matrix),o.applyMatrix4(e)}else void 0!==n.translation&&o.position.fromArray(n.translation),void 0!==n.rotation&&o.quaternion.fromArray(n.rotation),void 0!==n.scale&&o.scale.fromArray(n.scale);if(s.associations.has(o)){if(void 0!==n.mesh&&s.meshCache.refs[n.mesh]>1){const e=s.associations.get(o);s.associations.set(o,{...e})}}else s.associations.set(o,{});return s.associations.get(o).nodes=e,o})),this.nodeCache[e]}loadScene(e){const t=this.extensions,r=this.json.scenes[e],s=this,n=new i.Group;r.name&&(n.name=s.createUniqueName(r.name)),Ht(n,r),r.extensions&&Gt(t,n,r);const a=r.nodes||[],o=[];for(let i=0,l=a.length;i<l;i++)o.push(s.getDependency("node",a[i]));return Promise.all(o).then((function(e){for(let t=0,r=e.length;t<r;t++){const r=e[t];null!==r.parent?n.add($e(r)):n.add(r)}return s.associations=(e=>{const t=new Map;for(const[r,n]of s.associations)(r instanceof i.Material||r instanceof i.Texture)&&t.set(r,n);return e.traverse((e=>{const r=s.associations.get(e);null!=r&&t.set(e,r)})),t})(n),n}))}_createAnimationTracks(e,t,r,s,n){const a=[],o=e.name?e.name:e.uuid,l=[];function c(e){e.morphTargetInfluences&&l.push(e.name?e.name:e.uuid)}let h;switch(Ot[n.path]===Ot.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o),Ot[n.path]){case Ot.weights:h=i.NumberKeyframeTrack;break;case Ot.rotation:h=i.QuaternionKeyframeTrack;break;case Ot.translation:case Ot.scale:h=i.VectorKeyframeTrack;break;default:if(1===r.itemSize)h=i.NumberKeyframeTrack;else h=i.VectorKeyframeTrack}const u=void 0!==s.interpolation?Bt[s.interpolation]:i.InterpolateLinear,d=this._getArrayFromAccessor(r);for(let i=0,p=l.length;i<p;i++){const e=new h(l[i]+"."+Ot[n.path],t.array,d,u);"CUBICSPLINE"===s.interpolation&&this._createCubicSplineTrackInterpolant(e),a.push(e)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const e=Xt(t.constructor),r=new Float32Array(t.length);for(let i=0,s=t.length;i<s;i++)r[i]=t[i]*e;t=r}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof i.QuaternionKeyframeTrack?Pt:Et)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Qt(e,t,r){const s=t.attributes,n=[];function a(t,i){return r.getDependency("accessor",t).then((function(t){e.setAttribute(i,t)}))}for(const i in s){const t=Dt[i]||i.toLowerCase();t in e.attributes||n.push(a(s[i],t))}if(void 0!==t.indices&&!e.index){const i=r.getDependency("accessor",t.indices).then((function(t){e.setIndex(t)}));n.push(i)}return i.ColorManagement.workingColorSpace,i.LinearSRGBColorSpace,Ht(e,t),function(e,t,r){const s=t.attributes,n=new i.Box3;if(void 0===s.POSITION)return;{const e=r.json.accessors[s.POSITION],t=e.min,a=e.max;if(void 0===t||void 0===a)return;if(n.set(new i.Vector3(t[0],t[1],t[2]),new i.Vector3(a[0],a[1],a[2])),e.normalized){const t=Xt(Ut[e.componentType]);n.min.multiplyScalar(t),n.max.multiplyScalar(t)}}const a=t.targets;if(void 0!==a){const e=new i.Vector3,t=new i.Vector3;for(let i=0,s=a.length;i<s;i++){const s=a[i];if(void 0!==s.POSITION){const i=r.json.accessors[s.POSITION],n=i.min,a=i.max;if(void 0!==n&&void 0!==a){if(t.setX(Math.max(Math.abs(n[0]),Math.abs(a[0]))),t.setY(Math.max(Math.abs(n[1]),Math.abs(a[1]))),t.setZ(Math.max(Math.abs(n[2]),Math.abs(a[2]))),i.normalized){const e=Xt(Ut[i.componentType]);t.multiplyScalar(e)}e.max(t)}}}n.expandByVector(e)}e.boundingBox=n;const o=new i.Sphere;n.getCenter(o.center),o.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=o}(e,t,r),Promise.all(n).then((function(){return void 0!==t.targets?function(e,t,r){let i=!1,s=!1,n=!1;for(let c=0,h=t.length;c<h;c++){const e=t[c];if(void 0!==e.POSITION&&(i=!0),void 0!==e.NORMAL&&(s=!0),void 0!==e.COLOR_0&&(n=!0),i&&s&&n)break}if(!i&&!s&&!n)return Promise.resolve(e);const a=[],o=[],l=[];for(let c=0,h=t.length;c<h;c++){const h=t[c];if(i){const t=void 0!==h.POSITION?r.getDependency("accessor",h.POSITION):e.attributes.position;a.push(t)}if(s){const t=void 0!==h.NORMAL?r.getDependency("accessor",h.NORMAL):e.attributes.normal;o.push(t)}if(n){const t=void 0!==h.COLOR_0?r.getDependency("accessor",h.COLOR_0):e.attributes.color;l.push(t)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then((function(t){const r=t[0],a=t[1],o=t[2];return i&&(e.morphAttributes.position=r),s&&(e.morphAttributes.normal=a),n&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e}))}(e,t.targets,r):e}))}var $t=class extends qe{constructor(e=i.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new i.Matrix4}parse(e){let t=super.parse(e),r=t.glbBytes.slice().buffer;return new Promise(((e,i)=>{let s=this.manager,n=this.fetchOptions,a=s.getHandler("path.gltf")||new Je(s);"include"===n.credentials&&"cors"===n.mode&&a.setCrossOrigin("use-credentials"),"credentials"in n&&a.setWithCredentials("include"===n.credentials),n.headers&&a.setRequestHeader(n.headers);let o=this.workingPath;!/[\\/]$/.test(o)&&o.length&&(o+="/");let l=this.adjustmentTransform;a.parse(r,o,(r=>{let{batchTable:i,featureTable:s}=t,{scene:n}=r,a=s.getData("RTC_CENTER",1,"FLOAT","VEC3");a&&(n.position.x+=a[0],n.position.y+=a[1],n.position.z+=a[2]),r.scene.updateMatrix(),r.scene.matrix.multiply(l),r.scene.matrix.decompose(r.scene.position,r.scene.quaternion,r.scene.scale),r.batchTable=i,r.featureTable=s,n.batchTable=i,n.featureTable=s,e(r)}),i)}))}};function Zt(e){let t=e>>11,r=e>>5&63,i=31&e;return[Math.round(t/31*255),Math.round(r/63*255),Math.round(i/31*255)]}var Jt=new i.Vector2;function er(e,t,r=new i.Vector3){Jt.set(e,t).divideScalar(256).multiplyScalar(2).subScalar(1),r.set(Jt.x,Jt.y,1-Math.abs(Jt.x)-Math.abs(Jt.y));let s=i.MathUtils.clamp(-r.z,0,1);return r.x>=0?r.setX(r.x-s):r.setX(r.x+s),r.y>=0?r.setY(r.y-s):r.setY(r.y+s),r.normalize(),r}var tr={RGB:"color",POSITION:"position"},rr=class extends Ke{constructor(e=i.DefaultLoadingManager){super(),this.manager=e}parse(e){return super.parse(e).then((async e=>{let t,{featureTable:r,batchTable:s}=e,n=new i.PointsMaterial,a=r.header.extensions,o=new i.Vector3;if(a&&a["3DTILES_draco_point_compression"]){let{byteOffset:e,byteLength:i,properties:s}=a["3DTILES_draco_point_compression"],o=this.manager.getHandler("draco.drc");if(null==o)throw Error("PNTSLoader: dracoLoader not available.");let l={};for(let t in s)if(t in tr&&t in s){l[tr[t]]=s[t]}let c={attributeIDs:l,attributeTypes:{position:"Float32Array",color:"Uint8Array"},useUniqueIDs:!0},h=r.getBuffer(e,i);t=await o.decodeGeometry(h,c),t.attributes.color&&(n.vertexColors=!0)}else{let e=r.getData("POINTS_LENGTH"),s=r.getData("POSITION",e,"FLOAT","VEC3"),a=r.getData("NORMAL",e,"FLOAT","VEC3"),l=r.getData("NORMAL",e,"UNSIGNED_BYTE","VEC2"),c=r.getData("RGB",e,"UNSIGNED_BYTE","VEC3"),h=r.getData("RGBA",e,"UNSIGNED_BYTE","VEC4"),u=r.getData("RGB565",e,"UNSIGNED_SHORT","SCALAR"),d=r.getData("CONSTANT_RGBA",e,"UNSIGNED_BYTE","VEC4"),p=r.getData("POSITION_QUANTIZED",e,"UNSIGNED_SHORT","VEC3"),m=r.getData("QUANTIZED_VOLUME_SCALE",e,"FLOAT","VEC3"),f=r.getData("QUANTIZED_VOLUME_OFFSET",e,"FLOAT","VEC3");if(t=new i.BufferGeometry,p){let r=new Float32Array(3*e);for(let t=0;t<e;t++)for(let e=0;e<3;e++){let i=3*t+e;r[i]=p[i]/65535*m[e]}o.x=f[0],o.y=f[1],o.z=f[2],t.setAttribute("position",new i.BufferAttribute(r,3,!1))}else t.setAttribute("position",new i.BufferAttribute(s,3,!1));if(null!==a)t.setAttribute("normal",new i.BufferAttribute(a,3,!1));else if(null!==l){let r=new Float32Array(3*e),s=new i.Vector3;for(let t=0;t<e;t++){let e=er(l[2*t],l[2*t+1],s);r[3*t]=e.x,r[3*t+1]=e.y,r[3*t+2]=e.z}t.setAttribute("normal",new i.BufferAttribute(r,3,!1))}if(null!==h)t.setAttribute("color",new i.BufferAttribute(h,4,!0)),n.vertexColors=!0,n.transparent=!0,n.depthWrite=!1;else if(null!==c)t.setAttribute("color",new i.BufferAttribute(c,3,!0)),n.vertexColors=!0;else if(null!==u){let r=new Uint8Array(3*e);for(let t=0;t<e;t++){let e=Zt(u[t]);for(let i=0;i<3;i++){r[3*t+i]=e[i]}}t.setAttribute("color",new i.BufferAttribute(r,3,!0)),n.vertexColors=!0}else if(null!==d){n.color=new i.Color(d[0],d[1],d[2]);let e=d[3]/255;e<1&&(n.opacity=e,n.transparent=!0,n.depthWrite=!1)}}let l=new i.Points(t,n);l.position.copy(o),e.scene=l,e.scene.featureTable=r,e.scene.batchTable=s;let c=r.getData("RTC_CENTER",1,"FLOAT","VEC3");return c&&(e.scene.position.x+=c[0],e.scene.position.y+=c[1],e.scene.position.z+=c[2]),e}))}};var ir=new i.Spherical,sr=new i.Vector3,nr=new i.Vector3,ar=new i.Vector3,or=new i.Matrix4,lr=new i.Matrix4,cr=new i.Sphere,hr=new i.Euler,ur=new i.Vector3,dr=new i.Vector3,pr=new i.Vector3,mr=new i.Vector3,fr=new i.Ray,gr=class{constructor(e=1,t=1,r=1){this.name="",this.radius=new i.Vector3(e,t,r)}intersectRay(e,t){return or.makeScale(...this.radius).invert(),cr.center.set(0,0,0),cr.radius=1,fr.copy(e).applyMatrix4(or),fr.intersectSphere(cr,t)?(or.makeScale(...this.radius),t.applyMatrix4(or),t):null}getEastNorthUpFrame(e,t,r,i){return r.isMatrix4&&(i=r,r=0),this.getEastNorthUpAxes(e,t,ur,dr,pr),this.getCartographicToPosition(e,t,r,mr),i.makeBasis(ur,dr,pr).setPosition(mr)}getOrientedEastNorthUpFrame(e,t,r,i,s,n,a){return this.getObjectFrame(e,t,r,i,s,n,a,0)}getObjectFrame(e,t,r,i,s,n,a,o=2){return this.getEastNorthUpFrame(e,t,r,or),hr.set(s,n,-i,"ZXY"),a.makeRotationFromEuler(hr).premultiply(or),1===o?(hr.set(Math.PI/2,0,0,"XYZ"),lr.makeRotationFromEuler(hr),a.multiply(lr)):2===o&&(hr.set(-Math.PI/2,0,Math.PI,"XYZ"),lr.makeRotationFromEuler(hr),a.multiply(lr)),a}getCartographicFromObjectFrame(e,t,r=2){return 1===r?(hr.set(-Math.PI/2,0,0,"XYZ"),lr.makeRotationFromEuler(hr).premultiply(e)):2===r?(hr.set(-Math.PI/2,0,Math.PI,"XYZ"),lr.makeRotationFromEuler(hr).premultiply(e)):lr.copy(e),mr.setFromMatrixPosition(lr),this.getPositionToCartographic(mr,t),this.getEastNorthUpFrame(t.lat,t.lon,0,or).invert(),lr.premultiply(or),hr.setFromRotationMatrix(lr,"ZXY"),t.azimuth=-hr.z,t.elevation=hr.x,t.roll=hr.y,t}getEastNorthUpAxes(e,t,r,i,s,n=mr){this.getCartographicToPosition(e,t,0,n),this.getCartographicToNormal(e,t,s),r.set(-n.y,n.x,0).normalize(),i.crossVectors(s,r).normalize()}getCartographicToPosition(e,t,r,i){this.getCartographicToNormal(e,t,sr);let s=this.radius;nr.copy(sr),nr.x*=s.x**2,nr.y*=s.y**2,nr.z*=s.z**2;let n=Math.sqrt(sr.dot(nr));return nr.divideScalar(n),i.copy(nr).addScaledVector(sr,r)}getPositionToCartographic(e,t){this.getPositionToSurfacePoint(e,nr),this.getPositionToNormal(nr,sr);let r=ar.subVectors(e,nr);return t.lon=Math.atan2(sr.y,sr.x),t.lat=Math.asin(sr.z),t.height=Math.sign(r.dot(e))*r.length(),t}getCartographicToNormal(e,t,r){return ir.set(1,function(e){return-e+Math.PI/2}(e),t),r.setFromSpherical(ir).normalize(),function(e){let{x:t,y:r,z:i}=e;e.x=i,e.y=t,e.z=r}(r),r}getPositionToNormal(e,t){let r=this.radius;return t.copy(e),t.x/=r.x**2,t.y/=r.y**2,t.z/=r.z**2,t.normalize(),t}getPositionToSurfacePoint(e,t){let r=this.radius,i=1/r.x**2,s=1/r.y**2,n=1/r.z**2,a=e.x*e.x*i,o=e.y*e.y*s,l=e.z*e.z*n,c=a+o+l,h=Math.sqrt(1/c),u=nr.copy(e).multiplyScalar(h);if(c<.1)return isFinite(h)?t.copy(u):null;let d,p,m,f,g,y,v,T,x,b,_,w=ar.set(u.x*i*2,u.y*s*2,u.z*n*2),M=(1-h)*e.length()/(.5*w.length()),S=0;do{M-=S,m=1/(1+M*i),f=1/(1+M*s),g=1/(1+M*n),y=m*m,v=f*f,T=g*g,x=y*m,b=v*f,_=T*g,d=a*y+o*v+l*T-1,p=a*x*i+o*b*s+l*_*n,S=d/(-2*p)}while(Math.abs(d)>1e-12);return t.set(e.x*m,e.y*f,e.z*g)}calculateHorizonDistance(e,t){let r=this.calculateEffectiveRadius(e);return Math.sqrt(2*r*t+t**2)}calculateEffectiveRadius(e){let t=this.radius.x,r=1-this.radius.z**2/t**2,s=e*i.MathUtils.DEG2RAD,n=Math.sin(s)**2;return t/Math.sqrt(1-r*n)}getPositionElevation(e){this.getPositionToSurfacePoint(e,nr);let t=ar.subVectors(e,nr);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(or.makeScale(...this.radius).invert(),fr.copy(e).applyMatrix4(or),nr.set(0,0,0),fr.closestPointToPoint(nr,t).normalize(),or.makeScale(...this.radius),t.applyMatrix4(or))}copy(e){return this.radius.copy(e.radius),this}clone(){return(new this.constructor).copy(this)}},yr=new gr(he,he,6356752.314245179);yr.name="WGS84 Earth";var vr=new i.Vector3,Tr=new i.Vector3,xr=new i.Vector3,br=new i.Vector3,_r=new i.Quaternion,wr=new i.Vector3,Mr=new i.Matrix4,Sr=new i.Matrix4,Ar=new i.Vector3,Cr=new i.Matrix4,Er=new i.Quaternion,Rr={};function Pr(e,t,r,i){if(e=e/r*2-1,t=t/r*2-1,i.x=e,i.y=t,i.z=1-Math.abs(e)-Math.abs(t),i.z<0){let e=i.x;i.x=(1-Math.abs(i.y))*(e>=0?1:-1),i.y=(1-Math.abs(e))*(i.y>=0?1:-1)}return i.normalize(),i}var Lr=class extends Xe{constructor(e=i.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new i.Matrix4,this.ellipsoid=yr.clone()}resolveExternalURL(e){return this.manager.resolveURL(super.resolveExternalURL(e))}parse(e){return super.parse(e).then((e=>{let{featureTable:t,batchTable:r}=e,s=e.glbBytes.slice().buffer;return new Promise(((n,a)=>{let o=this.fetchOptions,l=this.manager,c=l.getHandler("path.gltf")||new Je(l);"include"===o.credentials&&"cors"===o.mode&&c.setCrossOrigin("use-credentials"),"credentials"in o&&c.setWithCredentials("include"===o.credentials),o.headers&&c.setRequestHeader(o.headers);let h=e.gltfWorkingPath??this.workingPath;/[\\/]$/.test(h)||(h+="/");let u=this.adjustmentTransform;c.parse(s,h,(e=>{let s=t.getData("INSTANCES_LENGTH"),a=t.getData("POSITION",s,"FLOAT","VEC3"),o=t.getData("POSITION_QUANTIZED",s,"UNSIGNED_SHORT","VEC3"),l=t.getData("QUANTIZED_VOLUME_OFFSET",1,"FLOAT","VEC3"),c=t.getData("QUANTIZED_VOLUME_SCALE",1,"FLOAT","VEC3"),h=t.getData("NORMAL_UP",s,"FLOAT","VEC3"),d=t.getData("NORMAL_RIGHT",s,"FLOAT","VEC3"),p=t.getData("NORMAL_UP_OCT32P",s,"UNSIGNED_SHORT","VEC2"),m=t.getData("NORMAL_RIGHT_OCT32P",s,"UNSIGNED_SHORT","VEC2"),f=t.getData("SCALE_NON_UNIFORM",s,"FLOAT","VEC3"),g=t.getData("SCALE",s,"FLOAT","SCALAR"),y=t.getData("RTC_CENTER",1,"FLOAT","VEC3"),v=t.getData("EAST_NORTH_UP");if(!a&&o){a=new Float32Array(3*s);for(let e=0;e<s;e++)a[3*e+0]=l[0]+o[3*e+0]/65535*c[0],a[3*e+1]=l[1]+o[3*e+1]/65535*c[1],a[3*e+2]=l[2]+o[3*e+2]/65535*c[2]}let T=new i.Vector3;for(let t=0;t<s;t++)T.x+=a[3*t+0]/s,T.y+=a[3*t+1]/s,T.z+=a[3*t+2]/s;let x=[],b=[];e.scene.updateMatrixWorld(),e.scene.traverse((e=>{if(e.isMesh){b.push(e);let{geometry:t,material:r}=e,n=new i.InstancedMesh(t,r,s);n.position.copy(T),y&&(n.position.x+=y[0],n.position.y+=y[1],n.position.z+=y[2]),x.push(n)}}));for(let t=0;t<s;t++){br.set(a[3*t+0]-T.x,a[3*t+1]-T.y,a[3*t+2]-T.z),_r.identity(),h&&d?(Tr.set(h[3*t+0],h[3*t+1],h[3*t+2]),xr.set(d[3*t+0],d[3*t+1],d[3*t+2]),vr.crossVectors(xr,Tr).normalize(),Mr.makeBasis(xr,Tr,vr),_r.setFromRotationMatrix(Mr)):p&&m&&(Pr(p[2*t+0],p[2*t+1],65535,Tr),Pr(m[2*t+0],m[2*t+1],65535,xr),vr.crossVectors(xr,Tr).normalize(),Mr.makeBasis(xr,Tr,vr),_r.setFromRotationMatrix(Mr)),wr.set(1,1,1),f&&wr.set(f[3*t+0],f[3*t+1],f[3*t+2]),g&&wr.multiplyScalar(g[t]);for(let e=0,r=x.length;e<r;e++){let r=x[e];Er.copy(_r),v&&(r.updateMatrixWorld(),Ar.copy(br).applyMatrix4(r.matrixWorld),this.ellipsoid.getPositionToCartographic(Ar,Rr),this.ellipsoid.getEastNorthUpFrame(Rr.lat,Rr.lon,Cr),Er.setFromRotationMatrix(Cr)),Mr.compose(br,Er,wr).multiply(u);let i=b[e];Sr.multiplyMatrices(Mr,i.matrixWorld),r.setMatrixAt(t,Sr)}}e.scene.clear(),e.scene.add(...x),e.batchTable=r,e.featureTable=t,e.scene.batchTable=r,e.scene.featureTable=t,n(e)}),a)}))}))}},Ur=class extends Ye{constructor(e=i.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new i.Matrix4,this.ellipsoid=yr.clone()}parse(e){let t=super.parse(e),{manager:r,ellipsoid:s,adjustmentTransform:n}=this,a=[];for(let i in t.tiles){let{type:e,buffer:o}=t.tiles[i];switch(e){case"b3dm":{let e=o.slice(),t=new $t(r);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.adjustmentTransform.copy(n);let i=t.parse(e.buffer);a.push(i);break}case"pnts":{let e=o.slice(),t=new rr(r);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions;let i=t.parse(e.buffer);a.push(i);break}case"i3dm":{let e=o.slice(),t=new Lr(r);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.ellipsoid.copy(s),t.adjustmentTransform.copy(n);let i=t.parse(e.buffer);a.push(i);break}}}return Promise.all(a).then((e=>{let t=new i.Group;return e.forEach((e=>{t.add(e.scene)})),{tiles:e,scene:t}}))}},Ir=new i.Matrix4,Fr=class extends i.Group{constructor(e){super(),this.isTilesGroup=!0,this.name="TilesRenderer.TilesGroup",this.tilesRenderer=e,this.matrixWorldInverse=new i.Matrix4}raycast(e,t){return this.tilesRenderer.raycast(e,t),!1}updateMatrixWorld(e){if(this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldNeedsUpdate||e){null===this.parent?Ir.copy(this.matrix):Ir.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1;let e=Ir.elements,t=this.matrixWorld.elements,r=!1;for(let i=0;i<16;i++){let s=e[i],n=t[i];if(Math.abs(s-n)>2**-52){r=!0;break}}if(r){this.matrixWorld.copy(Ir),this.matrixWorldInverse.copy(Ir).invert();let e=this.children;for(let s=0,n=e.length;s<n;s++)e[s].updateMatrixWorld();let{tilesRenderer:t}=this,{activeTiles:r,visibleTiles:i}=t;r.forEach((e=>{i.has(e)||e.engineData.scene.updateMatrixWorld(!0)}))}}}updateWorldMatrix(e,t){this.parent&&e&&this.parent.updateWorldMatrix(e,!1),this.updateMatrixWorld(!0)}},kr=new i.Ray;function Dr(e,t,r,i,s=null){if(!function(e){return"traversal"in e}(t))return;let{group:n,activeTiles:a}=e,{boundingVolume:o}=t.engineData;if(null===s&&(s=kr).copy(r.ray).applyMatrix4(n.matrixWorldInverse),!t.traversal.used||!o.intersectsRay(s))return;a.has(t)&&function(e,t,r,i){let{scene:s}=e.engineData;r.invokeOnePlugin((r=>r.raycastTile&&r.raycastTile(e,s,t,i)))||t.intersectObject(s,!0,i)}(t,r,e,i);let l=t.children;for(let c=0,h=l.length;c<h;c++)Dr(e,l[c],r,i,s)}var Or=new i.Vector3,Br=new i.Vector3,Nr=new i.Vector3,Vr=new i.Ray,zr=class{constructor(e=new i.Box3,t=new i.Matrix4){this.box=e.clone(),this.transform=t.clone(),this.inverseTransform=new i.Matrix4,this.points=Array(8).fill().map((()=>new i.Vector3)),this.planes=[,,,,,,].fill().map((()=>new i.Plane))}copy(e){return this.box.copy(e.box),this.transform.copy(e.transform),this.update(),this}clone(){return(new this.constructor).copy(this)}clampPoint(e,t){return t.copy(e).applyMatrix4(this.inverseTransform).clamp(this.box.min,this.box.max).applyMatrix4(this.transform)}distanceToPoint(e){return this.clampPoint(e,Nr).distanceTo(e)}containsPoint(e){return Nr.copy(e).applyMatrix4(this.inverseTransform),this.box.containsPoint(Nr)}intersectsRay(e){return Vr.copy(e).applyMatrix4(this.inverseTransform),Vr.intersectsBox(this.box)}intersectRay(e,t){return Vr.copy(e).applyMatrix4(this.inverseTransform),Vr.intersectBox(this.box,t)?(t.applyMatrix4(this.transform),t):null}update(){let{points:e,inverseTransform:t,transform:r,box:i}=this;t.copy(r).invert();let{min:s,max:n}=i,a=0;for(let o=-1;o<=1;o+=2)for(let t=-1;t<=1;t+=2)for(let i=-1;i<=1;i+=2)e[a].set(o<0?s.x:n.x,t<0?s.y:n.y,i<0?s.z:n.z).applyMatrix4(r),a++;this.updatePlanes()}updatePlanes(){Or.copy(this.box.min).applyMatrix4(this.transform),Br.copy(this.box.max).applyMatrix4(this.transform),Nr.set(0,0,1).transformDirection(this.transform),this.planes[0].setFromNormalAndCoplanarPoint(Nr,Or),this.planes[1].setFromNormalAndCoplanarPoint(Nr,Br).negate(),Nr.set(0,1,0).transformDirection(this.transform),this.planes[2].setFromNormalAndCoplanarPoint(Nr,Or),this.planes[3].setFromNormalAndCoplanarPoint(Nr,Br).negate(),Nr.set(1,0,0).transformDirection(this.transform),this.planes[4].setFromNormalAndCoplanarPoint(Nr,Or),this.planes[5].setFromNormalAndCoplanarPoint(Nr,Br).negate()}intersectsSphere(e){return this.clampPoint(e.center,Nr),Nr.distanceToSquared(e.center)<=e.radius*e.radius}intersectsFrustum(e){return this._intersectsPlaneShape(e.planes,e.points)}intersectsOBB(e){return this._intersectsPlaneShape(e.planes,e.points)}_intersectsPlaneShape(e,t){let r=this.points,i=this.planes;for(let s=0;s<6;s++){let t=e[s],i=-1/0;for(let e=0;e<8;e++){let s=r[e],n=t.distanceToPoint(s);i=i<n?n:i}if(i<0)return!1}for(let s=0;s<6;s++){let e=i[s],r=-1/0;for(let i=0;i<8;i++){let s=t[i],n=e.distanceToPoint(s);r=r<n?n:r}if(r<0)return!1}return!0}},Gr=Math.PI,Hr=Gr/2,jr=new i.Vector3,Wr=new i.Vector3,qr=new i.Vector3,Xr=new i.Vector3,Kr=new i.Matrix4,Yr=new i.Box3,Qr=new i.Matrix4;function $r(e,t){t.radius=Math.max(t.radius,e.distanceToSquared(t.center))}function Zr(e){return e.x!==e.y}var Jr=class extends gr{constructor(e=1,t=1,r=1,i=-Hr,s=Hr,n=0,a=2*Gr,o=0,l=0){super(e,t,r),this.latStart=i,this.latEnd=s,this.lonStart=n,this.lonEnd=a,this.heightStart=o,this.heightEnd=l}getBoundingBox(e,t){Zr(this.radius);let r,{latStart:i,latEnd:s,lonStart:n,lonEnd:a,heightStart:o,heightEnd:l}=this,c=.5*(i+s),h=.5*(n+a),u=i>0,d=s<0;r=u?i:d?s:0;let{min:p,max:m}=e;p.setScalar(1/0),m.setScalar(-1/0),a-n<=Gr?(this.getCartographicToNormal(c,h,qr),Wr.set(0,0,1),jr.crossVectors(Wr,qr).normalize(),Wr.crossVectors(qr,jr).normalize(),t.makeBasis(jr,Wr,qr),Kr.copy(t).invert(),this.getCartographicToPosition(r,n,l,Xr).applyMatrix4(Kr),m.x=Math.abs(Xr.x),p.x=-m.x,this.getCartographicToPosition(s,n,l,Xr).applyMatrix4(Kr),m.y=Xr.y,this.getCartographicToPosition(s,h,l,Xr).applyMatrix4(Kr),m.y=Math.max(Xr.y,m.y),this.getCartographicToPosition(i,n,l,Xr).applyMatrix4(Kr),p.y=Xr.y,this.getCartographicToPosition(i,h,l,Xr).applyMatrix4(Kr),p.y=Math.min(Xr.y,p.y),this.getCartographicToPosition(c,h,l,Xr).applyMatrix4(Kr),m.z=Xr.z,this.getCartographicToPosition(i,n,o,Xr).applyMatrix4(Kr),p.z=Xr.z,this.getCartographicToPosition(s,n,o,Xr).applyMatrix4(Kr),p.z=Math.min(Xr.z,p.z)):(this.getCartographicToPosition(r,h,l,qr),qr.z=0,qr.length()<1e-10?qr.set(1,0,0):qr.normalize(),Wr.set(0,0,1),jr.crossVectors(qr,Wr).normalize(),t.makeBasis(jr,Wr,qr),Kr.copy(t).invert(),this.getCartographicToPosition(r,h+Hr,l,Xr).applyMatrix4(Kr),m.x=Math.abs(Xr.x),p.x=-m.x,this.getCartographicToPosition(s,0,d?o:l,Xr).applyMatrix4(Kr),m.y=Xr.y,this.getCartographicToPosition(i,0,u?o:l,Xr).applyMatrix4(Kr),p.y=Xr.y,this.getCartographicToPosition(r,h,l,Xr).applyMatrix4(Kr),m.z=Xr.z,this.getCartographicToPosition(r,a,l,Xr).applyMatrix4(Kr),p.z=Xr.z),e.getCenter(Xr),e.min.sub(Xr).multiplyScalar(1.0000000000001),e.max.sub(Xr).multiplyScalar(1.0000000000001),Xr.applyMatrix4(t),t.setPosition(Xr)}getBoundingSphere(e){Zr(this.radius),this.getBoundingBox(Yr,Qr),e.center.setFromMatrixPosition(Qr),e.radius=0;let t,{latStart:r,latEnd:i,lonStart:s,lonEnd:n,heightStart:a,heightEnd:o}=this,l=.5*(r+i),c=.5*(s+n);t=r>0?r:i<0?i:0,this.getCartographicToPosition(t,s,o,Xr),$r(Xr,e),this.getCartographicToPosition(i,s,o,Xr),$r(Xr,e),this.getCartographicToPosition(i,c,o,Xr),$r(Xr,e),this.getCartographicToPosition(r,s,o,Xr),$r(Xr,e),this.getCartographicToPosition(r,c,o,Xr),$r(Xr,e),this.getCartographicToPosition(l,c,o,Xr),$r(Xr,e),this.getCartographicToPosition(r,s,a,Xr),$r(Xr,e),n-s>Gr&&(this.getCartographicToPosition(t,c+Gr,o,Xr),$r(Xr,e)),e.radius=1.0000000000001*Math.sqrt(e.radius)}},ei=new i.Vector3,ti=new i.Vector3,ri=new i.Vector3,ii=new i.Vector3,si=new i.Vector3,ni=class{constructor(){this.sphere=null,this.obb=null,this.region=null,this.regionObb=null}intersectsRay(e){let t=this.sphere,r=this.obb||this.regionObb;return!(t&&!e.intersectsSphere(t)||r&&!r.intersectsRay(e))}intersectRay(e,t=null){let r=this.sphere,i=this.obb||this.regionObb,s=-1/0,n=-1/0;r&&e.intersectSphere(r,ii)&&(s=r.containsPoint(e.origin)?0:e.origin.distanceToSquared(ii)),i&&i.intersectRay(e,si)&&(n=i.containsPoint(e.origin)?0:e.origin.distanceToSquared(si));let a=Math.max(s,n);return a===-1/0?null:(e.at(Math.sqrt(a),t),t)}distanceToPoint(e){let t=this.sphere,r=this.obb||this.regionObb,i=-1/0,s=-1/0;return t&&(i=Math.max(t.distanceToPoint(e),0)),r&&(s=r.distanceToPoint(e)),i>s?i:s}intersectsFrustum(e){let t=this.obb||this.regionObb,r=this.sphere;return!(r&&!e.intersectsSphere(r)||t&&!t.intersectsFrustum(e))&&!(!r&&!t)}intersectsSphere(e){let t=this.obb||this.regionObb,r=this.sphere;return!(r&&!r.intersectsSphere(e)||t&&!t.intersectsSphere(e))&&!(!r&&!t)}intersectsOBB(e){let t=this.obb||this.regionObb,r=this.sphere;return!(r&&!e.intersectsSphere(r)||t&&!t.intersectsOBB(e))&&!(!r&&!t)}getOBB(e,t){let r=this.obb||this.regionObb;r?(e.copy(r.box),t.copy(r.transform)):(this.getAABB(e),t.identity())}getAABB(e){if(this.sphere)this.sphere.getBoundingBox(e);else{let t=this.obb||this.regionObb;e.copy(t.box).applyMatrix4(t.transform)}}getSphere(e){if(this.sphere)e.copy(this.sphere);else if(this.region)this.region.getBoundingSphere(e);else{let t=this.obb||this.regionObb;t.box.getBoundingSphere(e),e.applyMatrix4(t.transform)}}setObbData(e,t){let r=new zr;ei.set(e[3],e[4],e[5]),ti.set(e[6],e[7],e[8]),ri.set(e[9],e[10],e[11]);let i=ei.length(),s=ti.length(),n=ri.length();ei.normalize(),ti.normalize(),ri.normalize(),0===i&&ei.crossVectors(ti,ri),0===s&&ti.crossVectors(ei,ri),0===n&&ri.crossVectors(ei,ti),r.transform.set(ei.x,ti.x,ri.x,e[0],ei.y,ti.y,ri.y,e[1],ei.z,ti.z,ri.z,e[2],0,0,0,1).premultiply(t),r.box.min.set(-i,-s,-n),r.box.max.set(i,s,n),r.update(),this.obb=r}setSphereData(e,t,r,s,n){let a=new i.Sphere;a.center.set(e,t,r),a.radius=s,a.applyMatrix4(n),this.sphere=a}setRegionData(e,t,r,i,s,n,a){let o=new Jr(...e.radius,r,s,t,i,n,a),l=new zr;o.getBoundingBox(l.box,l.transform),l.update(),this.region=o,this.regionObb=l}},ai=new i.Matrix3;var oi=class extends i.Frustum{constructor(){super(),this.points=Array(8).fill().map((()=>new i.Vector3))}setFromProjectionMatrix(...e){return super.setFromProjectionMatrix(...e),this.calculateFrustumPoints(),this}calculateFrustumPoints(){let{planes:e,points:t}=this;[[e[0],e[3],e[4]],[e[1],e[3],e[4]],[e[0],e[2],e[4]],[e[1],e[2],e[4]],[e[0],e[3],e[5]],[e[1],e[3],e[5]],[e[0],e[2],e[5]],[e[1],e[2],e[5]]].forEach(((e,r)=>{!function(e,t,r,i){let s=ai.set(e.normal.x,e.normal.y,e.normal.z,t.normal.x,t.normal.y,t.normal.z,r.normal.x,r.normal.y,r.normal.z);i.set(-e.constant,-t.constant,-r.constant),i.applyMatrix3(s.invert())}(e[0],e[1],e[2],t[r])}))}};function li(e,t,r,s){try{return i.TextureUtils.getByteLength(e,t,r,s)}catch{return 0}}function ci(e){var t,r;if(!e)return 0;if(e.isExternalTexture)return(null==(t=e.userData)?void 0:t.byteLength)??0;let{format:i,type:s,image:n,mipmaps:a}=e;if(e.isCompressedTexture&&Array.isArray(a)&&a.length>0){let e=0;for(let t of a)(null==(r=null==t?void 0:t.data)?void 0:r.byteLength)?e+=t.data.byteLength:e+=li(t.width,t.height,i,s);return e}if(!n)return 0;let o=li(n.width,n.height,i,s);return o*=e.generateMipmaps?4/3:1,o}var hi=Symbol("INITIAL_FRUSTUM_CULLED"),ui=new i.Matrix4,di=new i.Vector3,pi=new i.Vector2,mi=new i.Vector3(1,0,0),fi=new i.Vector3(0,1,0),gi=()=>null;function yi(e,t){e.traverse((e=>{e.frustumCulled=e[hi]&&t}))}var vi=class extends De{get autoDisableRendererCulling(){return this._autoDisableRendererCulling}set autoDisableRendererCulling(e){this._autoDisableRendererCulling!==e&&(super._autoDisableRendererCulling=e,this.forEachLoadedModel((t=>{yi(t,!e)})))}constructor(...e){super(...e),this.accelerateRaycast=!0,this.group=new Fr(this),this.ellipsoid=yr.clone(),this.cameras=[],this.cameraMap=new Map,this.cameraInfo=[],this._upRotationMatrix=new i.Matrix4,this._bytesUsed=new WeakMap,this._autoDisableRendererCulling=!0,this.manager=new i.LoadingManager,this._listeners={}}addEventListener(e,t){i.EventDispatcher.prototype.addEventListener.call(this,e,t)}hasEventListener(e,t){return i.EventDispatcher.prototype.hasEventListener.call(this,e,t)}removeEventListener(e,t){i.EventDispatcher.prototype.removeEventListener.call(this,e,t)}dispatchEvent(e){i.EventDispatcher.prototype.dispatchEvent.call(this,e)}getBoundingBox(e){if(!this.root)return!1;let t=this.root.engineData.boundingVolume;return!!t&&(t.getAABB(e),!0)}getOrientedBoundingBox(e,t){if(!this.root)return!1;let r=this.root.engineData.boundingVolume;return!!r&&(r.getOBB(e,t),!0)}getBoundingSphere(e){if(!this.root)return!1;let t=this.root.engineData.boundingVolume;return!!t&&(t.getSphere(e),!0)}forEachLoadedModel(e){this.traverse((t=>{let r=t.engineData&&t.engineData.scene;r&&e(r,t)}),null,!1)}raycast(e,t){if(this.root)if(this.accelerateRaycast)Dr(this,this.root,e,t);else{let r=e.firstHitOnly?[]:t;for(let t of this.activeTiles){let{scene:i}=t.engineData;this.invokeOnePlugin((s=>s.raycastTile&&s.raycastTile(t,i,e,r)))||e.intersectObject(i,!0,r)}e.firstHitOnly&&r.length>0&&(r.sort(((e,t)=>e.distance-t.distance)),t.push(r[0]))}}hasCamera(e){return this.cameraMap.has(e)}setCamera(e){let t=this.cameras,r=this.cameraMap;return!r.has(e)&&(r.set(e,new i.Vector2),t.push(e),this.dispatchEvent({type:"add-camera",camera:e}),!0)}setResolution(e,t,r){let i=this.cameraMap;if(!i.has(e))return!1;let s=t.isVector2?t.x:t,n=t.isVector2?t.y:r,a=i.get(e);return(a.width!==s||a.height!==n)&&(a.set(s,n),this.dispatchEvent({type:"camera-resolution-change"})),!0}getResolution(e,t){let r=this.cameraMap.get(e);return r?t.copy(r):null}setResolutionFromRenderer(e,t){return t.getSize(pi),this.setResolution(e,pi.x,pi.y)}deleteCamera(e){let t=this.cameras,r=this.cameraMap;if(r.has(e)){let i=t.indexOf(e);return t.splice(i,1),r.delete(e),this.dispatchEvent({type:"delete-camera",camera:e}),!0}return!1}loadRootTileset(...e){return super.loadRootTileset(...e).then((e=>{let{asset:t,extensions:r={}}=e;switch((t&&t.gltfUpAxis||"y").toLowerCase()){case"x":this._upRotationMatrix.makeRotationAxis(fi,-Math.PI/2);break;case"y":this._upRotationMatrix.makeRotationAxis(mi,Math.PI/2)}if("3DTILES_ellipsoid"in r){let e=r["3DTILES_ellipsoid"],{ellipsoid:t}=this;t.name=e.body,e.radii?t.radius.set(...e.radii):t.radius.set(1,1,1)}return e}))}prepareForTraversal(){let e=this.group,t=this.cameras,r=this.cameraMap,s=this.cameraInfo;for(;s.length>t.length;)s.pop();for(;s.length<t.length;)s.push({frustum:new oi,isOrthographic:!1,sseDenominator:-1,position:new i.Vector3,invScale:-1,pixelSize:0});di.setFromMatrixScale(e.matrixWorldInverse),Math.abs(Math.max(di.x-di.y,di.x-di.z));for(let i=0,n=s.length;i<n;i++){let n=t[i],a=s[i],o=a.frustum,l=a.position,c=r.get(n);0===c.width||c.height;let h=n.projectionMatrix.elements;if(a.isOrthographic=1===h[15],a.isOrthographic){let e=2/h[0],t=2/h[5];a.pixelSize=Math.max(t/c.height,e/c.width)}else a.sseDenominator=2/h[5]/c.height;ui.copy(e.matrixWorld),ui.premultiply(n.matrixWorldInverse),ui.premultiply(n.projectionMatrix),o.setFromProjectionMatrix(ui,n.coordinateSystem,n.reversedDepth),l.set(0,0,0),l.applyMatrix4(n.matrixWorld),l.applyMatrix4(e.matrixWorldInverse)}}update(){if(super.update(),0===this.cameras.length&&this.root){let e=!1;this.invokeAllPlugins((t=>e||(e=!(t===this||!t.calculateTileViewError))))}}preprocessNode(e,t,r=null){super.preprocessNode(e,t,r);let s=new i.Matrix4;if(e.transform){let t=e.transform;for(let e=0;e<16;e++)s.elements[e]=t[e]}r&&s.premultiply(r.engineData.transform);let n=(new i.Matrix4).copy(s).invert(),a=new ni;"sphere"in e.boundingVolume&&a.setSphereData(...e.boundingVolume.sphere,s),"box"in e.boundingVolume&&a.setObbData(e.boundingVolume.box,s),"region"in e.boundingVolume&&a.setRegionData(this.ellipsoid,...e.boundingVolume.region),e.engineData.transform=s,e.engineData.transformInverse=n,e.engineData.boundingVolume=a,e.engineData.geometry=null,e.engineData.materials=null,e.engineData.textures=null,e.toJSON=gi}async parseTile(e,t,r,s,n){let a=t.engineData,o=Ve(s),l=this.fetchOptions,c=this.manager,h=null,u=a.transform,d=this._upRotationMatrix,p=(Oe(e)||r).toLowerCase();switch(p){case"b3dm":{let t=new $t(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),h=t.parse(e);break}case"pnts":{let t=new rr(c);t.workingPath=o,t.fetchOptions=l,h=t.parse(e);break}case"i3dm":{let t=new Lr(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),t.ellipsoid.copy(this.ellipsoid),h=t.parse(e);break}case"cmpt":{let t=new Ur(c);t.workingPath=o,t.fetchOptions=l,t.adjustmentTransform.copy(d),t.ellipsoid.copy(this.ellipsoid),h=t.parse(e).then((e=>e.scene));break}case"gltf":case"glb":{let t=c.getHandler("path.gltf")||c.getHandler("path.glb")||new Je(c);t.setWithCredentials("include"===l.credentials),t.setRequestHeader(l.headers||{}),"include"===l.credentials&&"cors"===l.mode&&t.setCrossOrigin("use-credentials");let r=t.resourcePath||t.path||o;!/[\\/]$/.test(r)&&r.length&&(r+="/"),h=t.parseAsync(e,r).then((e=>{e.scene=e.scene||new i.Group;let{scene:t}=e;return t.updateMatrix(),t.matrix.multiply(d).decompose(t.position,t.quaternion,t.scale),e}));break}default:h=this.invokeOnePlugin((i=>i.parseToMesh&&i.parseToMesh(e,t,r,s,n)))}let m,f,g=await h;if(null===g)throw Error(`TilesRenderer: Content type "${p}" not supported.`);g.isObject3D?(m=g,f=null):(m=g.scene,f=g),m.updateMatrix(),m.matrix.premultiply(u),m.matrix.decompose(m.position,m.quaternion,m.scale),await this.invokeAllPlugins((e=>e.processTileModel&&e.processTileModel(m,t))),m.traverse((e=>{e[hi]=e.frustumCulled,e.userData.tile=t})),yi(m,!this.autoDisableRendererCulling);let y=[],v=[],T=[];if(m.traverse((e=>{if(e.geometry&&v.push(e.geometry),e.material){let t=e.material;y.push(e.material);for(let e in t){let r=t[e];r&&r.isTexture&&T.push(r)}}})),n.aborted)for(let i=0,x=T.length;i<x;i++){let e=T[i];e.image instanceof ImageBitmap&&e.image.close(),e.dispose()}else a.materials=y,a.geometry=v,a.textures=T,a.scene=m,a.metadata=f}disposeTile(e){super.disposeTile(e);let t=e.engineData;if(t.scene){let e=t.materials,r=t.geometry,i=t.textures,s=t.scene.parent;t.scene.traverse((e=>{e.userData.meshFeatures&&e.userData.meshFeatures.dispose(),e.userData.structuralMetadata&&e.userData.structuralMetadata.dispose()}));for(let t=0,n=r.length;t<n;t++)r[t].dispose();for(let t=0,n=e.length;t<n;t++)e[t].dispose();for(let t=0,n=i.length;t<n;t++){let e=i[t];e.image instanceof ImageBitmap&&e.image.close(),e.dispose()}s&&s.remove(t.scene),t.scene=null,t.materials=null,t.textures=null,t.geometry=null,t.metadata=null}}setTileActive(e,t){super.setTileActive(e,t);let r=e.engineData.scene;r&&(t?(r.parent=this.group,r.updateMatrixWorld(!0)):r.parent=null)}setTileVisible(e,t){let r=e.engineData.scene,{activeTiles:i,group:s}=this;r&&(t?s.add(r):(s.remove(r),i.has(e)&&(r.parent=s))),super.setTileVisible(e,t)}calculateBytesUsed(e,t){let r=this._bytesUsed;return!r.has(e)&&t&&r.set(e,function(e){let t=new Set,r=0;return e.traverse((e=>{if(e.geometry&&!t.has(e.geometry)&&(r+=function(e){let t=0;for(const i in e.attributes){const r=e.getAttribute(i);t+=r.count*r.itemSize*r.array.BYTES_PER_ELEMENT}const r=e.getIndex();return t+=r?r.count*r.itemSize*r.array.BYTES_PER_ELEMENT:0,t}(e.geometry),t.add(e.geometry)),e.material){let i=e.material;for(let e in i){let s=i[e];s&&s.isTexture&&!t.has(s)&&(r+=ci(s),t.add(s))}}})),r}(t)),r.get(e)??null}calculateTileViewError(e,t){let r=e.engineData,i=this.cameras,s=this.cameraInfo,n=r.boundingVolume,a=!1,o=0,l=1/0,c=0,h=1/0;for(let u=0,d=i.length;u<d;u++){let t,r,i=s[u];if(i.isOrthographic){let s=i.pixelSize;t=e.geometricError/s,r=1/0}else{let s=i.sseDenominator;r=n.distanceToPoint(i.position),t=0===r?1/0:e.geometricError/(r*s)}let d=s[u].frustum;n.intersectsFrustum(d)&&(a=!0,o=Math.max(o,t),l=Math.min(l,r)),c=Math.max(c,t),h=Math.min(h,r)}a?(t.inView=!0,t.error=o,t.distanceFromCamera=l):(t.inView=!1,t.error=c,t.distanceFromCamera=h)}dispose(){super.dispose(),this.group.removeFromParent()}};const Ti=new i.Matrix4,xi=new i.Matrix4,bi=new i.Vector3,_i=new i.Vector3,wi=new i.Vector3,Mi=new i.Vector3,Si=new i.Vector3,Ai=new i.Vector3,Ci=new i.Quaternion,Ei=new i.Vector3,Ri=new i.Vector3,Pi=new i.Ray,Li=new gr,Ui=new i.Vector2,Ii={};class Fi extends ie{get tilesGroup(){return this.ellipsoidFrame}get ellipsoidFrame(){return this.ellipsoidGroup.matrixWorld}get ellipsoidFrameInverse(){const{ellipsoidGroup:e,ellipsoidFrame:t,_ellipsoidFrameInverse:r}=this;return e.matrixWorldInverse?e.matrixWorldInverse:r.copy(t).invert()}constructor(e=null,t=null,r=null,s=null){super(e,t,r),this.isGlobeControls=!0,this._dragMode=0,this._rotationMode=0,this.maxZoom=.01,this.nearMargin=.25,this.farMargin=0,this.useFallbackPlane=!1,this.autoAdjustCameraRotation=!1,this.globeInertia=new i.Quaternion,this.globeInertiaFactor=0,this.ellipsoid=yr.clone(),this.ellipsoidGroup=new i.Group,this._ellipsoidFrameInverse=new i.Matrix4,null!==s&&this.setTilesRenderer(s)}setTilesRenderer(e){super.setTilesRenderer(e),null!==e&&this.setEllipsoid(e.ellipsoid,e.group)}setEllipsoid(e,t){this.ellipsoid=e||yr.clone(),this.ellipsoidGroup=t||new i.Group}getPivotPoint(e){const{camera:t,ellipsoidFrame:r,ellipsoidFrameInverse:i,ellipsoid:s}=this;return Mi.set(0,0,-1).transformDirection(t.matrixWorld),Pi.origin.copy(t.position),Pi.direction.copy(Mi),Pi.applyMatrix4(i),s.closestPointToRayEstimate(Pi,_i).applyMatrix4(r),(null===super.getPivotPoint(e)||bi.subVectors(e,Pi.origin).dot(Pi.direction)>bi.subVectors(_i,Pi.origin).dot(Pi.direction))&&e.copy(_i),e}getVectorToCenter(e){const{ellipsoidFrame:t,camera:r}=this;return e.setFromMatrixPosition(t).sub(r.position)}getDistanceToCenter(){return this.getVectorToCenter(_i).length()}getUpDirection(e,t){const{ellipsoidFrame:r,ellipsoidFrameInverse:i,ellipsoid:s}=this;_i.copy(e).applyMatrix4(i),s.getPositionToNormal(_i,t),t.transformDirection(r)}getCameraUpDirection(e){const{ellipsoidFrame:t,ellipsoidFrameInverse:r,ellipsoid:i,camera:s}=this;s.isOrthographicCamera?(this._getVirtualOrthoCameraPosition(_i),_i.applyMatrix4(r),i.getPositionToNormal(_i,e),e.transformDirection(t)):this.getUpDirection(s.position,e)}update(e=Math.min(this.clock.getDelta(),.064)){if(!this.enabled||!this.camera||0===e)return;const{camera:t,pivotMesh:r}=this;this._isNearControls()?this.scaleZoomOrientationAtEdges=this.zoomDelta<0:(0!==this.state&&1!==this._dragMode&&1!==this._rotationMode&&(r.visible=!1),this.scaleZoomOrientationAtEdges=!1);const i=this.needsUpdate||this._inertiaNeedsUpdate();super.update(e),this.adjustCamera(t),i&&this._isNearControls()&&(this.getCameraUpDirection(Ai),this._alignCameraUp(Ai,1),this.getCameraUpDirection(Ai),this._clampRotation(Ai))}adjustCamera(e){super.adjustCamera(e);const{ellipsoidFrame:t,ellipsoidFrameInverse:r,ellipsoid:s,nearMargin:n,farMargin:a}=this,o=Math.max(...s.radius);if(e.isPerspectiveCamera){const l=_i.setFromMatrixPosition(t).sub(e.position).length(),c=n*o,h=i.MathUtils.clamp((l-o)/c,0,1),u=i.MathUtils.lerp(1,1e3,h);e.near=Math.max(u,l-o-c),bi.copy(e.position).applyMatrix4(r),s.getPositionToCartographic(bi,Ii);const d=Math.max(s.getPositionElevation(bi),2550),p=s.calculateHorizonDistance(Ii.lat,d);e.far=p+.1+o*a,e.updateProjectionMatrix()}else{this._getVirtualOrthoCameraPosition(e.position,e),e.updateMatrixWorld(),Ti.copy(e.matrixWorld).invert(),_i.setFromMatrixPosition(t).applyMatrix4(Ti);const r=-_i.z;e.near=r-o*(1+n),e.far=r+.1+o*a,e.position.addScaledVector(Mi,e.near),e.far-=e.near,e.near=0,e.updateProjectionMatrix(),e.updateMatrixWorld()}}setState(...e){super.setState(...e),this._dragMode=0,this._rotationMode=0}_updateInertia(e){super._updateInertia(e);const{globeInertia:t,enableDamping:r,dampingFactor:i,camera:s,cameraRadius:n,minDistance:a,inertiaTargetDistance:o,ellipsoidFrame:l}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return this.globeInertiaFactor=0,void this.globeInertia.identity();const c=Math.pow(2,-e/i),h=Math.max(s.near,n,a,o),u=25e-5;if(wi.setFromMatrixPosition(l),0!==this.globeInertiaFactor){E(Pi,_i.set(0,0,-1),s),Pi.applyMatrix4(s.matrixWorldInverse),Pi.direction.normalize(),Pi.recast(-Pi.direction.dot(Pi.origin)).at(h/Pi.direction.z,_i),_i.applyMatrix4(s.matrixWorld),E(Pi,bi.set(u,u,-1),s),Pi.applyMatrix4(s.matrixWorldInverse),Pi.direction.normalize(),Pi.recast(-Pi.direction.dot(Pi.origin)).at(h/Pi.direction.z,bi),bi.applyMatrix4(s.matrixWorld),_i.sub(wi).normalize(),bi.sub(wi).normalize(),this.globeInertiaFactor*=c;const i=_i.angleTo(bi)/e;(2*Math.acos(t.w)*this.globeInertiaFactor<i||!r)&&(this.globeInertiaFactor=0,t.identity())}0!==this.globeInertiaFactor&&(1!==t.w||0===t.x&&0===t.y&&0===t.z||(t.w=Math.min(t.w,1-1e-9)),wi.setFromMatrixPosition(l),Ci.identity().slerp(t,this.globeInertiaFactor*e),A(wi,Ci,xi),s.matrixWorld.premultiply(xi),s.matrixWorld.decompose(s.position,s.quaternion,_i))}_inertiaNeedsUpdate(){return super._inertiaNeedsUpdate()||0!==this.globeInertiaFactor}_updatePosition(e){if(1===this.state){0===this._dragMode&&(this._dragMode=this._isNearControls()?1:-1);const{raycaster:t,camera:r,pivotPoint:i,pointerTracker:s,domElement:n,ellipsoidFrame:a,ellipsoidFrameInverse:o}=this,l=bi,c=Si;s.getCenterPoint(Ui),C(Ui,n,Ui),E(t,Ui,r),t.ray.applyMatrix4(o);const h=_i.copy(i).applyMatrix4(o).length();if(Li.radius.setScalar(h),!Li.intersectRay(t.ray,_i))return this.resetState(),void this._updateInertia(e);_i.applyMatrix4(a),wi.setFromMatrixPosition(a),l.subVectors(i,wi).normalize(),c.subVectors(_i,wi).normalize(),Ci.setFromUnitVectors(c,l),A(wi,Ci,xi),r.matrixWorld.premultiply(xi),r.matrixWorld.decompose(r.position,r.quaternion,_i),s.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(this.globeInertia.copy(Ci),this.globeInertiaFactor=1/e,this.inertiaStableFrames=0)}}_updateRotation(...e){1===this._rotationMode||this._isNearControls()?(this._rotationMode=1,super._updateRotation(...e)):(this.pivotMesh.visible=!1,this._rotationMode=-1)}_updateZoom(){const{zoomDelta:e,ellipsoid:t,zoomSpeed:r,zoomPoint:s,camera:n,maxZoom:a,state:o}=this;if(3!==o&&0===e)return;this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),this.globeInertia.identity(),this.globeInertiaFactor=0;const l=i.MathUtils.clamp(i.MathUtils.mapLinear(Math.abs(e),0,20,0,1),0,1);if(this._isNearControls()||e>0){if(this._updateZoomDirection(),e<0&&(this.zoomPointSet||this._updateZoomPoint())){Mi.set(0,0,-1).transformDirection(n.matrixWorld).normalize(),Ri.copy(this.up).multiplyScalar(-1),this.getUpDirection(s,Ei);const e=i.MathUtils.clamp(i.MathUtils.mapLinear(-Ei.dot(Ri),1,.95,0,1),0,1),t=1-Mi.dot(Ri),r=n.isOrthographicCamera?.05:1,a=i.MathUtils.clamp(3*l,0,1),o=Math.min(e*t*r*a,.1);Ri.lerpVectors(Mi,Ri,o).normalize(),Ci.setFromUnitVectors(Mi,Ri),A(s,Ci,xi),n.matrixWorld.premultiply(xi),n.matrixWorld.decompose(n.position,n.quaternion,Ri),this.zoomDirection.subVectors(s,n.position).normalize()}super._updateZoom()}else if(n.isPerspectiveCamera){const s=this._getPerspectiveTransitionDistance(),n=this._getMaxPerspectiveDistance(),a=i.MathUtils.mapLinear(this.getDistanceToCenter(),s,n,0,1);this._tiltTowardsCenter(i.MathUtils.lerp(0,.4,a*l)),this._alignCameraUpToNorth(i.MathUtils.lerp(0,.2,a*l));const o=e*(this.getDistanceToCenter()-t.radius.x)*r*.0025,c=Math.max(o,Math.min(this.getDistanceToCenter()-n,0));this.getVectorToCenter(_i).normalize(),this.camera.position.addScaledVector(_i,c),this.camera.updateMatrixWorld(),this.zoomDelta=0}else{const e=this._getOrthographicTransitionZoom(),t=this._getMinOrthographicZoom(),s=i.MathUtils.mapLinear(n.zoom,e,t,0,1);this._tiltTowardsCenter(i.MathUtils.lerp(0,.4,s*l)),this._alignCameraUpToNorth(i.MathUtils.lerp(0,.2,s*l));const o=this.zoomDelta,c=Math.pow(.95,Math.abs(.05*o)),h=o>0?1/Math.abs(c):c,u=t/n.zoom,d=Math.max(h*r,Math.min(u,1));n.zoom=Math.min(a,n.zoom*d),n.updateProjectionMatrix(),this.zoomDelta=0,this.zoomDirectionSet=!1}}_alignCameraUpToNorth(e){const{ellipsoidFrame:t}=this;Ai.set(0,0,1).transformDirection(t),this._alignCameraUp(Ai,e)}_tiltTowardsCenter(e){const{camera:t,ellipsoidFrame:r}=this;Mi.set(0,0,-1).transformDirection(t.matrixWorld).normalize(),_i.setFromMatrixPosition(r).sub(t.position).normalize(),_i.lerp(Mi,1-e).normalize(),Ci.setFromUnitVectors(Mi,_i),t.quaternion.premultiply(Ci),t.updateMatrixWorld()}_getPerspectiveTransitionDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const r=Math.max(...t.radius),s=2*Math.atan(Math.tan(i.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),n=r/Math.tan(i.MathUtils.DEG2RAD*e.fov*.5),a=r/Math.tan(.5*s);return Math.max(n,a)}_getMaxPerspectiveDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const r=Math.max(...t.radius),s=2*Math.atan(Math.tan(i.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),n=r/Math.tan(i.MathUtils.DEG2RAD*e.fov*.5),a=r/Math.tan(.5*s);return 2*Math.max(n,a)}_getOrthographicTransitionZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const r=e.top-e.bottom,i=e.right-e.left;return 2*Math.max(r,i)/(2*Math.max(...t.radius))}_getMinOrthographicZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const r=e.top-e.bottom,i=e.right-e.left;return.7*Math.min(r,i)/(2*Math.max(...t.radius))}_getVirtualOrthoCameraPosition(e,t=this.camera){const{ellipsoidFrame:r,ellipsoidFrameInverse:i,ellipsoid:s}=this;if(!t.isOrthographicCamera)throw new Error;Pi.origin.copy(t.position),Pi.direction.set(0,0,-1).transformDirection(t.matrixWorld),Pi.applyMatrix4(i),s.closestPointToRayEstimate(Pi,bi).applyMatrix4(r);const n=t.top-t.bottom,a=t.right-t.left,o=Math.max(n,a)/t.zoom;Mi.set(0,0,-1).transformDirection(t.matrixWorld);const l=bi.sub(t.position).dot(Mi);e.copy(t.position).addScaledVector(Mi,l-4*o)}_isNearControls(){const{camera:e}=this;return e.isPerspectiveCamera?this.getDistanceToCenter()<this._getPerspectiveTransitionDistance():e.zoom>this._getOrthographicTransitionZoom()}_raycast(e){const t=super._raycast(e);if(null===t){const{ellipsoid:t,ellipsoidFrame:r,ellipsoidFrameInverse:i}=this;Pi.copy(e.ray).applyMatrix4(i);const s=t.intersectRay(Pi,_i);return null!==s?{point:s.clone().applyMatrix4(r)}:null}return t}}const ki=new WeakMap,Di="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-decoder-c55a594e8ffd.wasm").href:new URL("assets/viewer/draco-decoder-c55a594e8ffd.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Oi="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-wasm-wrapper-e8049906ef3f.js").href:new URL("assets/viewer/draco-wasm-wrapper-e8049906ef3f.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Bi="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/draco-decoder-30e4d486fa02.js").href:new URL("assets/viewer/draco-decoder-30e4d486fa02.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href;class Ni extends i.Loader{constructor(e){super(e),this.decoderPaths={js:Oi,wasm:Di,dep_js:Bi},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){const{decoderPaths:t}=this;return"object"==typeof e?(t.js=e.js,t.wasm=e.wasm,t.dep_js=null):(t.js=i.LoaderUtils.resolveURL("draco_wasm_wrapper.js",e),t.wasm=i.LoaderUtils.resolveURL("draco_decoder.wasm",e),t.dep_js=i.LoaderUtils.resolveURL("draco_decoder.js",e)),this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,r,s){const n=new i.FileLoader(this.manager);n.setPath(this.path),n.setResponseType("arraybuffer"),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials),n.load(e,(e=>{this.parse(e,t,s)}),r,s)}parse(e,t,r=()=>{}){this.decodeDracoFile(e,t,null,null,i.SRGBColorSpace,r).catch(r)}decodeDracoFile(e,t,r,s,n=i.LinearSRGBColorSpace,a=()=>{}){const o={attributeIDs:r||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!r,vertexColorSpace:n};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const r=JSON.stringify(t);if(ki.has(e)){const t=ki.get(e);if(t.key===r)return t.promise;if(0===e.byteLength)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i;const s=this.workerNextTaskID++,n=e.byteLength,a=this._getWorker(s,n).then((r=>(i=r,new Promise(((r,n)=>{i._callbacks[s]={resolve:r,reject:n},i.postMessage({type:"decode",id:s,taskConfig:t,buffer:e},[e])}))))).then((e=>this._createGeometry(e.geometry)));return a.catch((()=>!0)).then((()=>{i&&s&&this._releaseTask(i,s)})),ki.set(e,{key:r,promise:a}),a}_createGeometry(e){const t=new i.BufferGeometry;e.index&&t.setIndex(new i.BufferAttribute(e.index.array,1));for(let r=0;r<e.attributes.length;r++){const{name:s,array:n,itemSize:a,stride:o,vertexColorSpace:l}=e.attributes[r];let c;if(a===o)c=new i.BufferAttribute(n,a);else{const e=new i.InterleavedBuffer(n,o);c=new i.InterleavedBufferAttribute(e,a,0)}"color"===s&&(this._assignVertexColorSpace(c,l),c.normalized=n instanceof Float32Array==!1),t.setAttribute(s,c)}return t}_assignVertexColorSpace(e,t){if(t!==i.SRGBColorSpace)return;const r=new i.Color;for(let s=0,n=e.count;s<n;s++)r.fromBufferAttribute(e,s),i.ColorManagement.colorSpaceToWorking(r,i.SRGBColorSpace),e.setXYZ(s,r.r,r.g,r.b)}_loadLibrary(e,t){const r=new i.FileLoader(this.manager);return r.setResponseType(t),r.setWithCredentials(this.withCredentials),new Promise(((t,i)=>{r.load(e,t,void 0,i)}))}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e="object"!=typeof WebAssembly||"js"===this.decoderConfig.type,t=[],{decoderPaths:r}=this;if(e){if(null===r.dep_js)throw new Error("THREE.DRACOLoader: WebAssembly is required when using a custom decoder paths.");t.push(this._loadLibrary(r.dep_js,"text"))}else t.push(this._loadLibrary(r.js,"text")),t.push(this._loadLibrary(r.wasm,"arraybuffer"));return this.decoderPending=Promise.all(t).then((t=>{const r=t[0];e||(this.decoderConfig.wasmBinary=t[1]);const i=Vi.toString(),s=["/* draco decoder */",r,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([s]))})),this.decoderPending}_getWorker(e,t){return this._initDecoder().then((()=>{if(this.workerPool.length<this.workerLimit){const e=new Worker(this.workerSourceURL);e._callbacks={},e._taskCosts={},e._taskLoad=0,e.postMessage({type:"init",decoderConfig:this.decoderConfig}),e.onmessage=function(t){const r=t.data;switch(r.type){case"decode":e._callbacks[r.id].resolve(r);break;case"error":e._callbacks[r.id].reject(r)}},this.workerPool.push(e)}else this.workerPool.sort((function(e,t){return e._taskLoad>t._taskLoad?-1:1}));const r=this.workerPool[this.workerPool.length-1];return r._taskCosts[e]=t,r._taskLoad+=t,r}))}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){}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 Vi(){let e,t;function r(e,t,r,i,s,n){const a=r.num_points(),o=n.num_components(),l=function(e,t){switch(t){case Float32Array:return e.DT_FLOAT32;case Int8Array:return e.DT_INT8;case Int16Array:return e.DT_INT16;case Int32Array:return e.DT_INT32;case Uint8Array:return e.DT_UINT8;case Uint16Array:return e.DT_UINT16;case Uint32Array:return e.DT_UINT32}}(e,s),c=o*s.BYTES_PER_ELEMENT,h=4*Math.ceil(c/4),u=h/s.BYTES_PER_ELEMENT,d=a*c,p=a*h,m=e._malloc(d);t.GetAttributeDataArrayForAllPoints(r,n,l,d,m);const f=new s(e.HEAPF32.buffer,m,d/s.BYTES_PER_ELEMENT);let g;if(c===h)g=f.slice();else{g=new s(p/s.BYTES_PER_ELEMENT);let e=0;for(let t=0,r=f.length;t<r;t++){for(let r=0;r<o;r++)g[e+r]=f[t*o+r];e+=u}}return e._free(m),{name:i,count:a,itemSize:o,array:g,stride:u}}onmessage=function(i){const s=i.data;switch(s.type){case"init":e=s.decoderConfig,t=new Promise((function(t){e.onModuleLoaded=function(e){t({draco:e})},DracoDecoderModule(e)}));break;case"decode":const i=s.buffer,n=s.taskConfig;t.then((e=>{const t=e.draco,a=new t.Decoder;try{const e=function(e,t,i,s){const n=s.attributeIDs,a=s.attributeTypes;let o,l;const c=t.GetEncodedGeometryType(i);if(c===e.TRIANGULAR_MESH)o=new e.Mesh,l=t.DecodeArrayToMesh(i,i.byteLength,o);else{if(c!==e.POINT_CLOUD)throw new Error("THREE.DRACOLoader: Unexpected geometry type.");o=new e.PointCloud,l=t.DecodeArrayToPointCloud(i,i.byteLength,o)}if(!l.ok()||0===o.ptr)throw new Error("THREE.DRACOLoader: Decoding failed: "+l.error_msg());const h={index:null,attributes:[]};for(const u in n){const i=self[a[u]];let l,c;if(s.useUniqueIDs)c=n[u],l=t.GetAttributeByUniqueId(o,c);else{if(c=t.GetAttributeId(o,e[n[u]]),-1===c)continue;l=t.GetAttribute(o,c)}const d=r(e,t,o,u,i,l);"color"===u&&(d.vertexColorSpace=s.vertexColorSpace),h.attributes.push(d)}c===e.TRIANGULAR_MESH&&(h.index=function(e,t,r){const i=r.num_faces(),s=3*i,n=4*s,a=e._malloc(n);t.GetTrianglesUInt32Array(r,n,a);const o=new Uint32Array(e.HEAPF32.buffer,a,s).slice();return e._free(a),{array:o,itemSize:1}}(e,t,o));return e.destroy(o),h}(t,a,new Int8Array(i),n),o=e.attributes.map((e=>e.array.buffer));e.index&&o.push(e.index.array.buffer),self.postMessage({type:"decode",id:s.id,geometry:e},o)}catch(o){self.postMessage({type:"error",id:s.id,error:o.message})}finally{t.destroy(a)}}))}}}let zi=class{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const r=this.workersResolve[e];if(r&&r(t),this.queue.length){const{resolve:t,msg:r,transfer:i}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(r,i)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((r=>{const i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<<i,this.workersResolve[i]=r,this.workers[i].postMessage(e,t)):this.queue.push({resolve:r,msg:e,transfer:t})}))}dispose(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};const Gi=9,Hi=15,ji=16,Wi=22,qi=37,Xi=43,Ki=76,Yi=83,Qi=91,$i=97,Zi=100,Ji=103,es=109,ts=122,rs=123,is=131,ss=132,ns=133,as=134,os=137,ls=138,cs=139,hs=140,us=141,ds=142,ps=145,ms=146,fs=148,gs=152,ys=153,vs=154,Ts=155,xs=156,bs=157,_s=158,ws=165,Ms=166,Ss=1000054e3,As=1000054001,Cs=1000054004,Es=1000054005,Rs=1000066e3,Ps=1000066004;class Ls{constructor(e,t,r,i){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,r),this._littleEndian=i,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t=0){const r=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==t&&i<e;)i++,this._offset++;return i<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+r,i)}}const Us=[171,75,84,88,32,50,48,187,13,10,26,10];function Is(e){return(new TextDecoder).decode(e)}let Fs,ks,Ds;const Os={env:{emscripten_notify_memory_growth:function(e){Ds=new Uint8Array(ks.exports.memory.buffer)}}};class Bs{init(){return Fs||(Fs="undefined"!=typeof fetch?fetch("undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/zstd-decoder-67d12d34f82e.wasm").href:new URL("assets/viewer/zstd-decoder-67d12d34f82e.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,Os))).then(this._init):fetch("undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/zstd-decoder-67d12d34f82e.wasm").href:new URL("assets/viewer/zstd-decoder-67d12d34f82e.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,Os))).then(this._init),Fs)}_init(e){ks=e.instance,Os.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!ks)throw new Error("ZSTDDecoder: Await .init() before decoding.");const r=e.byteLength,i=ks.exports.malloc(r);Ds.set(e,i),t=t||Number(ks.exports.ZSTD_findDecompressedSize(i,r));const s=ks.exports.malloc(t),n=ks.exports.ZSTD_decompress(s,t,i,r),a=Ds.slice(s,s+n);return ks.exports.free(i),ks.exports.free(s),a}}i.ColorManagement.spaces[i.SRGBColorSpace];const Ns="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/basis-transcoder-6cf17dc88935.wasm").href:new URL("assets/viewer/basis-transcoder-6cf17dc88935.wasm",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,Vs="undefined"==typeof document?require("url").pathToFileURL(__dirname+"/assets/viewer/basis-transcoder-8478b5b6d6b7.js").href:new URL("assets/viewer/basis-transcoder-8478b5b6d6b7.js",document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||document.baseURI).href,zs=new WeakMap;let Gs;class Hs extends i.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new zi,this.workerSourceURL="",this.workerConfig=null}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return await e.init(),this.detectSupport(e)}detectSupport(e){return!0===e.isWebGPURenderer?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-s3tc"),bptcSupported:e.hasFeature("texture-compression-bc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:(this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:e.extensions.has("WEBGL_compressed_texture_astc")&&e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},"undefined"!=typeof navigator&&void 0!==navigator.platform&&void 0!==navigator.userAgent&&navigator.platform.indexOf("Linux")>=0&&navigator.userAgent.indexOf("Android")<0&&this.workerConfig.astcSupported&&this.workerConfig.etc2Supported&&this.workerConfig.bptcSupported&&this.workerConfig.dxtSupported&&(this.workerConfig.astcSupported=!1,this.workerConfig.etc1Supported=!1,this.workerConfig.etc2Supported=!1)),this}init(){if(!this.transcoderPending){const e=new i.FileLoader(this.manager);e.setWithCredentials(this.withCredentials);const t=new i.FileLoader(this.manager);let r,s;t.setWithCredentials(this.withCredentials),t.setResponseType("arraybuffer"),""===this.transcoderPath?(r=e.loadAsync(Vs),s=t.loadAsync(Ns)):(e.setPath(this.transcoderPath),r=e.loadAsync("basis_transcoder.js"),t.setPath(this.transcoderPath),s=t.loadAsync("basis_transcoder.wasm")),this.transcoderPending=Promise.all([r,s]).then((([e,t])=>{const r=Hs.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(Hs.EngineFormat),"let _EngineType = "+JSON.stringify(Hs.EngineType),"let _TranscoderFormat = "+JSON.stringify(Hs.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Hs.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([i])),this.transcoderBinary=t,this.workerPool.setWorkerCreator((()=>{const e=new Worker(this.workerSourceURL),t=this.transcoderBinary.slice(0);return e.postMessage({type:"init",config:this.workerConfig,transcoderBinary:t},[t]),e}))}))}return this.transcoderPending}load(e,t,r,s){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const n=new i.FileLoader(this.manager);n.setPath(this.path),n.setCrossOrigin(this.crossOrigin),n.setWithCredentials(this.withCredentials),n.setRequestHeader(this.requestHeader),n.setResponseType("arraybuffer"),n.load(e,(e=>{this.parse(e,t,s)}),r,s)}parse(e,t,r){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(zs.has(e)){return zs.get(e).promise.then(t).catch(r)}this._createTexture(e).then((e=>t?t(e):null)).catch(r)}_createTextureFrom(e,t){const{type:r,error:s,data:{faces:n,width:a,height:o,format:l,type:c,dfdFlags:h}}=e;if("error"===r)return Promise.reject(s);let u;if(6===t.faceCount)u=new i.CompressedCubeTexture(n,l,c);else{const e=n[0].mipmaps;u=t.layerCount>1?new i.CompressedArrayTexture(e,a,o,t.layerCount,l,c):new i.CompressedTexture(e,a,o,l,c)}return u.minFilter=1===n[0].mipmaps.length?i.LinearFilter:i.LinearMipmapLinearFilter,u.magFilter=i.LinearFilter,u.generateMipmaps=!1,u.needsUpdate=!0,u.colorSpace=Ks(t),u.premultiplyAlpha=!!(1&h),u}async _createTexture(e,t={}){const r=function(e){const t=new Uint8Array(e.buffer,e.byteOffset,Us.length);if(t[0]!==Us[0]||t[1]!==Us[1]||t[2]!==Us[2]||t[3]!==Us[3]||t[4]!==Us[4]||t[5]!==Us[5]||t[6]!==Us[6]||t[7]!==Us[7]||t[8]!==Us[8]||t[9]!==Us[9]||t[10]!==Us[10]||t[11]!==Us[11])throw new Error("Missing KTX 2.0 identifier.");const r={vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null},i=17*Uint32Array.BYTES_PER_ELEMENT,s=new Ls(e,Us.length,i,!0);r.vkFormat=s._nextUint32(),r.typeSize=s._nextUint32(),r.pixelWidth=s._nextUint32(),r.pixelHeight=s._nextUint32(),r.pixelDepth=s._nextUint32(),r.layerCount=s._nextUint32(),r.faceCount=s._nextUint32(),r.levelCount=s._nextUint32(),r.supercompressionScheme=s._nextUint32();const n=s._nextUint32(),a=s._nextUint32(),o=s._nextUint32(),l=s._nextUint32(),c=s._nextUint64(),h=s._nextUint64(),u=3*Math.max(r.levelCount,1)*8,d=new Ls(e,Us.length+i,u,!0);for(let O=0,B=Math.max(r.levelCount,1);O<B;O++)r.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const p=new Ls(e,n,a,!0);p._skip(4);const m=p._nextUint16(),f=p._nextUint16(),g=p._nextUint16(),y=p._nextUint16(),v={vendorId:m,descriptorType:f,versionNumber:g,colorModel:p._nextUint8(),colorPrimaries:p._nextUint8(),transferFunction:p._nextUint8(),flags:p._nextUint8(),texelBlockDimension:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],bytesPlane:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],samples:[]},T=(y/4-6)/4;for(let O=0;O<T;O++){const e={bitOffset:p._nextUint16(),bitLength:p._nextUint8(),channelType:p._nextUint8(),samplePosition:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};64&e.channelType?(e.sampleLower=p._nextInt32(),e.sampleUpper=p._nextInt32()):(e.sampleLower=p._nextUint32(),e.sampleUpper=p._nextUint32()),v.samples[O]=e}r.dataFormatDescriptor.length=0,r.dataFormatDescriptor.push(v);const x=new Ls(e,o,l,!0);for(;x._offset<l;){const e=x._nextUint32(),t=x._scan(e),i=Is(t);if(r.keyValue[i]=x._nextUint8Array(e-t.byteLength-1),i.match(/^ktx/i)){const e=Is(r.keyValue[i]);r.keyValue[i]=e.substring(0,e.lastIndexOf("\0"))}x._skip(e%4?4-e%4:0)}if(h<=0)return r;const b=new Ls(e,c,h,!0),_=b._nextUint16(),w=b._nextUint16(),M=b._nextUint32(),S=b._nextUint32(),A=b._nextUint32(),C=b._nextUint32(),E=[];for(let O=0,B=Math.max(r.levelCount,1);O<B;O++)E.push({imageFlags:b._nextUint32(),rgbSliceByteOffset:b._nextUint32(),rgbSliceByteLength:b._nextUint32(),alphaSliceByteOffset:b._nextUint32(),alphaSliceByteLength:b._nextUint32()});const R=c+b._offset,P=R+M,L=P+S,U=L+A,I=new Uint8Array(e.buffer,e.byteOffset+R,M),F=new Uint8Array(e.buffer,e.byteOffset+P,S),k=new Uint8Array(e.buffer,e.byteOffset+L,A),D=new Uint8Array(e.buffer,e.byteOffset+U,C);return r.globalData={endpointCount:_,selectorCount:w,imageDescs:E,endpointsData:I,selectorsData:F,tablesData:k,extendedData:D},r}(new Uint8Array(e)),s=r.vkFormat===Rs&&167===r.dataFormatDescriptor[0].colorModel;if(!(0===r.vkFormat||s&&!this.workerConfig.astcHDRSupported))return async function(e){const{vkFormat:t}=e;if(void 0===qs[t])throw new Error("THREE.KTX2Loader: Unsupported vkFormat: "+t);Xs[t];let r;2===e.supercompressionScheme&&(Gs||(Gs=new Promise((async e=>{const t=new Bs;await t.init(),e(t)}))),r=await Gs);const s=[];for(let o=0;o<e.levels.length;o++){const n=Math.max(1,e.pixelWidth>>o),a=Math.max(1,e.pixelHeight>>o),l=e.pixelDepth?Math.max(1,e.pixelDepth>>o):0,c=e.levels[o];let h,u;if(0===e.supercompressionScheme)h=c.levelData;else{if(2!==e.supercompressionScheme)throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");h=r.decode(c.levelData,c.uncompressedByteLength)}u=Xs[t]===i.FloatType?new Float32Array(h.buffer,h.byteOffset,h.byteLength/Float32Array.BYTES_PER_ELEMENT):Xs[t]===i.HalfFloatType||Xs[t]===i.UnsignedShortType?new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT):Xs[t]===i.UnsignedInt5999Type||Xs[t]===i.UnsignedInt101111Type?new Uint32Array(h.buffer,h.byteOffset,h.byteLength/Uint32Array.BYTES_PER_ELEMENT):h,s.push({data:u,width:n,height:a,depth:l})}const n=0===e.levelCount||s.length>1;let a;if(js.has(qs[t]))a=0===e.pixelDepth?new i.DataTexture(s[0].data,e.pixelWidth,e.pixelHeight):new i.Data3DTexture(s[0].data,e.pixelWidth,e.pixelHeight,e.pixelDepth),a.minFilter=n?i.NearestMipmapNearestFilter:i.NearestFilter,a.magFilter=i.NearestFilter,a.generateMipmaps=0===e.levelCount,a.normalized=Ws.has(t);else{if(e.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");a=new i.CompressedTexture(s,e.pixelWidth,e.pixelHeight),a.minFilter=n?i.LinearMipmapLinearFilter:i.LinearFilter,a.magFilter=i.LinearFilter}return a.mipmaps=s,a.type=Xs[t],a.format=qs[t],a.colorSpace=Ks(e),a.needsUpdate=!0,Promise.resolve(a)}(r);const n=t,a=this.init().then((()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:n},[e]))).then((e=>this._createTextureFrom(e.data,r)));return zs.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL)}}Hs.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},Hs.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},Hs.EngineFormat={RGBAFormat:i.RGBAFormat,RGBA_ASTC_4x4_Format:i.RGBA_ASTC_4x4_Format,RGB_BPTC_UNSIGNED_Format:i.RGB_BPTC_UNSIGNED_Format,RGBA_BPTC_Format:i.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:i.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:i.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:i.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:i.RGB_ETC1_Format,RGB_ETC2_Format:i.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:i.RGB_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:i.RGBA_S3TC_DXT1_Format},Hs.EngineType={UnsignedByteType:i.UnsignedByteType,HalfFloatType:i.HalfFloatType,FloatType:i.FloatType},Hs.BasisWorker=function(){let e,t,r;const i=_EngineFormat,s=_EngineType,n=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(i){const n=i.data;switch(n.type){case"init":e=n.config,o=n.transcoderBinary,t=new Promise((e=>{r={wasmBinary:o,onRuntimeInitialized:e},BASIS(r)})).then((()=>{r.initializeBasis(),r.KTX2File}));break;case"transcode":t.then((()=>{try{const{faces:t,buffers:i,width:o,height:u,hasAlpha:d,format:p,type:m,dfdFlags:f}=function(t){const i=new r.KTX2File(new Uint8Array(t));function n(){i.close(),i.delete()}if(!i.isValid())throw n(),new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file");let o;if(i.isUASTC())o=a.UASTC;else if(i.isETC1S())o=a.ETC1S;else{if(!i.isHDR())throw new Error("THREE.KTX2Loader: Unknown Basis encoding");o=a.UASTC_HDR}const u=i.getWidth(),d=i.getHeight(),p=i.getLayers()||1,m=i.getLevels(),f=i.getFaces(),g=i.getHasAlpha(),y=i.getDFDFlags(),{transcoderFormat:v,engineFormat:T,engineType:x}=function(t,r,i,s){const n=l[t];for(let a=0;a<n.length;a++){const o=n[a];if(o.if&&!e[o.if])continue;if(!o.basisFormat.includes(t))continue;if(s&&o.transcoderFormat.length<2)continue;if(o.needsPowerOfTwo&&(!c(r)||!c(i)))continue;return{transcoderFormat:o.transcoderFormat[s?1:0],engineFormat:o.engineFormat[s?1:0],engineType:o.engineType[0]}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}(o,u,d,g);if(!u||!d||!m)throw n(),new Error("THREE.KTX2Loader:\tInvalid texture");if(!i.startTranscoding())throw n(),new Error("THREE.KTX2Loader: .startTranscoding failed");const b=[],_=[];for(let e=0;e<f;e++){const t=[];for(let r=0;r<m;r++){const a=[];let o,l;for(let t=0;t<p;t++){const c=i.getImageLevelInfo(r,t,e);0===e&&0===r&&0===t&&(c.origWidth%4!=0||c.origHeight),m>1?(o=c.origWidth,l=c.origHeight):(o=c.width,l=c.height);let h=new Uint8Array(i.getImageTranscodedSizeInBytes(r,t,0,v));const u=i.transcodeImage(h,r,t,e,v,0,-1,-1);if(x===s.HalfFloatType&&(h=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!u)throw n(),new Error("THREE.KTX2Loader: .transcodeImage failed.");a.push(h)}const c=h(a);t.push({data:c,width:o,height:l}),_.push(c.buffer)}b.push({mipmaps:t,width:u,height:d,format:T,type:x})}return n(),{faces:b,buffers:_,width:u,height:d,hasAlpha:g,dfdFlags:y,format:T,type:x}}(n.buffer);self.postMessage({type:"transcode",id:n.id,data:{faces:t,width:o,height:u,hasAlpha:d,format:p,type:m,dfdFlags:f}},i)}catch(t){self.postMessage({type:"error",id:n.id,error:t.message})}}))}var o}));const o=[{if:"astcSupported",basisFormat:[a.UASTC],transcoderFormat:[n.ASTC_4x4,n.ASTC_4x4],engineFormat:[i.RGBA_ASTC_4x4_Format,i.RGBA_ASTC_4x4_Format],engineType:[s.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.BC7_M5,n.BC7_M5],engineFormat:[i.RGBA_BPTC_Format,i.RGBA_BPTC_Format],engineType:[s.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.BC1,n.BC3],engineFormat:[i.RGBA_S3TC_DXT1_Format,i.RGBA_S3TC_DXT5_Format],engineType:[s.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.ETC1,n.ETC2],engineFormat:[i.RGB_ETC2_Format,i.RGBA_ETC2_EAC_Format],engineType:[s.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.ETC1],engineFormat:[i.RGB_ETC1_Format],engineType:[s.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.PVRTC1_4_RGB,n.PVRTC1_4_RGBA],engineFormat:[i.RGB_PVRTC_4BPPV1_Format,i.RGBA_PVRTC_4BPPV1_Format],engineType:[s.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[a.UASTC_HDR],transcoderFormat:[n.BC6H],engineFormat:[i.RGB_BPTC_UNSIGNED_Format],engineType:[s.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.RGBA32,n.RGBA32],engineFormat:[i.RGBAFormat,i.RGBAFormat],engineType:[s.UnsignedByteType,s.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[a.UASTC_HDR],transcoderFormat:[n.RGBA_HALF],engineFormat:[i.RGBAFormat],engineType:[s.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],l={[a.ETC1S]:o.filter((e=>e.basisFormat.includes(a.ETC1S))).sort(((e,t)=>e.priorityETC1S-t.priorityETC1S)),[a.UASTC]:o.filter((e=>e.basisFormat.includes(a.UASTC))).sort(((e,t)=>e.priorityUASTC-t.priorityUASTC)),[a.UASTC_HDR]:o.filter((e=>e.basisFormat.includes(a.UASTC_HDR))).sort(((e,t)=>e.priorityHDR-t.priorityHDR))};function c(e){return e<=2||!(e&e-1)&&0!==e}function h(e){if(1===e.length)return e[0];let t=0;for(let s=0;s<e.length;s++){t+=e[s].byteLength}const r=new Uint8Array(t);let i=0;for(let s=0;s<e.length;s++){const t=e[s];r.set(t,i),i+=t.byteLength}return r}};const js=new Set([i.RGBAFormat,i.RGBFormat,i.RGFormat,i.RedFormat]),Ws=new Set([91]),qs={[es]:i.RGBAFormat,[Ji]:i.RGFormat,[Zi]:i.RedFormat,[$i]:i.RGBAFormat,[Yi]:i.RGFormat,[Ki]:i.RedFormat,[Qi]:i.RGBAFormat,[Xi]:i.RGBAFormat,[qi]:i.RGBAFormat,[Wi]:i.RGFormat,[ji]:i.RGFormat,[Hi]:i.RedFormat,[Gi]:i.RedFormat,[rs]:i.RGBFormat,[ts]:i.RGBFormat,[gs]:i.RGBA_ETC2_EAC_Format,[fs]:i.RGB_ETC2_Format,[ys]:i.R11_EAC_Format,[vs]:i.SIGNED_R11_EAC_Format,[Ts]:i.RG11_EAC_Format,[xs]:i.SIGNED_RG11_EAC_Format,[Rs]:i.RGBA_ASTC_4x4_Format,[_s]:i.RGBA_ASTC_4x4_Format,[bs]:i.RGBA_ASTC_4x4_Format,[Ps]:i.RGBA_ASTC_6x6_Format,[Ms]:i.RGBA_ASTC_6x6_Format,[ws]:i.RGBA_ASTC_6x6_Format,[as]:i.RGBA_S3TC_DXT1_Format,[ns]:i.RGBA_S3TC_DXT1_Format,[ss]:i.RGB_S3TC_DXT1_Format,[is]:i.RGB_S3TC_DXT1_Format,[ls]:i.RGBA_S3TC_DXT5_Format,[os]:i.RGBA_S3TC_DXT5_Format,[hs]:i.SIGNED_RED_RGTC1_Format,[cs]:i.RED_RGTC1_Format,[ds]:i.SIGNED_RED_GREEN_RGTC2_Format,[us]:i.RED_GREEN_RGTC2_Format,[ms]:i.RGBA_BPTC_Format,[ps]:i.RGBA_BPTC_Format,[Es]:i.RGBA_PVRTC_4BPPV1_Format,[As]:i.RGBA_PVRTC_4BPPV1_Format,[Cs]:i.RGBA_PVRTC_2BPPV1_Format,[Ss]:i.RGBA_PVRTC_2BPPV1_Format},Xs={[es]:i.FloatType,[Ji]:i.FloatType,[Zi]:i.FloatType,[$i]:i.HalfFloatType,[Yi]:i.HalfFloatType,[Ki]:i.HalfFloatType,[Qi]:i.UnsignedShortType,[Xi]:i.UnsignedByteType,[qi]:i.UnsignedByteType,[Wi]:i.UnsignedByteType,[ji]:i.UnsignedByteType,[Hi]:i.UnsignedByteType,[Gi]:i.UnsignedByteType,[rs]:i.UnsignedInt5999Type,[ts]:i.UnsignedInt101111Type,[gs]:i.UnsignedByteType,[fs]:i.UnsignedByteType,[ys]:i.UnsignedByteType,[vs]:i.UnsignedByteType,[Ts]:i.UnsignedByteType,[xs]:i.UnsignedByteType,[Rs]:i.HalfFloatType,[_s]:i.UnsignedByteType,[bs]:i.UnsignedByteType,[Ps]:i.HalfFloatType,[Ms]:i.UnsignedByteType,[ws]:i.UnsignedByteType,[as]:i.UnsignedByteType,[ns]:i.UnsignedByteType,[ss]:i.UnsignedByteType,[is]:i.UnsignedByteType,[ls]:i.UnsignedByteType,[os]:i.UnsignedByteType,[hs]:i.UnsignedByteType,[cs]:i.UnsignedByteType,[ds]:i.UnsignedByteType,[us]:i.UnsignedByteType,[ms]:i.UnsignedByteType,[ps]:i.UnsignedByteType,[Es]:i.UnsignedByteType,[As]:i.UnsignedByteType,[Cs]:i.UnsignedByteType,[Ss]:i.UnsignedByteType};function Ks(e){const t=e.dataFormatDescriptor[0];return 1===t.colorPrimaries?2===t.transferFunction?i.SRGBColorSpace:i.LinearSRGBColorSpace:10===t.colorPrimaries?2===t.transferFunction?"display-p3":"display-p3-linear":(t.colorPrimaries,i.NoColorSpace)}function Ys(e,t,r,i){let s=!1,n=!1;const a=new Set,o=e.dispose.bind(e),l=t=>{a.delete(t),s&&!n&&0===a.size&&(n=!0,("transcoderPending"!==i||e[i])&&o())};for(const c of[t,r]){const t=e[c].bind(e);e[c]=(...e)=>{if(s)return Promise.reject(new DOMException("Tile decoders disposed","AbortError"));const r=Promise.resolve(t(...e));return a.add(r),r.then((()=>l(r)),(()=>l(r))),r}}return e.preload&&(e.preload=()=>(s||e[t]().catch((()=>{})),e)),e.dispose=()=>(s=!0,l(null),e),e}class Qs{constructor(e){this.renderer=e,this.draco=null,this.ktx2=null,this.disposed=!1}getDraco(){if(this.disposed)throw new Error("Tile decoders disposed");return this.draco??(this.draco=Ys(new Ni,"_initDecoder","decodeGeometry","decoderPending"))}getKTX2(){if(this.disposed)throw new Error("Tile decoders disposed");return this.ktx2||(this.ktx2=Ys(new Hs,"init","_createTexture","transcoderPending"),this.ktx2.detectSupport(this.renderer)),this.ktx2}dispose(){var e,t;this.disposed||(this.disposed=!0,null==(e=this.draco)||e.dispose(),null==(t=this.ktx2)||t.dispose())}}var $s=class{constructor(e={}){let{apiToken:t,autoRefreshToken:r=!1}=e;this.apiToken=t,this.autoRefreshToken=r,this.authURL=null,this._tokenRefreshPromise=null,this._bearerToken=null,this._bearerHostname=null}async fetch(e,t){await this._tokenRefreshPromise;let r={...t},i=null!==this._bearerHostname&&new URL(e).host===this._bearerHostname;i&&(r.headers={...r.headers,Authorization:this._bearerToken});let s=await fetch(e,r);return i&&s.status>=400&&s.status<=499&&this.autoRefreshToken?(await this.refreshToken(t),r.headers.Authorization=this._bearerToken,fetch(e,r)):s}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("access_token",this.apiToken),this._tokenRefreshPromise=fetch(t,e).then((e=>{if(!e.ok)throw Error(`CesiumIonAuthPlugin: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(e.accessToken&&e.url&&(this._bearerToken=`Bearer ${e.accessToken}`,this._bearerHostname=new URL(e.url).host),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}},Zs="https://tile.googleapis.com/v1/createSession",Js=class{get isMapTilesSession(){return this.authURL===Zs}constructor(e={}){let{apiToken:t,sessionOptions:r=null,autoRefreshToken:i=!1}=e;this.apiToken=t,this.autoRefreshToken=i,this.authURL=Zs,this.sessionToken=null,this.sessionOptions=r,this._tokenRefreshPromise=null,this._authHostname=null}async fetch(e,t){null===this.sessionToken&&this.isMapTilesSession&&this.refreshToken(t),await this._tokenRefreshPromise,null===this._authHostname&&(this._authHostname=new URL(this.authURL).host);let r=new URL(e),i=r.host===this._authHostname;i&&(r.searchParams.set("key",this.apiToken),this.sessionToken&&r.searchParams.set("session",this.sessionToken));let s=await fetch(r,t);return i&&s.status>=400&&s.status<=499&&this.autoRefreshToken&&(await this.refreshToken(t),this.sessionToken&&r.searchParams.set("session",this.sessionToken),s=await fetch(r,t)),null!==this.sessionToken||this.isMapTilesSession?s:s.json().then((e=>(this.sessionToken=en(e),e)))}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("key",this.apiToken);let r={...e};this.isMapTilesSession&&(r.method="POST",r.body=JSON.stringify(this.sessionOptions),r.headers=r.headers||{},r.headers={...r.headers,"Content-Type":"application/json"}),this._tokenRefreshPromise=fetch(t,r).then((e=>{if(!e.ok)throw Error(`GoogleCloudAuth: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(this.sessionToken=en(e),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}};function en(e){if("session"in e)return e.session;{let t=null;return Ee(e.root,(e=>{if(e.content&&e.content.uri){let[,r]=e.content.uri.split("?");return t=new URLSearchParams(r).get("session"),!0}return!1})),t}}var tn=class{constructor(){this.creditsCount={}}_adjustAttributions(e,t){let r=this.creditsCount,i=e.split(/;/g);for(let s=0,n=i.length;s<n;s++){let e=i[s];e in r||(r[e]=0),r[e]+=t?1:-1,r[e]<=0&&delete r[e]}}addAttributions(e){this._adjustAttributions(e,!0)}removeAttributions(e){this._adjustAttributions(e,!1)}toString(){return Object.entries(this.creditsCount).sort(((e,t)=>{let r=e[1];return t[1]-r})).map((e=>e[0])).join("; ")}},rn=class{constructor({apiToken:e,sessionOptions:t=null,autoRefreshToken:r=!1,logoUrl:i=null,useRecommendedSettings:s=!0}){this.name="GOOGLE_CLOUD_AUTH_PLUGIN",this.apiToken=e,this.useRecommendedSettings=s,this.logoUrl=i,this.auth=new Js({apiToken:e,autoRefreshToken:r,sessionOptions:t}),this.tiles=null,this._visibilityChangeCallback=null,this._attributionsManager=new tn,this._logoAttribution={value:"",type:"image",collapsible:!1},this._attribution={value:"",type:"string",collapsible:!0}}init(e){let{useRecommendedSettings:t,auth:r}=this;e.resetFailedTiles(),e.rootURL??(e.rootURL="https://tile.googleapis.com/v1/3dtiles/root.json"),r.sessionOptions||(r.authURL=e.rootURL),t&&!r.isMapTilesSession&&(e.errorTarget=20),this.tiles=e,this._visibilityChangeCallback=({tile:e,visible:t})=>{var r,i;let s=(null==(i=null==(r=e.engineData.metadata)?void 0:r.asset)?void 0:i.copyright)||"";t?this._attributionsManager.addAttributions(s):this._attributionsManager.removeAttributions(s)},e.addEventListener("tile-visibility-change",this._visibilityChangeCallback)}getAttributions(e){this.tiles.visibleTiles.size>0&&(this.logoUrl&&(this._logoAttribution.value=this.logoUrl,e.push(this._logoAttribution)),this._attribution.value=this._attributionsManager.toString(),e.push(this._attribution))}dispose(){this.tiles.removeEventListener("tile-visibility-change",this._visibilityChangeCallback)}async fetchData(e,t){return this.auth.fetch(e,t)}},sn=class{get apiToken(){return this.auth.apiToken}set apiToken(e){this.auth.apiToken=e}get autoRefreshToken(){return this.auth.autoRefreshToken}set autoRefreshToken(e){this.auth.autoRefreshToken=e}constructor(e={}){let{apiToken:t,assetId:r=null,autoRefreshToken:i=!1,useRecommendedSettings:s=!0,assetTypeHandler:n=(e,t,r)=>{}}=e;this.name="CESIUM_ION_AUTH_PLUGIN",this.auth=new $s({apiToken:t,autoRefreshToken:i}),this.assetId=r,this.autoRefreshToken=i,this.useRecommendedSettings=s,this.assetTypeHandler=n,this.tiles=null,this._tileSetVersion=-1,this._attributions=[]}init(e){null!==this.assetId&&(e.rootURL=`https://api.cesium.com/v1/assets/${this.assetId}/endpoint`),this.tiles=e,this.auth.authURL=e.rootURL,e.resetFailedTiles()}loadRootTileset(){return this.auth.refreshToken().then((e=>(this._initializeFromAsset(e),this.tiles.invokeOnePlugin((e=>e!==this&&e.loadRootTileset&&e.loadRootTileset()))))).catch((e=>{this.tiles.dispatchEvent({type:"load-error",tile:null,error:e,url:this.auth.authURL})}))}preprocessURL(e){return e=new URL(e),/^http/.test(e.protocol)&&-1!=this._tileSetVersion&&e.searchParams.set("v",this._tileSetVersion),e.toString()}fetchData(e,t){return null===this.tiles.getPluginByName("GOOGLE_CLOUD_AUTH_PLUGIN")?this.auth.fetch(e,t):null}getAttributions(e){this.tiles.visibleTiles.size>0&&e.push(...this._attributions)}_initializeFromAsset(e){let t=this.tiles;if("externalType"in e){let r=new URL(e.options.url);t.rootURL=e.options.url,t.registerPlugin(new rn({apiToken:r.searchParams.get("key"),autoRefreshToken:this.autoRefreshToken,useRecommendedSettings:this.useRecommendedSettings}))}else{"3DTILES"!==e.type&&this.assetTypeHandler(e.type,t,e),t.rootURL=e.url;let r=new URL(e.url);r.searchParams.has("v")&&-1===this._tileSetVersion&&(this._tileSetVersion=r.searchParams.get("v")),e.attributions&&(this._attributions=e.attributions.map((e=>({value:e.html,type:"html",collapsible:e.collapsible}))))}}};function nn(e){return"OCTREE"===e.implicitTilingData.root.implicitTiling.subdivisionScheme}function an(e){return nn(e)?8:4}var on=class{constructor(e,t){this.parent=e,this.children=[],this.geometricError=0,this.boundingVolume=null;let[r,i,s]=function(e,t){if(!e)return[0,0,0];let r=e.implicitTilingData.x,i=e.implicitTilingData.y,s=e.implicitTilingData.z;return[2*r+t%2,2*i+Math.floor(t/2)%2,nn(e)?2*s+Math.floor(t/4)%2:0]}(e,t);this.implicitTilingData={level:e.implicitTilingData.level+1,root:e.implicitTilingData.root,subtreeIdx:t,x:r,y:i,z:s}}static clone(e){return{parent:e.parent,children:[],geometricError:e.geometricError,boundingVolume:e.boundingVolume,implicitTilingData:{...e.implicitTilingData}}}},ln=class extends ze{constructor(e){super(),this.tile=e,this.rootTile=e.implicitTilingData.root,this.workingPath=null}parseBuffer(e){let t=new DataView(e),r=0;Oe(t);r+=4;let i=t.getUint32(r,!0);r+=4;let s=t.getUint32(r,!0);r+=8;let n=t.getUint32(r,!0);r+=8;let a=JSON.parse(Ne(new Uint8Array(e,r,s)));return r+=s,{version:i,subtreeJson:a,subtreeByte:e.slice(r,r+n)}}async parse(e){let t=this.parseBuffer(e),r=t.subtreeJson;r.contentAvailabilityHeaders=[].concat(r.contentAvailability);let i=this.preprocessBuffers(r.buffers),s=this.preprocessBufferViews(r.bufferViews,i);this.markActiveBufferViews(r,s);let n=await this.requestActiveBuffers(i,t.subtreeByte),a=this.parseActiveBufferViews(s,n);this.parseAvailability(t,r,a),this.expandSubtree(this.tile,t)}markActiveBufferViews(e,t){let r,i=e.tileAvailability;isNaN(i.bitstream)?isNaN(i.bufferView)||(r=t[i.bufferView]):r=t[i.bitstream],r&&(r.isActive=!0,r.bufferHeader.isActive=!0);let s=e.contentAvailabilityHeaders;for(let a=0;a<s.length;a++)r=void 0,isNaN(s[a].bitstream)?isNaN(s[a].bufferView)||(r=t[s[a].bufferView]):r=t[s[a].bitstream],r&&(r.isActive=!0,r.bufferHeader.isActive=!0);r=void 0;let n=e.childSubtreeAvailability;isNaN(n.bitstream)?isNaN(n.bufferView)||(r=t[n.bufferView]):r=t[n.bitstream],r&&(r.isActive=!0,r.bufferHeader.isActive=!0)}async requestActiveBuffers(e,t){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i.isActive)if(i.isExternal){let e=this.parseImplicitURIBuffer(this.tile,this.rootTile.implicitTiling.subtrees.uri,i.uri),t=fetch(e,this.fetchOptions).then((e=>{if(!e.ok)throw Error(`SUBTREELoader: Failed to load external buffer from ${i.uri} with error code ${e.status}.`);return e.arrayBuffer()})).then((e=>new Uint8Array(e)));r.push(t)}else r.push(Promise.resolve(new Uint8Array(t)));else r.push(Promise.resolve())}let i=await Promise.all(r),s={};for(let n=0;n<i.length;n++){let e=i[n];e&&(s[n]=e)}return s}parseActiveBufferViews(e,t){let r={};for(let i=0;i<e.length;i++){let s=e[i];if(!s.isActive)continue;let n=s.byteOffset,a=n+s.byteLength;r[i]=t[s.buffer].slice(n,a)}return r}preprocessBuffers(e=[]){for(let t=0;t<e.length;t++){let r=e[t];r.isActive=!1,r.isExternal=!!r.uri}return e}preprocessBufferViews(e=[],t){for(let r=0;r<e.length;r++){let i=e[r];i.bufferHeader=t[i.buffer],i.isActive=!1,i.isExternal=i.bufferHeader.isExternal}return e}parseAvailability(e,t,r){let i=an(this.rootTile),s=this.rootTile.implicitTiling.subtreeLevels,n=(i**+s-1)/(i-1),a=i**+s;e._tileAvailability=this.parseAvailabilityBitstream(t.tileAvailability,r,n),e._contentAvailabilityBitstreams=[];for(let o=0;o<t.contentAvailabilityHeaders.length;o++){let i=this.parseAvailabilityBitstream(t.contentAvailabilityHeaders[o],r,n);e._contentAvailabilityBitstreams.push(i)}e._childSubtreeAvailability=this.parseAvailabilityBitstream(t.childSubtreeAvailability,r,a)}parseAvailabilityBitstream(e,t,r){if(!isNaN(e.constant))return{constant:!!e.constant,lengthBits:r};let i;return isNaN(e.bitstream)?isNaN(e.bufferView)||(i=t[e.bufferView]):i=t[e.bitstream],{bitstream:i,lengthBits:r}}expandSubtree(e,t){let r=on.clone(e);for(let n=0;t&&n<t._contentAvailabilityBitstreams.length;n++)if(t&&this.getBit(t._contentAvailabilityBitstreams[n],0)){r.content={uri:this.parseImplicitURI(e,this.rootTile.content.uri)};break}e.children.push(r);let i=this.transcodeSubtreeTiles(r,t),s=this.listChildSubtrees(t,i);for(let n=0;n<s.length;n++){let e=s[n],t=e.tile,r=this.deriveChildTile(null,t,null,e.childMortonIndex);r.content={uri:this.parseImplicitURI(r,this.rootTile.implicitTiling.subtrees.uri)},t.children.push(r)}}transcodeSubtreeTiles(e,t){let r=[e],i=[];for(let s=1;s<this.rootTile.implicitTiling.subtreeLevels;s++){let e=an(this.rootTile),n=(e**+s-1)/(e-1),a=e*r.length;for(let s=0;s<a;s++){let a=n+s,o=r[s>>Math.log2(e)];if(!this.getBit(t._tileAvailability,a)){i.push(void 0);continue}let l=this.deriveChildTile(t,o,a,s);o.children.push(l),i.push(l)}r=i,i=[]}return r}deriveChildTile(e,t,r,i){let s=new on(t,i);s.boundingVolume=this.getTileBoundingVolume(s),s.geometricError=this.getGeometricError(s);for(let n=0;e&&n<e._contentAvailabilityBitstreams.length;n++)if(e&&this.getBit(e._contentAvailabilityBitstreams[n],r)){s.content={uri:this.parseImplicitURI(s,this.rootTile.content.uri)};break}return s}getBit(e,t){if(t<0||t>=e.lengthBits)throw Error("Bit index out of bounds.");if(void 0!==e.constant)return e.constant;let r=t>>3,i=t%8;return 1==(new Uint8Array(e.bitstream)[r]>>i&1)}getTileBoundingVolume(e){let t={};if(this.rootTile.boundingVolume.region){let r=[...this.rootTile.boundingVolume.region],i=r[0],s=r[2],n=r[1],a=r[3],o=(s-i)/2**e.implicitTilingData.level,l=(a-n)/2**e.implicitTilingData.level;r[0]=i+o*e.implicitTilingData.x,r[2]=i+o*(e.implicitTilingData.x+1),r[1]=n+l*e.implicitTilingData.y,r[3]=n+l*(e.implicitTilingData.y+1);for(let e=0;e<4;e++){let t=r[e];t<-Math.PI?r[e]+=2*Math.PI:t>Math.PI&&(r[e]-=2*Math.PI)}if(nn(e)){let t=r[4],i=(r[5]-t)/2**e.implicitTilingData.level;r[4]=t+i*e.implicitTilingData.z,r[5]=t+i*(e.implicitTilingData.z+1)}t.region=r}if(this.rootTile.boundingVolume.box){let r=[...this.rootTile.boundingVolume.box],i=2**e.implicitTilingData.level-1,s=2**-e.implicitTilingData.level,n=nn(e)?3:2;for(let t=0;t<n;t++){r[3+3*t+0]*=s,r[3+3*t+1]*=s,r[3+3*t+2]*=s;let n=r[3+3*t+0],a=r[3+3*t+1],o=r[3+3*t+2],l=0===t?e.implicitTilingData.x:1===t?e.implicitTilingData.y:e.implicitTilingData.z;r[0]+=2*n*(-.5*i+l),r[1]+=2*a*(-.5*i+l),r[2]+=2*o*(-.5*i+l)}t.box=r}return t}getGeometricError(e){return this.rootTile.geometricError/2**e.implicitTilingData.level}listChildSubtrees(e,t){let r=[],i=an(this.rootTile);for(let s=0;s<t.length;s++){let n=t[s];if(void 0!==n)for(let t=0;t<i;t++){let a=s*i+t;this.getBit(e._childSubtreeAvailability,a)&&r.push({tile:n,childMortonIndex:a})}}return r}parseImplicitURI(e,t){return t=(t=(t=(t=t.replace("{level}",e.implicitTilingData.level)).replace("{x}",e.implicitTilingData.x)).replace("{y}",e.implicitTilingData.y)).replace("{z}",e.implicitTilingData.z)}parseImplicitURIBuffer(e,t,r){let i=this.parseImplicitURI(e,t),s=new URL(i,this.workingPath+"/");return s.pathname=s.pathname.substring(0,s.pathname.lastIndexOf("/")),new URL(s.pathname+"/"+r,this.workingPath+"/").toString()}},cn=class{constructor(){this.name="IMPLICIT_TILING_PLUGIN"}init(e){this.tiles=e}preprocessNode(e,t,r){var i;e.implicitTiling?(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1,e.implicitTilingData={root:e,subtreeIdx:0,x:0,y:0,z:0,level:0}):/.subtree$/i.test(null==(i=e.content)?void 0:i.uri)&&(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1)}parseTile(e,t,r){if(/^subtree$/i.test(r)){let r=new ln(t);return r.workingPath=t.internal.basePath,r.fetchOptions=this.tiles.fetchOptions,r.parse(e)}}preprocessURL(e,t){if(t&&t.implicitTiling){let e=t.implicitTiling.subtrees.uri.replace("{level}",t.implicitTilingData.level).replace("{x}",t.implicitTilingData.x).replace("{y}",t.implicitTilingData.y).replace("{z}",t.implicitTilingData.z);return new URL(e,t.internal.basePath+"/").toString()}return e}disposeTile(e){var t;/.subtree$/i.test(null==(t=e.content)?void 0:t.uri)&&(e.children.forEach((e=>{this.tiles.processNodeQueue.remove(e)})),e.children.length=0)}};function hn(e){return e>>1^-(1&e)}var un=class extends ze{constructor(...e){super(...e),this.fetchOptions.header={Accept:"application/vnd.quantized-mesh,application/octet-stream;q=0.9"}}loadAsync(...e){let{fetchOptions:t}=this;return t.header=t.header||{},t.header.Accept="application/vnd.quantized-mesh,application/octet-stream;q=0.9",t.header.Accept+=";extensions=octvertexnormals-watermask-metadata",super.loadAsync(...e)}parse(e){let t=0,r=new DataView(e),i=()=>{let e=r.getFloat64(t,!0);return t+=8,e},s=()=>{let e=r.getFloat32(t,!0);return t+=4,e},n=()=>{let e=r.getUint32(t,!0);return t+=4,e},a=()=>{let e=r.getUint8(t);return t+=1,e},o=(r,i)=>{let s=new i(e,t,r);return t+=r*i.BYTES_PER_ELEMENT,s},l={center:[i(),i(),i()],minHeight:s(),maxHeight:s(),sphereCenter:[i(),i(),i()],sphereRadius:i(),horizonOcclusionPoint:[i(),i(),i()]},c=n(),h=o(c,Uint16Array),u=o(c,Uint16Array),d=o(c,Uint16Array),p=new Float32Array(c),m=new Float32Array(c),f=new Float32Array(c),g=0,y=0,v=0,T=32767;for(let I=0;I<c;++I)g+=hn(h[I]),y+=hn(u[I]),v+=hn(d[I]),p[I]=g/T,m[I]=y/T,f[I]=v/T;let x=c>65536,b=x?Uint32Array:Uint16Array;t=x?4*Math.ceil(t/4):2*Math.ceil(t/2);let _=o(3*n(),b),w=0;for(var M=0;M<_.length;++M){let e=_[M];_[M]=w-e,0===e&&++w}let S=(e,t)=>m[t]-m[e],A=(e,t)=>p[e]-p[t],C=o(n(),b);C.sort(S);let E=o(n(),b);E.sort(A);let R=o(n(),b);R.sort(((e,t)=>-S(e,t)));let P=o(n(),b);P.sort(((e,t)=>-A(e,t)));let L={westIndices:C,southIndices:E,eastIndices:R,northIndices:P},U={};for(;t<r.byteLength;){let e=a(),t=n();if(1===e){let t=o(2*c,Uint8Array),r=new Float32Array(3*c);for(let e=0;e<c;e++){let i=t[2*e+0]/255*2-1,s=t[2*e+1]/255*2-1,n=1-(Math.abs(i)+Math.abs(s));if(n<0){let e=i;i=(1-Math.abs(s))*dn(e),s=(1-Math.abs(e))*dn(s)}let a=Math.sqrt(i*i+s*s+n*n);r[3*e+0]=i/a,r[3*e+1]=s/a,r[3*e+2]=n/a}U.octvertexnormals={extensionId:e,normals:r}}else if(2===e){let r=1===t?1:256;U.watermask={extensionId:e,mask:o(r*r,Uint8Array),size:r}}else if(4===e){let t=o(n(),Uint8Array),r=(new TextDecoder).decode(t);U.metadata={extensionId:e,json:JSON.parse(r)}}}return{header:l,indices:_,vertexData:{u:p,v:m,height:f},edgeIndices:L,extensions:U}}};function dn(e){return e<0?-1:1}const pn=new i.OrthographicCamera(-1,1,1,-1,0,1);class mn extends i.BufferGeometry{constructor(){super(),this.setAttribute("position",new i.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new i.Float32BufferAttribute([0,2,0,0,2,0],2))}}const fn=new mn;class gn{constructor(e){this._mesh=new i.Mesh(fn,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,pn)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}var yn=new i.Vector3,vn=new i.Vector3;var Tn=class{get isMercator(){return"EPSG:3857"===this.scheme}get isCartographic(){return"none"!==this.scheme}constructor(e="EPSG:4326"){this.scheme=e,this.tileCountX=1,this.tileCountY=1,this.setScheme(e)}setScheme(e){switch(this.scheme=e,e){case"CRS:84":case"EPSG:4326":this.tileCountX=2,this.tileCountY=1;break;case"EPSG:3857":case"none":this.tileCountX=1,this.tileCountY=1;break;default:throw Error(`ProjectionScheme: Unknown projection scheme "${e}"`)}}convertNormalizedToLatitude(e){if("none"===this.scheme)return e;if(this.isMercator){let t=i.MathUtils.mapLinear(e,0,1,-1,1);return 2*Math.atan(Math.exp(t*Math.PI))-Math.PI/2}return i.MathUtils.mapLinear(e,0,1,-Math.PI/2,Math.PI/2)}convertNormalizedToLongitude(e){return"none"===this.scheme?e:i.MathUtils.mapLinear(e,0,1,-Math.PI,Math.PI)}convertLatitudeToNormalized(e){return"none"===this.scheme?e:this.isMercator?.5+1*Math.log(Math.tan(Math.PI/4+e/2))/(2*Math.PI):i.MathUtils.mapLinear(e,-Math.PI/2,Math.PI/2,0,1)}convertLongitudeToNormalized(e){return"none"===this.scheme?e:(e+Math.PI)/(2*Math.PI)}getLongitudeDerivativeAtNormalized(e){return"none"===this.scheme?1:2*Math.PI}getLatitudeDerivativeAtNormalized(e){if("none"===this.scheme)return 1;{let t=1e-5,r=e-t;return r<0&&(r=e+t),this.isMercator?Math.abs(this.convertNormalizedToLatitude(e)-this.convertNormalizedToLatitude(r))/t:Math.PI}}getBounds(){return"none"===this.scheme?[0,0,1,1]:[this.convertNormalizedToLongitude(0),this.convertNormalizedToLatitude(0),this.convertNormalizedToLongitude(1),this.convertNormalizedToLatitude(1)]}toNormalizedPoint(e,t){let r=[e,t];return r[0]=this.convertLongitudeToNormalized(r[0]),r[1]=this.convertLatitudeToNormalized(r[1]),r}toNormalizedRange(e){return[...this.toNormalizedPoint(e[0],e[1]),...this.toNormalizedPoint(e[2],e[3])]}toCartographicPoint(e,t){let r=[e,t];return r[0]=this.convertNormalizedToLongitude(r[0]),r[1]=this.convertNormalizedToLatitude(r[1]),r}toCartographicRange(e){return[...this.toCartographicPoint(e[0],e[1]),...this.toCartographicPoint(e[2],e[3])]}clampToBounds(e,t=!1){let r,s=[...e];r=t?[0,0,1,1]:this.getBounds();let[n,a,o,l]=r;return s[0]=i.MathUtils.clamp(s[0],n,o),s[2]=i.MathUtils.clamp(s[2],n,o),s[1]=i.MathUtils.clamp(s[1],a,l),s[3]=i.MathUtils.clamp(s[3],a,l),s}};function xn(e,t){let[r,i,s,n]=e,[a,o,l,c]=t;return!(r>=l||s<=a||i>=c||n<=o)}var bn=class{get levelCount(){return this._levels.length}get maxLevel(){return this.levelCount-1}get minLevel(){let e=this._levels;for(let t=0;t<e.length;t++)if(null!==e[t])return t;return-1}get contentBounds(){return this._contentBounds??this.projection.getBounds()}get aspectRatio(){let{pixelWidth:e,pixelHeight:t}=this.getLevel(this.maxLevel);return e/t}constructor(){this.flipY=!1,this.pixelOverlap=0,this._contentBounds=null,this.projection=new Tn("none"),this._levels=[]}setLevel(e,t={}){let r=this._levels;for(;r.length<e;)r.push(null);let{tileSplitX:i=2,tileSplitY:s=2}=t,{tilePixelWidth:n=256,tilePixelHeight:a=256,tileCountX:o=i**e,tileCountY:l=s**e,tileBounds:c=null}=t,{pixelWidth:h=n*o,pixelHeight:u=a*l}=t;r[e]={tilePixelWidth:n,tilePixelHeight:a,pixelWidth:h,pixelHeight:u,tileCountX:o,tileCountY:l,tileSplitX:i,tileSplitY:s,tileBounds:c}}generateLevels(e,t,r,i={}){let{minLevel:s=0,tilePixelWidth:n=256,tilePixelHeight:a=256}=i,o=e-1,{pixelWidth:l=n*t*2**o,pixelHeight:c=a*r*2**o}=i;for(let h=s;h<e;h++){let t=e-h-1,r=Math.ceil(l*2**-t),i=Math.ceil(c*2**-t),s=Math.ceil(r/n),o=Math.ceil(i/a);this.setLevel(h,{tilePixelWidth:n,tilePixelHeight:a,pixelWidth:r,pixelHeight:i,tileCountX:s,tileCountY:o})}}getLevel(e){return this._levels[e]}setContentBounds(e,t,r,i){this._contentBounds=[e,t,r,i]}setProjection(e){this.projection=e}getTileAtPoint(e,t,r,s=!1){let{flipY:n}=this,{tileCountY:a,tileBounds:o,pixelHeight:l,pixelWidth:c,tilePixelHeight:h,tilePixelWidth:u}=this.getLevel(r),d=u/c,p=h/l;if(s||([e,t]=this.toNormalizedPoint(e,t)),o){let r=this.toNormalizedRange(o);e=i.MathUtils.mapLinear(e,r[0],r[2],0,1),t=i.MathUtils.mapLinear(t,r[1],r[3],0,1)}let m=Math.floor(e/d),f=Math.floor(t/p);return n&&(f=a-1-f),[m,f]}getTilesInRange(e,t,r,s,n,a=!1){let o=[e,t,r,s],l=this.getContentBounds(a),c=this.getLevel(n).tileBounds;if(!xn(o,l)||c&&(a&&(c=this.toNormalizedRange(c)),!xn(o,l)))return[0,0,-1,-1];let[h,u,d,p]=this.clampToContentBounds(o,a),m=this.getTileAtPoint(h,u,n,a),f=this.getTileAtPoint(d,p,n,a);this.flipY&&([m[1],f[1]]=[f[1],m[1]]);let{tileCountX:g,tileCountY:y}=this.getLevel(n),[v,T]=m,[x,b]=f;return x<0||b<0||v>=g||T>=y?[0,0,-1,-1]:[i.MathUtils.clamp(v,0,g-1),i.MathUtils.clamp(T,0,y-1),i.MathUtils.clamp(x,0,g-1),i.MathUtils.clamp(b,0,y-1)]}getTileExists(e,t,r){let[i,s,n,a]=this.contentBounds,[o,l,c,h]=this.getTileBounds(e,t,r);return!(o>=c||l>=h)&&o<=n&&l<=a&&c>=i&&h>=s}getContentBounds(e=!1){let{projection:t}=this,r=[...this.contentBounds];return e&&(r[0]=t.convertLongitudeToNormalized(r[0]),r[1]=t.convertLatitudeToNormalized(r[1]),r[2]=t.convertLongitudeToNormalized(r[2]),r[3]=t.convertLatitudeToNormalized(r[3])),r}getTileContentUVBounds(e,t,r){let[s,n,a,o]=this.getTileBounds(e,t,r,!0,!0),[l,c,h,u]=this.getTileBounds(e,t,r,!0,!1);return[i.MathUtils.mapLinear(s,l,h,0,1),i.MathUtils.mapLinear(n,c,u,0,1),i.MathUtils.mapLinear(a,l,h,0,1),i.MathUtils.mapLinear(o,c,u,0,1)]}getTileBounds(e,t,r,s=!1,n=!0){let{flipY:a,pixelOverlap:o,projection:l}=this,{tilePixelWidth:c,tilePixelHeight:h,pixelWidth:u,pixelHeight:d,tileBounds:p}=this.getLevel(r),m=c*e-o,f=h*t-o,g=m+c+2*o,y=f+h+2*o;if(m=Math.max(m,0),f=Math.max(f,0),g=Math.min(g,u),y=Math.min(y,d),m/=u,g/=u,f/=d,y/=d,a){let e=(y-f)/2,t=1-(f+y)/2;f=t-e,y=t+e}let v=[m,f,g,y];if(p){let e=this.toNormalizedRange(p);v[0]=i.MathUtils.mapLinear(v[0],0,1,e[0],e[2]),v[2]=i.MathUtils.mapLinear(v[2],0,1,e[0],e[2]),v[1]=i.MathUtils.mapLinear(v[1],0,1,e[1],e[3]),v[3]=i.MathUtils.mapLinear(v[3],0,1,e[1],e[3])}return n&&(v=this.clampToBounds(v,!0)),s||(v[0]=l.convertNormalizedToLongitude(v[0]),v[1]=l.convertNormalizedToLatitude(v[1]),v[2]=l.convertNormalizedToLongitude(v[2]),v[3]=l.convertNormalizedToLatitude(v[3])),v}toNormalizedPoint(e,t){return this.projection.toNormalizedPoint(e,t)}toNormalizedRange(e){return this.projection.toNormalizedRange(e)}toCartographicPoint(e,t){return this.projection.toCartographicPoint(e,t)}toCartographicRange(e){return this.projection.toCartographicRange(e)}clampToContentBounds(e,t=!1){let r=[...e],[s,n,a,o]=this.getContentBounds(t);return r[0]=i.MathUtils.clamp(r[0],s,a),r[1]=i.MathUtils.clamp(r[1],n,o),r[2]=i.MathUtils.clamp(r[2],s,a),r[3]=i.MathUtils.clamp(r[3],n,o),r}clampToBounds(e,t=!1){return this.projection.clampToBounds(e,t)}},_n=Symbol("TILE_X"),wn=Symbol("TILE_Y"),Mn=Symbol("TILE_LEVEL"),Sn=Symbol("OVERLAY_RANGE"),An=Symbol("OVERLAY_LEVEL"),Cn=new i.Vector3,En=new i.Vector3,Rn=new i.Sphere,Pn=class{constructor(e={}){let{overlay:t=null,shape:r="ellipsoid",endCaps:i=!0,center:s=!0,useRecommendedSettings:n=!0,applyOverlayTexture:a=!1}=e;this.priority=-10,this.tiles=null,this.overlay=t,this.shape=r,this.endCaps=i,this.center=s,this.useRecommendedSettings=n,this.applyOverlayTexture=a,this._tiling=null}init(e){this.useRecommendedSettings&&(e.errorTarget=1),this.tiles=e}async loadRootTileset(){let{overlay:e}=this;return e?(await e.init(),this._tiling=e.tiling||this._createDefaultTiling()):this._tiling=this._createDefaultTiling(),this.getTileset()}async parseToMesh(e,t,r,i,s){if("generated_surface"!==r)return null;let n;n=this._useEllipsoid()?this._createEllipsoidMesh(t):this._createPlanarMesh(t);let{overlay:a,applyOverlayTexture:o}=this;if(a&&o){let e=t[_n],r=t[wn],i=t[Mn],o=this._tiling.getTileBounds(e,r,i,!0,!1);if(a.hasContent(o,i)){try{await a.lockTexture(o,i)}catch(l){if("AbortError"!==l.name)throw l;return null}let e=a.getTexture(o,i);if(t[Sn]=o,t[An]=i,s.aborted)return a.releaseTexture(o,i),delete t[Sn],delete t[An],null;n.material.map=e,n.material.needsUpdate=!0}}return n}preprocessNode(e){let t=this._tiling.maxLevel;e[Mn]<t&&null!==e.parent&&this.expandChildren(e)}disposeTile(e){let t=e[Sn];this.overlay&&t&&(this.overlay.releaseTexture(t,e[An]),delete e[Sn],delete e[An])}dispose(){this.tiles.forEachLoadedModel(((e,t)=>{this.disposeTile(t)}))}getCartographicFromPosition(e,t={}){let{_tiling:r}=this,{projection:i}=r;if(!i.isCartographic)throw Error("GeneratedSurfacePlugin: getCartographicFromPosition requires a cartographic projection.");if(this._useEllipsoid())return this.tiles.ellipsoid.getPositionToCartographic(e,t);let{center:s}=this,n=e.x/r.aspectRatio+(s?.5:0),a=e.y+(s?.5:0);return t.lat=i.convertNormalizedToLatitude(a),t.lon=i.convertNormalizedToLongitude(n),t}getPositionFromCartographic(e,t,r=new i.Vector3){let{_tiling:s}=this,{projection:n}=s;if(!n.isCartographic)throw Error("GeneratedSurfacePlugin: getPositionFromCartographic requires a cartographic projection.");if(this._useEllipsoid())return this.tiles.ellipsoid.getCartographicToPosition(e,t,0,r);let{center:a}=this,o=n.convertLongitudeToNormalized(t),l=n.convertLatitudeToNormalized(e);return r.x=(o-(a?.5:0))*s.aspectRatio,r.y=l-(a?.5:0),r.z=0,r}_useEllipsoid(){return this._tiling.projection.isCartographic&&"ellipsoid"===this.shape}_createPlanarMesh(e){let t=e[_n],r=e[wn],s=e[Mn],n=e.boundingVolume.box,a=1,o=1,l=0,c=0,h=0;n&&([l,c,h]=n,a=n[3],o=n[7]);let u=new i.PlaneGeometry(2*a,2*o),d=new i.Mesh(u,new i.MeshBasicMaterial);d.position.set(l,c,h);let p=this._tiling.getTileContentUVBounds(t,r,s),{uv:m}=u.attributes;for(let f=0;f<m.count;f++)m.setXY(f,i.MathUtils.mapLinear(m.getX(f),0,1,p[0],p[2]),i.MathUtils.mapLinear(m.getY(f),0,1,p[1],p[3]));return d}_createEllipsoidMesh(e){let{tiles:t,endCaps:r,_tiling:s}=this,{projection:n}=s,a=e[Mn],o=e[_n],l=e[wn],[c,h,u,d]=e.boundingVolume.region,p=Math.max(15,Math.ceil((d-h)*i.MathUtils.RAD2DEG*.25)),m=Math.max(30,Math.ceil((u-c)*i.MathUtils.RAD2DEG*.25)),f=m+3,g=p+3,y=new i.PlaneGeometry(1,1,m+2,p+2),[v,T,x,b]=s.getTileBounds(o,l,a,!0,!0),_=s.getTileContentUVBounds(o,l,a),{position:w,normal:M,uv:S}=y.attributes,A=w.count;e.engineData.boundingVolume.getSphere(Rn);for(let E=0;E<A;E++){let s=E%f,a=Math.floor(E/f),o=0===s||s===f-1||0===a||a===g-1,l=(Math.max(1,Math.min(f-2,s))-1)/m,c=1-(Math.max(1,Math.min(g-2,a))-1)/p,u=n.convertNormalizedToLongitude(i.MathUtils.mapLinear(l,0,1,v,x)),y=n.convertNormalizedToLatitude(i.MathUtils.mapLinear(c,0,1,T,b));if(n.isMercator&&r&&(1===b&&1===c&&(y=Math.PI/2),0===T&&0===c&&(y=-Math.PI/2)),n.isMercator&&0!==c&&1!==c){let e=n.convertNormalizedToLatitude(1),t=1/p,r=i.MathUtils.mapLinear(c-t,0,1,h,d),s=i.MathUtils.mapLinear(c+t,0,1,h,d);y>e&&r<e&&(y=e),y<-e&&s>-e&&(y=-e)}t.ellipsoid.getCartographicToPosition(y,u,0,Cn).sub(Rn.center),t.ellipsoid.getCartographicToNormal(y,u,En),o&&Cn.addScaledVector(En,-e.geometricError);let A=i.MathUtils.mapLinear(n.convertLongitudeToNormalized(u),v,x,_[0],_[2]),C=i.MathUtils.mapLinear(n.convertLatitudeToNormalized(y),T,b,_[1],_[3]);w.setXYZ(E,Cn.x,Cn.y,Cn.z),M.setXYZ(E,En.x,En.y,En.z),S.setXY(E,A,C)}let C=new i.Mesh(y,new i.MeshBasicMaterial);return C.position.copy(Rn.center),C}getTileset(){let{tiles:e,_tiling:t}=this,r=t.minLevel,{tileCountX:i,tileCountY:s}=t.getLevel(r),n=[];for(let o=0;o<i;o++)for(let e=0;e<s;e++){let t=this.createChild(o,e,r);null!==t&&n.push(t)}let a={asset:{version:"1.1"},geometricError:1/0,root:{refine:"REPLACE",geometricError:1/0,boundingVolume:this.createBoundingVolume(0,0,-1),children:n,[Mn]:-1,[_n]:0,[wn]:0}};return e.preprocessTileset(a,""),a}getUrl(){return"tile.generated_surface"}fetchData(e){if(/generated_surface/.test(e))return new ArrayBuffer}createBoundingVolume(e,t,r,i=0){let{_tiling:s}=this,n=-1===r;if(this._useEllipsoid()){let a,o,{endCaps:l}=this;return n?(a=s.getContentBounds(!0),o=s.getContentBounds()):(a=s.getTileBounds(e,t,r,!0,!0),o=s.getTileBounds(e,t,r,!1,!0)),l&&(1===a[3]&&(o[3]=Math.PI/2),0===a[1]&&(o[1]=-Math.PI/2)),{region:[...o,-i,1]}}{let i,{center:a}=this;i=n?s.getContentBounds(!0):s.getTileBounds(e,t,r,!0);let[o,l,c,h]=i,u=(c-o)/2,d=(h-l)/2,p=o+u,m=l+d;return a&&(p-=.5,m-=.5),p*=s.aspectRatio,u*=s.aspectRatio,{box:[p,m,0,u,0,0,0,d,0,0,0,0]}}}createChild(e,t,r){let{_tiling:i}=this,{projection:s}=i;if(!i.getTileExists(e,t,r))return null;let n,a=this._useEllipsoid();if(a){let[a,o,l,c]=i.getTileBounds(e,t,r,!0),{tilePixelWidth:h,tilePixelHeight:u}=i.getLevel(r),d=(l-a)/h,p=(c-o)/u,[,m,f,g]=i.getTileBounds(e,t,r),y=m>0==g>0?Math.min(Math.abs(m),Math.abs(g)):0,v=s.convertLatitudeToNormalized(y),T=s.getLongitudeDerivativeAtNormalized(a),x=s.getLatitudeDerivativeAtNormalized(v),[b,_]=function(e,t,r){let i=1e-5,s=r+i,n=t+i;Math.abs(n)>Math.PI/2&&(n-=i),e.getCartographicToPosition(t,r,0,yn),e.getCartographicToPosition(n,r,0,vn);let a=yn.distanceTo(vn)/i;return e.getCartographicToPosition(t,s,0,vn),[yn.distanceTo(vn)/i,a]}(this.tiles.ellipsoid,y,f);n=Math.max(d*T*b,p*x*_)}else{let{pixelWidth:e,pixelHeight:t}=i.getLevel(r);n=Math.max(i.aspectRatio/e,1/t)}return{refine:"REPLACE",geometricError:n,boundingVolume:this.createBoundingVolume(e,t,r,a?n:0),content:{uri:this.getUrl(e,t,r)},children:[],[_n]:e,[wn]:t,[Mn]:r}}expandChildren(e){let t=e[Mn],r=e[_n],i=e[wn],{tileSplitX:s,tileSplitY:n}=this._tiling.getLevel(t);for(let a=0;a<s;a++)for(let o=0;o<n;o++){let l=this.createChild(s*r+a,n*i+o,t+1);l&&e.children.push(l)}}_createDefaultTiling(){let e=new bn;if("ellipsoid"===this.shape){let t=new Tn("EPSG:3857");e.setProjection(t),e.generateLevels(20,t.tileCountX,t.tileCountY)}else{let t=new Tn("none");e.setProjection(t),e.generateLevels(20,1,1)}return e}},Ln=class extends DOMException{constructor(){super("DataCache: Item removed","AbortError")}};function Un(...e){return e.join("_")}var In=class{constructor(){this.cache={},this.count=0,this.cachedBytes=0,this.active=0}fetchItem(e,t){}disposeItem(e,t){}getMemoryUsage(e){return 0}setData(...e){let{cache:t}=this,r=e.pop(),i=Un(...e);if(i in t)throw Error(`DataCache: "${i}" is already present.`);return this.cache[i]={abortController:new AbortController,result:r,count:1,bytes:this.getMemoryUsage(r)},this.count++,this.cachedBytes+=this.cache[i].bytes,r}lock(...e){let{cache:t}=this,r=Un(...e);if(r in t)t[r].count++;else{let t=new AbortController,i={abortController:t,result:null,count:1,bytes:0,args:e};this.active++,i.result=this.fetchItem(e,t.signal),i.result instanceof Promise?i.result=i.result.then((e=>(t.signal.throwIfAborted(),i.result=e,i.bytes=this.getMemoryUsage(e),this.cachedBytes+=i.bytes,e))).finally((()=>{this.active--})):(this.active--,i.bytes=this.getMemoryUsage(i.result),this.cachedBytes+=i.bytes),this.cache[r]=i,this.count++}return t[r].result}release(...e){let t=Un(...e);this.releaseViaFullKey(t)}get(...e){let{cache:t}=this,r=Un(...e);return r in t&&t[r].count>0?t[r].result:null}has(...e){let{cache:t}=this;return Un(...e)in t}forEachItem(e){let{cache:t}=this;for(let r in t){let i=t[r];i.result instanceof Promise||e(i.result,i.args)}}dispose(){let{cache:e}=this;for(let t in e){let{abortController:r}=e[t];r.abort(new Ln),this.releaseViaFullKey(t,!0)}this.cache={}}releaseViaFullKey(e,t=!1){let{cache:r}=this;if(e in r&&r[e].count>0){let i=r[e];if(i.count--,0===i.count||t){let s=()=>{if(r[e]!==i)return;let{result:t,abortController:s}=i;s.abort(new Ln),t instanceof Promise?t.then((e=>{this.disposeItem(e,i.args)})).catch((()=>{this.disposeItem(null,i.args)})).finally((()=>{this.count--,this.cachedBytes-=i.bytes})):(this.disposeItem(t,i.args),this.count--,this.cachedBytes-=i.bytes),delete r[e]};t?s():queueMicrotask((()=>{0===i.count&&s()}))}return!0}throw Error("DataCache: Attempting to release key that does not exist")}},Fn=class extends In{constructor(e={}){super();let{fetchOptions:t={}}=e;this.tiling=new bn,this.fetchOptions=t,this.fetchData=(...e)=>fetch(...e)}init(){}async processBufferToTexture(e){let t=new Blob([e]),r=new i.Texture(await createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none",imageOrientation:"flipY"}));return r.generateMipmaps=!1,r.colorSpace=i.SRGBColorSpace,r.needsUpdate=!0,r}getMemoryUsage(e){let{format:t,type:r,image:s,generateMipmaps:n}=e,{width:a,height:o}=s,l=i.TextureUtils.getByteLength(a,o,t,r);return n?4*l/3:l}fetchItem(e,t){let r={...this.fetchOptions,signal:t},i=this.getUrl(...e);return this.fetchData(i,r).then((e=>e.arrayBuffer())).then((e=>this.processBufferToTexture(e)))}disposeItem(e){e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}getUrl(...e){}},kn=class extends Fn{constructor(e={}){let{url:t=null,...r}=e;super(r),this.tileSets=null,this.extension=null,this.url=t}getUrl(e,t,r){let{url:i,extension:s,tileSets:n,tiling:a}=this;return new URL(`${parseInt(n[r-a.minLevel].href)}/${e}/${t}.${s}`,i).toString()}init(){let{url:e}=this;return this.fetchData(new URL("tilemapresource.xml",e),this.fetchOptions).then((e=>e.text())).then((t=>{let{tiling:r}=this,s=(new DOMParser).parseFromString(t,"text/xml"),n=s.querySelector("BoundingBox"),a=s.querySelector("TileFormat"),o=[...s.querySelector("TileSets").querySelectorAll("TileSet")].map((e=>({href:parseInt(e.getAttribute("href")),unitsPerPixel:parseFloat(e.getAttribute("units-per-pixel")),order:parseInt(e.getAttribute("order"))}))).sort(((e,t)=>e.order-t.order)),l=parseFloat(n.getAttribute("minx"))*i.MathUtils.DEG2RAD,c=parseFloat(n.getAttribute("maxx"))*i.MathUtils.DEG2RAD,h=parseFloat(n.getAttribute("miny"))*i.MathUtils.DEG2RAD,u=parseFloat(n.getAttribute("maxy"))*i.MathUtils.DEG2RAD,d=parseInt(a.getAttribute("width")),p=parseInt(a.getAttribute("height")),m=a.getAttribute("extension"),f=s.querySelector("SRS").textContent;this.extension=m,this.url=e,this.tileSets=o,r.setProjection(new Tn(f)),r.setContentBounds(l,h,c,u),o.forEach((({order:e})=>{r.setLevel(e,{tileCountX:r.projection.tileCountX*2**e,tilePixelWidth:d,tilePixelHeight:p})}))}))}};function Dn(e,t,r,i){let[s,n,a,o]=e;n+=1e-8,s+=1e-8,o-=1e-8,a-=1e-8;let l=Math.max(Math.min(t,r.maxLevel),r.minLevel),[c,h,u,d]=r.getTilesInRange(s,n,a,o,l,!0);for(let p=c;p<=u;p++)for(let e=h;e<=d;e++)i(p,e,l)}var On=["a","b","c"],Bn=new i.Vector4,Nn=new i.Vector4,Vn=new i.Vector4,zn=new i.Vector4,Gn=class{constructor(){this.attributeList=null,this.splitOperations=[],this.trianglePool=new Hn}forEachSplitPermutation(e){let{splitOperations:t}=this,r=(i=0)=>{i>=t.length?e():(t[i].keepPositive=!0,r(i+1),t[i].keepPositive=!1,r(i+1))};r()}addSplitOperation(e,t=!0){this.splitOperations.push({callback:e,keepPositive:t})}clearSplitOperations(){this.splitOperations.length=0}clipObject(e){let t=e.clone(),r=[];return t.traverse((e=>{e.isMesh&&(e.geometry=this.clip(e).geometry,0==(e.geometry.index?e.geometry.index.count/3:e.attributes.position.count/3)&&r.push(e))})),r.forEach((e=>{e.removeFromParent()})),t}clip(e,t=null){let r=this.getClippedData(e,t);return this.constructMesh(r.attributes,r.index,e)}getClippedData(e,t=null,r={}){let{trianglePool:i,splitOperations:s,attributeList:n}=this,a=e.geometry,o=a.attributes.position,l=a.index,c=0,h={};r.index=r.index||[],r.vertexIsClipped=r.vertexIsClipped||[],r.attributes=r.attributes||{};for(let m in a.attributes)null!==n&&(n instanceof Function&&!n(m)||Array.isArray(n)&&!n.includes(m))||(r.attributes[m]=[]);let u=0,d=l?l.count:o.count;null!==t&&(u=t.start,d=t.count);for(let m=u,f=u+d;m<f;m+=3){let t=m+0,r=m+1,n=m+2;l&&(t=l.getX(t),r=l.getX(r),n=l.getX(n));let o=i.get();o.initFromIndices(t,r,n);let c=[o];for(let i=0;i<s.length;i++){let{keepPositive:t,callback:r}=s[i],n=[];for(let i=0;i<c.length;i++){let s=c[i],{indices:o,barycoord:l}=s;s.clipValues.a=r(a,o.a,o.b,o.c,l.a,e.matrixWorld),s.clipValues.b=r(a,o.a,o.b,o.c,l.b,e.matrixWorld),s.clipValues.c=r(a,o.a,o.b,o.c,l.c,e.matrixWorld),this.splitTriangle(s,!t,n)}c=n}for(let e=0,i=c.length;e<i;e++){p(c[e],a)}i.reset()}return r;function p(e,t){for(let i=0;i<3;i++){let s=e.getVertexHash(i,t);s in h||(h[s]=c,c++,e.getVertexData(i,t,r.attributes),r.vertexIsClipped.push(0===e.clipValues[On[i]]));let n=h[s];r.index.push(n)}}}constructMesh(e,t,r){let s=r.geometry,n=new i.BufferGeometry,a=e.position.length/3>65535?new Uint32Array(t):new Uint16Array(t);n.setIndex(new i.BufferAttribute(a,1,!1));for(let l in e){let t=s.getAttribute(l),r=new i.BufferAttribute(new t.array.constructor(e[l]),t.itemSize,t.normalized);r.gpuType=t.gpuType,n.setAttribute(l,r)}let o=new i.Mesh(n,r.material.clone());return o.position.copy(r.position),o.quaternion.copy(r.quaternion),o.scale.copy(r.scale),o}splitTriangle(e,t,r){let{trianglePool:s}=this,n=[],a=[],o=[];for(let l=0;l<3;l++){let t=On[l],r=On[(l+1)%3],s=e.clipValues[t],c=e.clipValues[r];(s<0!=c<0||0===s)&&(n.push(l),a.push([t,r]),s===c?o.push(0):o.push(i.MathUtils.mapLinear(0,s,c,0,1)))}if(2!==n.length)Math.min(e.clipValues.a,e.clipValues.b,e.clipValues.c)<0===t&&r.push(e);else if(2===n.length){let i,l,c=s.get().initFromTriangle(e),h=s.get().initFromTriangle(e),u=s.get().initFromTriangle(e);(n[0]+1)%3===n[1]?(c.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),c.copyVertex(e,a[0][1],"b"),c.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),c.clipValues.a=0,c.clipValues.c=0,h.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),h.copyVertex(e,a[1][1],"b"),h.copyVertex(e,a[0][0],"c"),h.clipValues.a=0,u.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),u.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"b"),u.copyVertex(e,a[1][1],"c"),u.clipValues.a=0,u.clipValues.b=0):(c.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),c.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"b"),c.copyVertex(e,a[0][0],"c"),c.clipValues.a=0,c.clipValues.b=0,h.lerpVertexFromEdge(e,a[0][0],a[0][1],o[0],"a"),h.copyVertex(e,a[0][1],"b"),h.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),h.clipValues.a=0,h.clipValues.c=0,u.copyVertex(e,a[0][1],"a"),u.copyVertex(e,a[1][0],"b"),u.lerpVertexFromEdge(e,a[1][0],a[1][1],o[1],"c"),u.clipValues.c=0),i=Math.min(c.clipValues.a,c.clipValues.b,c.clipValues.c),l=i<0,l===t&&r.push(c),i=Math.min(h.clipValues.a,h.clipValues.b,h.clipValues.c),l=i<0,l===t&&r.push(h),i=Math.min(u.clipValues.a,u.clipValues.b,u.clipValues.c),l=i<0,l===t&&r.push(u)}}},Hn=class{constructor(){this.pool=[],this.index=0}get(){if(this.index>=this.pool.length){let e=new jn;this.pool.push(e)}let e=this.pool[this.index];return this.index++,e}reset(){this.index=0}},jn=class{constructor(){this.indices={a:-1,b:-1,c:-1},this.clipValues={a:-1,b:-1,c:-1},this.barycoord=new i.Triangle}getVertexHash(e,t){let{barycoord:r,indices:i}=this,s=r[On[e]];if(1===s.x)return i[On[0]];if(1===s.y)return i[On[1]];if(1===s.z)return i[On[2]];{let{attributes:e}=t,r="";for(let t in e){let n=e[t];switch(Wn(n,i.a,i.b,i.c,s,Bn),("normal"===t||"tangent"===t||"bitangent"===t)&&Bn.normalize(),n.itemSize){case 4:r+=qn(Bn.x,Bn.y,Bn.z,Bn.w);break;case 3:r+=qn(Bn.x,Bn.y,Bn.z);break;case 2:r+=qn(Bn.x,Bn.y);break;case 1:r+=qn(Bn.x)}r+="|"}return r}}getVertexData(e,t,r){let{barycoord:i,indices:s}=this,n=i[On[e]],{attributes:a}=t;for(let o in a){if(!r[o])continue;let e=a[o],t=r[o];switch(Wn(e,s.a,s.b,s.c,n,Bn),("normal"===o||"tangent"===o||"bitangent"===o)&&Bn.normalize(),e.itemSize){case 4:t.push(Bn.x,Bn.y,Bn.z,Bn.w);break;case 3:t.push(Bn.x,Bn.y,Bn.z);break;case 2:t.push(Bn.x,Bn.y);break;case 1:t.push(Bn.x)}}}initFromTriangle(e){return this.initFromIndices(e.indices.a,e.indices.b,e.indices.c)}initFromIndices(e,t,r){return this.indices.a=e,this.indices.b=t,this.indices.c=r,this.clipValues.a=-1,this.clipValues.b=-1,this.clipValues.c=-1,this.barycoord.a.set(1,0,0),this.barycoord.b.set(0,1,0),this.barycoord.c.set(0,0,1),this}lerpVertexFromEdge(e,t,r,s,n){this.clipValues[n]=i.MathUtils.lerp(e.clipValues[t],e.clipValues[r],s),this.barycoord[n].lerpVectors(e.barycoord[t],e.barycoord[r],s)}copyVertex(e,t,r){this.clipValues[r]=e.clipValues[t],this.barycoord[r].copy(e.barycoord[t])}};function Wn(e,t,r,i,s,n){switch(Nn.fromBufferAttribute(e,t),Vn.fromBufferAttribute(e,r),zn.fromBufferAttribute(e,i),n.set(0,0,0,0).addScaledVector(Nn,s.x).addScaledVector(Vn,s.y).addScaledVector(zn,s.z),e.itemSize){case 3:Bn.w=0;break;case 2:Bn.w=0,Bn.z=0;break;case 1:Bn.w=0,Bn.z=0,Bn.y=0}return n}function qn(...e){let t="";for(let r=0,i=e.length;r<i;r++)t+=~~(1e5*e[r]+.5),r!==i-1&&(t+="_");return t}var Xn=class{constructor(){this.canvas=null,this.context=null,this.range=[0,0,1,1]}setTarget(e,t){this.canvas=e.image,this.context=e.image.getContext("2d"),this.range=[...t]}draw(e,t){let{canvas:r,range:s,context:n}=this,{width:a,height:o}=r,{image:l}=e,c=Math.round(i.MathUtils.mapLinear(t[0],s[0],s[2],0,a)),h=Math.round(i.MathUtils.mapLinear(t[1],s[1],s[3],0,o)),u=Math.round(i.MathUtils.mapLinear(t[2],s[0],s[2],0,a))-c,d=Math.round(i.MathUtils.mapLinear(t[3],s[1],s[3],0,o))-h;l instanceof ImageBitmap?(n.save(),n.translate(c,o-h),n.scale(1,-1),n.drawImage(l,0,0,u,d),n.restore()):n.drawImage(l,c,o-h,u,-d)}clear(){let{context:e,canvas:t}=this;e.clearRect(0,0,t.width,t.height)}};var Kn=class extends In{hasContent(...e){return!0}},Yn=class extends Kn{constructor(e){super(),this.tiledImageSource=e,this.tileComposer=new Xn,this.resolution=256}hasContent(e,t,r,i,s){let n=this.tiledImageSource.tiling,a=0;return Dn([e,t,r,i],s,n,(()=>{a++})),0!==a}async fetchItem([e,t,r,s,n],a){let{tiledImageSource:o,tileComposer:l}=this,c=[e,t,r,s],h=o.tiling;await this._markImages(c,n,!1),null==a||a.throwIfAborted();let u=null;if(Dn(c,n,h,((e,t,r)=>{(function(e,t,r=0){if(e.length!==t.length)return!1;for(let i=0,s=e.length;i<s;i++)if(Math.abs(e[i]-t[i])>r)return!1;return!0})(h.getTileBounds(e,t,r,!0,!1),c,1e-10)&&(u=[e,t,r])})),null!==u){let[e,t,r]=u;return o.get(e,t,r).clone()}let d=document.createElement("canvas");d.width=this.resolution,d.height=this.resolution;let p=new i.CanvasTexture(d);return p.colorSpace=i.SRGBColorSpace,p.generateMipmaps=!1,l.setTarget(p,c),l.clear(16777215,0),Dn(c,n,h,((e,t,r)=>{let i=h.getTileBounds(e,t,r,!0,!1),s=o.get(e,t,r);l.draw(s,i)})),p}disposeItem(e,[t,r,i,s,n]){e&&e.dispose(),this._markImages([t,r,i,s],n,!0)}dispose(){super.dispose(),this.tiledImageSource.dispose()}_markImages(e,t,r=!1){let i=this.tiledImageSource,s=i.tiling,n=[];Dn(e,t,s,((e,t,s)=>{r?i.release(e,t,s):n.push(i.lock(e,t,s))}));let a=n.filter((e=>e instanceof Promise));return 0===a.length?null:Promise.all(a)}},Qn=new ce;Qn.maxJobs=10,Qn.priorityCallback=(e,t)=>{let r=e.tile,i=t.tile,s=r.internal.renderer,n=i.internal.renderer,a=s.visibleTiles.has(r);return a===n.visibleTiles.has(i)?Le(r,i):a?1:-1};var $n=class{get isPlanarProjection(){return!!this.frame}get downloadQueue(){return this._downloadQueue}set downloadQueue(e){e instanceof ce||(this._downloadQueue=e)}constructor(e={}){let{opacity:t=1,color:r=16777215,frame:s=null,preprocessURL:n=null,alphaMask:a=!1,alphaInvert:o=!1}=e;this.preprocessURL=n,this.opacity=t,this.color=new i.Color(r),this.frame=null===s?null:s.clone(),this.alphaMask=a,this.alphaInvert=o,this.downloadQueue=Ie,this._whenReady=null,this.isReady=!1,this.isInitialized=!1,this._visibleRegionCounts=new Map}init(){return this.isInitialized||(this.isInitialized=!0,this._whenReady=this._init().then((()=>this.isReady=!0))),this._whenReady}whenReady(){return this._whenReady}_init(){return Promise.resolve()}fetch(e,t={}){this.preprocessURL&&(e=this.preprocessURL(e));let r={priority:-performance.now()};return this.downloadQueue.add(e,r,(()=>fetch(e,t)),t.signal)}getAttributions(e){}hasContent(e,t=null){return!1}async getTexture(e,t=null){return null}async lockTexture(e,t=null){return null}lockTextureSafe(e){let t=this.lockTexture(e);return t instanceof Promise&&t.catch((e=>{if("AbortError"!==e.name)throw e})),t}releaseTexture(e,t=null){}shouldSplit(e,t=null){return!1}setResolution(e){}setRegionVisible(e,t){let{_visibleRegionCounts:r}=this,i=e.join("_"),s=r.get(i);if(s||(s={range:[...e],count:0},r.set(i,s)),s.count+=t?1:-1,s.count<0)throw Error();0===s.count&&r.delete(i)}},Zn=class extends $n{get tiling(){return this.imageSource.tiling}get projection(){return this.tiling.projection}get aspectRatio(){return this.tiling&&this.isReady?this.tiling.aspectRatio:1}get fetchOptions(){return this.imageSource.fetchOptions}set fetchOptions(e){this.imageSource.fetchOptions=e}constructor(e={}){let{imageSource:t=null,...r}=e;super(r),this.imageSource=t,this.regionImageSource=null}_init(){return this._initImageSource().then((()=>{this.imageSource.fetchData=(...e)=>this.fetch(...e),this.regionImageSource=new Yn(this.imageSource)}))}_initImageSource(){return this.imageSource.init()}calculateLevel(e,t=null){let[r,i,s,n]=e,a=s-r,o=n-i;null===t&&(t=this.regionImageSource.resolution);let l=0,c=this.tiling.maxLevel;for(;l<c;l++){let e=t/a,r=t/o,i=this.tiling.getLevel(l);if(null==i)continue;let{pixelWidth:s,pixelHeight:n}=i;if(s>=e||n>=r)break}return l}hasContent(e,t=this.calculateLevel(e)){return this.regionImageSource.hasContent(...e,t)}getTexture(e,t=this.calculateLevel(e)){return this.regionImageSource.get(...e,t)}lockTexture(e,t=this.calculateLevel(e)){return this.regionImageSource.lock(...e,t)}releaseTexture(e,t=this.calculateLevel(e)){this.regionImageSource.release(...e,t)}shouldSplit(e,t=this.calculateLevel(e)){return this.tiling.maxLevel>t}setResolution(e){this.regionImageSource.resolution=e}},Jn=class extends Zn{constructor(e={}){super(e),this.imageSource=new kn(e)}},ea=new i.Vector3,ta=new i.Triangle,ra=new i.Vector3,ia=new i.Vector3,sa=class extends un{constructor(e=i.DefaultLoadingManager){super(),this.manager=e,this.ellipsoid=new gr,this.skirtLength=1e3,this.smoothSkirtNormals=!0,this.generateNormals=!0,this.solid=!1,this.minLat=-Math.PI/2,this.maxLat=Math.PI/2,this.minLon=-Math.PI,this.maxLon=Math.PI}parse(e){let{ellipsoid:t,solid:r,skirtLength:s,smoothSkirtNormals:n,generateNormals:a,minLat:o,maxLat:l,minLon:c,maxLon:h}=this,{header:u,indices:d,vertexData:p,edgeIndices:m,extensions:f}=super.parse(e),g=new i.BufferGeometry,y=new i.MeshStandardMaterial,v=new i.Mesh(g,y);v.position.set(...u.center);let T="octvertexnormals"in f,x=T||a,b=p.u.length,_=[],w=[],M=[],S=[],A=0,C=0;for(let i=0;i<b;i++)R(i,ra),P(ra.x,ra.y,ra.z,ia),w.push(ra.x,ra.y),_.push(...ia);for(let i=0,U=d.length;i<U;i++)M.push(d[i]);if(x)if(T){let e=f.octvertexnormals.normals;for(let t=0,r=e.length;t<r;t++)S.push(e[t])}else{let e=new i.BufferGeometry,t=d.length>21845?new Uint32Array(d):new Uint16Array(d);e.setIndex(new i.BufferAttribute(t,1,!1)),e.setAttribute("position",new i.BufferAttribute(new Float32Array(_),3,!1)),e.computeVertexNormals();let r=e.getAttribute("normal").array;f.octvertexnormals={normals:r};for(let i=0,s=r.length;i<s;i++)S.push(r[i])}if(g.addGroup(A,d.length,C),A+=d.length,C++,r){let e=_.length/3;for(let t=0;t<b;t++)R(t,ra),P(ra.x,ra.y,ra.z,ia,-s),w.push(ra.x,ra.y),_.push(...ia);for(let t=d.length-1;t>=0;t--)M.push(d[t]+e);if(x){let e=f.octvertexnormals.normals;for(let t=0,r=e.length;t<r;t++)S.push(-e[t])}g.addGroup(A,d.length,C),A+=d.length,C++}if(s>0){let e,{westIndices:t,eastIndices:r,southIndices:i,northIndices:s}=m,n=L(t);e=_.length/3,w.push(...n.uv),_.push(...n.positions);for(let c=0,h=n.indices.length;c<h;c++)M.push(n.indices[c]+e);let a=L(r);e=_.length/3,w.push(...a.uv),_.push(...a.positions);for(let c=0,h=a.indices.length;c<h;c++)M.push(a.indices[c]+e);let o=L(i);e=_.length/3,w.push(...o.uv),_.push(...o.positions);for(let c=0,h=o.indices.length;c<h;c++)M.push(o.indices[c]+e);let l=L(s);e=_.length/3,w.push(...l.uv),_.push(...l.positions);for(let c=0,h=l.indices.length;c<h;c++)M.push(l.indices[c]+e);x&&(S.push(...n.normals),S.push(...a.normals),S.push(...o.normals),S.push(...l.normals)),g.addGroup(A,d.length,C),A+=d.length,C++}for(let i=0,U=_.length;i<U;i+=3)_[i+0]-=u.center[0],_[i+1]-=u.center[1],_[i+2]-=u.center[2];let E=_.length/3>65535?new Uint32Array(M):new Uint16Array(M);if(g.setIndex(new i.BufferAttribute(E,1,!1)),g.setAttribute("position",new i.BufferAttribute(new Float32Array(_),3,!1)),g.setAttribute("uv",new i.BufferAttribute(new Float32Array(w),2,!1)),x&&g.setAttribute("normal",new i.BufferAttribute(new Float32Array(S),3,!1)),"watermask"in f){let{mask:e,size:t}=f.watermask,r=new Uint8Array(2*t*t);for(let i=0,n=e.length;i<n;i++){let t=255===e[i]?0:255;r[2*i+0]=t,r[2*i+1]=t}let s=new i.DataTexture(r,t,t,i.RGFormat,i.UnsignedByteType);s.flipY=!0,s.minFilter=i.LinearMipMapLinearFilter,s.magFilter=i.LinearFilter,s.needsUpdate=!0,y.roughnessMap=s}return v.userData.minHeight=u.minHeight,v.userData.maxHeight=u.maxHeight,"metadata"in f&&(v.userData.metadata=f.metadata.json),v;function R(e,t){return t.x=p.u[e],t.y=p.v[e],t.z=p.height[e],t}function P(e,r,s,n,a=0){let d=i.MathUtils.lerp(u.minHeight,u.maxHeight,s),p=i.MathUtils.lerp(c,h,e),m=i.MathUtils.lerp(o,l,r);return t.getCartographicToPosition(m,p,d+a,n),n}function L(e){let t=[],r=[],i=[],a=[],o=[];for(let n=0,h=e.length;n<h;n++)R(e[n],ra),t.push(ra.x,ra.y),i.push(ra.x,ra.y),P(ra.x,ra.y,ra.z,ia),r.push(...ia),P(ra.x,ra.y,ra.z,ia,-s),a.push(...ia);let l=e.length-1;for(let s=0;s<l;s++){let t=s,r=s+1,i=s+e.length,n=s+e.length+1;o.push(t,i,r),o.push(r,i,n)}let c=null;if(x){let t=(r.length+a.length)/3;if(n){c=Array(3*t);let r=f.octvertexnormals.normals,i=c.length/2;for(let s=0,n=t/2;s<n;s++){let t=e[s],n=3*s,a=r[3*t+0],o=r[3*t+1],l=r[3*t+2];c[n+0]=a,c[n+1]=o,c[n+2]=l,c[i+n+0]=a,c[i+n+1]=o,c[i+n+2]=l}}else{c=[],ta.a.fromArray(r,0),ta.b.fromArray(a,0),ta.c.fromArray(r,3),ta.getNormal(ea);for(let e=0;e<t;e++)c.push(...ea)}}return{uv:[...t,...i],positions:[...r,...a],indices:o,normals:c}}}},na={},aa=new i.Vector3,oa=new i.Vector3,la=new i.Vector3,ca=new i.Vector3,ha=new i.Vector3,ua=new i.Vector3,da=new i.Vector3,pa=new i.Vector2,ma=new i.Vector2,fa=new i.Vector2,ga=class extends Gn{constructor(){super(),this.ellipsoid=new gr,this.skirtLength=1e3,this.smoothSkirtNormals=!0,this.solid=!1,this.minLat=-Math.PI/2,this.maxLat=Math.PI/2,this.minLon=-Math.PI,this.maxLon=Math.PI,this.attributeList=["position","normal","uv"]}clipToQuadrant(e,t,r){let{solid:i,skirtLength:s,ellipsoid:n,smoothSkirtNormals:a}=this;this.clearSplitOperations(),this.addSplitOperation(ya("x"),!t),this.addSplitOperation(ya("y"),!r);let o,l,c=e.geometry.groups[0],h=this.getClippedData(e,c);if(this.adjustVertices(h,e.position,0),i){o={index:h.index.slice().reverse(),attributes:{}};for(let e in h.attributes)o.attributes[e]=h.attributes[e].slice();let t=o.attributes.normal;if(t)for(let e=0;e<t.length;e+=3)t[e+0]*=-1,t[e+1]*=-1,t[e+2]*=-1;this.adjustVertices(o,e.position,-s)}if(s>0){l={index:[],attributes:{position:[],normal:[],uv:[]}};let t=0,r={},i=(e,i,s)=>{let n=qn(...e,...s,...i);n in r||(r[n]=t,t++,l.attributes.position.push(...e),l.attributes.normal.push(...s),l.attributes.uv.push(...i)),l.index.push(r[n])},o=h.index,c=h.attributes.uv,u=h.attributes.position,d=h.attributes.normal,p=h.index.length/3;for(let l=0;l<p;l++){let t=3*l;for(let r=0;r<3;r++){let l=(r+1)%3,h=o[t+r],p=o[t+l];if(pa.fromArray(c,2*h),ma.fromArray(c,2*p),pa.x===ma.x&&(0===pa.x||.5===pa.x||1===pa.x)||pa.y===ma.y&&(0===pa.y||.5===pa.y||1===pa.y)){oa.fromArray(u,3*h),la.fromArray(u,3*p);let t=oa,r=la,o=ca.copy(oa),l=ha.copy(la);ua.copy(o).add(e.position),n.getPositionToNormal(ua,ua),o.addScaledVector(ua,-s),ua.copy(l).add(e.position),n.getPositionToNormal(ua,ua),l.addScaledVector(ua,-s),a&&d?(ua.fromArray(d,3*h),da.fromArray(d,3*p)):(ua.subVectors(t,r),da.subVectors(t,o).cross(ua).normalize(),ua.copy(da)),i(r,ma,da),i(t,pa,ua),i(o,pa,ua),i(r,ma,da),i(o,pa,ua),i(l,ma,da)}}}}let u=h.index.length,d=h;if(o){let{index:e,attributes:t}=o,r=d.attributes.position.length/3;for(let i=0,s=e.length;i<s;i++)d.index.push(e[i]+r);for(let i in h.attributes)d.attributes[i].push(...t[i])}if(l){let{index:e,attributes:t}=l,r=d.attributes.position.length/3;for(let i=0,s=e.length;i<s;i++)d.index.push(e[i]+r);for(let i in h.attributes)d.attributes[i].push(...t[i])}let p=t?0:-.5,m=r?0:-.5,f=d.attributes.uv;for(let T=0,x=f.length;T<x;T+=2)f[T]=2*(f[T]+p),f[T+1]=2*(f[T+1]+m);let g=this.constructMesh(d.attributes,d.index,e);g.userData.minHeight=e.userData.minHeight,g.userData.maxHeight=e.userData.maxHeight;let y=0,v=0;return g.geometry.addGroup(v,u,y),v+=u,y++,o&&(g.geometry.addGroup(v,o.index.length,y),v+=o.index.length,y++),l&&(g.geometry.addGroup(v,l.index.length,y),v+=l.index.length,y++),g}adjustVertices(e,t,r){let{ellipsoid:s,minLat:n,maxLat:a,minLon:o,maxLon:l}=this,{attributes:c,vertexIsClipped:h}=e,u=c.position,d=c.uv,p=u.length/3;for(let m=0;m<p;m++){let e=pa.fromArray(d,2*m);h&&h[m]&&(Math.abs(e.x-.5)<1e-10&&(e.x=.5),Math.abs(e.y-.5)<1e-10&&(e.y=.5),pa.toArray(d,2*m));let c=i.MathUtils.lerp(n,a,e.y),p=i.MathUtils.lerp(o,l,e.x),f=aa.fromArray(u,3*m).add(t);s.getPositionToCartographic(f,na),s.getCartographicToPosition(c,p,na.height+r,f),f.sub(t),f.toArray(u,3*m)}}};function ya(e){return(t,r,i,s,n)=>{let a=t.attributes.uv;return pa.fromBufferAttribute(a,r),ma.fromBufferAttribute(a,i),fa.fromBufferAttribute(a,s),pa[e]*n.x+ma[e]*n.y+fa[e]*n.z-.5}}var va=Symbol("TILE_X"),Ta=Symbol("TILE_Y"),xa=Symbol("TILE_LEVEL"),ba=Symbol("TILE_AVAILABLE"),_a=Symbol("TILE_SPLIT_SOURCE_SCENE"),wa=new i.Vector3;function Ma(e){let{available:t=null,maxzoom:r=null}=e;return null===r?t.length-1:r}function Sa(e,t){let r=e[xa],i=function(e){let{metadataAvailability:t=-1}=e;return t}(t);return r<Ma(t)&&-1!==i&&r%i==0}var Aa=class{constructor(e={}){let{useRecommendedSettings:t=!0,skirtLength:r=null,smoothSkirtNormals:i=!0,generateNormals:s=!0,solid:n=!1}=e;this.name="QUANTIZED_MESH_PLUGIN",this.priority=-1e3,this.tiles=null,this.layer=null,this.useRecommendedSettings=t,this.skirtLength=r,this.smoothSkirtNormals=i,this.solid=n,this.generateNormals=s,this.attribution=null,this.tiling=new bn,this.projection=new Tn}init(e){e.fetchOptions.headers=e.fetchOptions.headers||{},e.fetchOptions.headers.Accept="application/vnd.quantized-mesh,application/octet-stream;q=0.9",this.useRecommendedSettings&&(e.errorTarget=2),this.tiles=e}loadRootTileset(){let{tiles:e}=this,t=new URL("layer.json",new URL(e.rootURL,location.href));return e.invokeAllPlugins((e=>t=e.preprocessURL?e.preprocessURL(t,null):t)),e.invokeOnePlugin((e=>e.fetchData&&e.fetchData(t,this.tiles.fetchOptions))).then((e=>e.json())).then((e=>{this.layer=e;let{projection:t="EPSG:4326",extensions:r=[],attribution:i="",available:s=null}=e,{tiling:n,tiles:a,projection:o}=this;i&&(this.attribution={value:i,type:"string",collapsible:!0}),r.length>0&&(a.fetchOptions.headers.Accept+=`;extensions=${r.join("-")}`),o.setScheme(t);let{tileCountX:l,tileCountY:c}=o;n.setProjection(o),n.generateLevels(Ma(e)+1,l,c);let h=[];for(let p=0;p<l;p++){let e=this.createChild(0,p,0,s);e&&h.push(e)}let u={asset:{version:"1.1"},geometricError:1/0,root:{refine:"REPLACE",geometricError:1/0,boundingVolume:{region:[...this.tiling.getContentBounds(),-1e4,1e4]},children:h,[ba]:s,[xa]:-1}},d=a.rootURL;return a.invokeAllPlugins((e=>d=e.preprocessURL?e.preprocessURL(d,null):d)),a.preprocessTileset(u,d),u}))}parseToMesh(e,t,r,i){let s,{skirtLength:n,solid:a,smoothSkirtNormals:o,generateNormals:l,tiles:c}=this,h=c.ellipsoid;if("quantized_tile_split"===r){let e=new URL(i).searchParams,r="true"===e.get("left"),l="true"===e.get("bottom"),c=new ga;c.ellipsoid.copy(h),c.solid=a,c.smoothSkirtNormals=o,c.skirtLength=null===n?t.geometricError:n;let[u,d,p,m]=t.parent.boundingVolume.region;c.minLat=d,c.maxLat=m,c.minLon=u,c.maxLon=p;let f=t.parent.engineData.scene||t.parent[_a];s=c.clipToQuadrant(f,r,l)}else{if("terrain"!==r)return;{let r=new sa(c.manager);r.ellipsoid.copy(h),r.solid=a,r.smoothSkirtNormals=o,r.generateNormals=l,r.skirtLength=null===n?t.geometricError:n;let[i,u,d,p]=t.boundingVolume.region;r.minLat=u,r.maxLat=p,r.minLon=i,r.maxLon=d,s=r.parse(e)}}let{minHeight:u,maxHeight:d,metadata:p}=s.userData;return t.boundingVolume.region[4]=u,t.boundingVolume.region[5]=d,t.engineData.boundingVolume.setRegionData(h,...t.boundingVolume.region),p&&("geometricerror"in p&&(t.geometricError=p.geometricerror),Sa(t,this.layer)&&"available"in p&&0===t.children.length&&(t[ba]=[...Array(t[xa]+1).fill(null),...p.available])),t[_a]=s,this.expandChildren(t),s}getAttributions(e){this.attribution&&e.push(this.attribution)}createChild(e,t,r,i){let{tiles:s,layer:n,tiling:a,projection:o}=this,l=s.ellipsoid,c=null===i&&0===e||function(e,t,r,i){if(e&&t<e.length){let s=e[t];for(let e=0,t=s.length;e<t;e++){let{startX:t,startY:n,endX:a,endY:o}=s[e];if(r>=t&&r<=a&&i>=n&&i<=o)return!0}}return!1}(i,e,t,r),h=function(e,t,r,i,s){return s.tiles[0].replace(/{\s*z\s*}/g,r).replace(/{\s*x\s*}/g,e).replace(/{\s*y\s*}/g,t).replace(/{\s*version\s*}/g,i)}(t,r,e,1,n),u=[...a.getTileBounds(t,r,e),-1e4,1e4],[,d,,p,,m]=u,f=d>0==p>0?Math.min(Math.abs(d),Math.abs(p)):0;l.getCartographicToPosition(f,0,m,wa),wa.z=0;let g=o.tileCountX,y=2*Math.max(...l.radius)*Math.PI*.25/(65*g)/2**e,v={[ba]:null,[xa]:e,[va]:t,[Ta]:r,refine:"REPLACE",geometricError:y,boundingVolume:{region:u},content:c?{uri:h}:null,children:[]};return Sa(v,n)||(v[ba]=i),v}expandChildren(e){let t=e[xa],r=e[va],i=e[Ta],s=e[ba];if(t>=this.tiling.maxLevel)return;let n=!1;for(let a=0;a<2;a++)for(let o=0;o<2;o++){let l=this.createChild(t+1,2*r+a,2*i+o,s);null===l.content?(l.content={uri:`tile.quantized_tile_split?bottom=${0===o}&left=${0===a}`},l.internal={isVirtual:!0},e.internal.virtualChildCount++,e.children.push(l)):(e.children.push(l),n=!0)}n||(e.children.length-=e.internal.virtualChildCount,e.internal.virtualChildCount=0)}fetchData(e,t){if(/quantized_tile_split/.test(e))return new ArrayBuffer}disposeTile(e){let{tiles:t,layer:r}=this;if(delete e[_a],Sa(e,r)&&(e[ba]=null),ba in e){let{virtualChildCount:r}=e.internal,i=e.children.length;for(let s=i-r;s<i;s++)t.processNodeQueue.remove(e.children[s]);e.children.length=0,e.internal.virtualChildCount=0}}},Ca=class extends sn{constructor(e={}){super({assetTypeHandler:(e,t,r)=>{if("TERRAIN"===e&&null===t.getPluginByName("QUANTIZED_MESH_PLUGIN"))t.registerPlugin(new Aa({useRecommendedSettings:this.useRecommendedSettings}));else if("IMAGERY"===e&&null===t.getPluginByName("GENERATED_SURFACE_PLUGIN")){let e=new Jn({url:t.rootURL});t.registerPlugin(new Pn({shape:"ellipsoid",overlay:e}))}},...e})}},Ea=new i.Matrix4,Ra=class{constructor(){this.name="UPDATE_ON_CHANGE_PLUGIN",this.tiles=null,this.needsUpdate=!1,this.cameraMatrices=new Map}init(e){this.tiles=e,this._needsUpdateCallback=()=>{this.needsUpdate=!0},this._onCameraAdd=({camera:e})=>{this.needsUpdate=!0,this.cameraMatrices.set(e,new i.Matrix4)},this._onCameraDelete=({camera:e})=>{this.needsUpdate=!0,this.cameraMatrices.delete(e)},e.addEventListener("needs-update",this._needsUpdateCallback),e.addEventListener("add-camera",this._onCameraAdd),e.addEventListener("delete-camera",this._onCameraDelete),e.addEventListener("camera-resolution-change",this._needsUpdateCallback),e.cameras.forEach((e=>{this._onCameraAdd({camera:e})}))}doTilesNeedUpdate(){let e=this.tiles,t=!1;this.cameraMatrices.forEach(((r,i)=>{Ea.copy(e.group.matrixWorld).premultiply(i.matrixWorldInverse).premultiply(i.projectionMatrixInverse),t||(t=!Ea.equals(r)),r.copy(Ea)}));let r=this.needsUpdate;return this.needsUpdate=!1,r||t}preprocessNode(){this.needsUpdate=!0}dispose(){let e=this.tiles;e.removeEventListener("camera-resolution-change",this._needsUpdateCallback),e.removeEventListener("needs-update",this._needsUpdateCallback),e.removeEventListener("add-camera",this._onCameraAdd),e.removeEventListener("delete-camera",this._onCameraDelete)}},Pa=new i.Vector3;function La(e,t){if(e.isInterleavedBufferAttribute||e.array instanceof t)return e;let r=t===Int8Array||t===Int16Array||t===Int32Array?-1:0,s=new i.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!0),n=e.itemSize,a=e.count;for(let o=0;o<a;o++)for(let t=0;t<n;t++){let n=i.MathUtils.clamp(e.getComponent(o,t),r,1);s.setComponent(o,t,n)}return s}var Ua=class{constructor(e){this._options={generateNormals:!1,disableMipmaps:!0,compressIndex:!0,compressNormals:!1,compressUvs:!1,compressPosition:!1,uvType:Int8Array,normalType:Int8Array,positionType:Int16Array,...e},this.name="TILES_COMPRESSION_PLUGIN",this.priority=-100}processTileModel(e,t){let{generateNormals:r,disableMipmaps:s,compressIndex:n,compressUvs:a,compressNormals:o,compressPosition:l,uvType:c,normalType:h,positionType:u}=this._options;e.traverse((e=>{if(e.material&&s){let t=e.material;for(let e in t){let r=t[e];r&&r.isTexture&&r.generateMipmaps&&(r.generateMipmaps=!1,r.minFilter=i.LinearFilter)}}if(e.geometry){let t=e.geometry,s=t.attributes;if(a){let{uv:e,uv1:t,uv2:r,uv3:i}=s;e&&(s.uv=La(e,c)),t&&(s.uv1=La(t,c)),r&&(s.uv2=La(r,c)),i&&(s.uv3=La(i,c))}if(r&&!s.normals&&t.computeVertexNormals(),o&&s.normals&&(s.normals=La(s.normals,h)),l&&function(e,t=Int16Array){let r=e.geometry,s=r.attributes,n=s.position;if(n.isInterleavedBufferAttribute||n.array instanceof t)return n;let a=new i.BufferAttribute(new t(n.count*n.itemSize),n.itemSize,!1),o=n.itemSize,l=n.count;r.computeBoundingBox();let c=r.boundingBox,{min:h,max:u}=c,d=2**(8*t.BYTES_PER_ELEMENT-1)-1,p=-d;for(let m=0;m<l;m++)for(let e=0;e<o;e++){let t=0===e?"x":1===e?"y":"z",r=h[t],s=u[t],o=i.MathUtils.mapLinear(n.getComponent(m,e),r,s,p,d);a.setComponent(m,e,o)}c.getCenter(Pa).multiply(e.scale).applyQuaternion(e.quaternion),e.position.add(Pa),e.scale.x*=.5*(u.x-h.x)/d,e.scale.y*=.5*(u.y-h.y)/d,e.scale.z*=.5*(u.z-h.z)/d,s.position=a,e.geometry.boundingBox=null,e.geometry.boundingSphere=null,e.updateMatrixWorld()}(e,u),n&&t.index){let e=s.position.count,r=t.index,n=e>65535?Uint32Array:e>255?Uint16Array:Uint8Array;if(!(r.array instanceof n)){let e=new n(t.index.count);e.set(r.array);let s=new i.BufferAttribute(e,1);t.setIndex(s)}}}}))}};function Ia(e,t,r){return e&&t in e?e[t]:r}function Fa(e){return"BOOLEAN"!==e&&"STRING"!==e&&"ENUM"!==e}function ka(e){return/^VEC/.test(e)}function Da(e){return/^MAT/.test(e)}function Oa(e,t,r,i=null){return Da(r)||ka(r)?i.fromArray(e,t):e[t]}function Ba(e){let{type:t,componentType:r}=e;switch(t){case"SCALAR":return"INT64"===r?0n:0;case"VEC2":return new i.Vector2;case"VEC3":return new i.Vector3;case"VEC4":return new i.Vector4;case"MAT2":return new i.Matrix2;case"MAT3":return new i.Matrix3;case"MAT4":return new i.Matrix4;case"BOOLEAN":return!1;case"STRING":return"";case"ENUM":return 0}}function Na(e,t){if(null==t)return!1;switch(e){case"SCALAR":case"ENUM":return"number"==typeof t||"bigint"==typeof t;case"VEC2":return t.isVector2;case"VEC3":return t.isVector3;case"VEC4":return t.isVector4;case"MAT2":return t.isMatrix2;case"MAT3":return t.isMatrix3;case"MAT4":return t.isMatrix4;case"BOOLEAN":return"boolean"==typeof t;case"STRING":return"string"==typeof t}throw Error("ClassProperty: invalid type.")}function Va(e,t=null){switch(e){case"INT8":return Int8Array;case"INT16":return Int16Array;case"INT32":return Int32Array;case"INT64":return BigInt64Array;case"UINT8":return Uint8Array;case"UINT16":return Uint16Array;case"UINT32":return Uint32Array;case"UINT64":return BigUint64Array;case"FLOAT32":return Float32Array;case"FLOAT64":return Float64Array}switch(t){case"BOOLEAN":case"STRING":return Uint8Array}throw Error("ClassProperty: invalid type.")}function za(e,t=null){let r=e.default,i=e.type;if(t||(t=Ba(e)),null===r){switch(i){case"SCALAR":return 0;case"VEC2":return t.set(0,0);case"VEC3":return t.set(0,0,0);case"VEC4":return t.set(0,0,0,0);case"MAT2":case"MAT3":case"MAT4":return t.identity();case"BOOLEAN":return!1;case"STRING":case"ENUM":return""}throw Error("ClassProperty: invalid type.")}if(Da(i))t.fromArray(r);else{if(!ka(i))return r;t.fromArray(r)}}function Ga(e,t){if(null===e.noData)return t;let r=e.noData,i=e.type;if(Array.isArray(t))for(let n=0,a=t.length;n<a;n++)t[n]=s(t[n]);else t=s(t);return t;function s(t){return function(e){if(Da(i)){let t=e.elements;for(let e=0,i=r.length;e<i;e++)if(r[e]!==t[e])return!1;return!0}if(ka(i)){for(let t=0,i=r.length;t<i;t++)if(r[t]!==e.getComponent(t))return!1;return!0}return r===e}(t)&&(t=za(e,t)),t}}function Ha(e,t){let{type:r,componentType:i,scale:s,offset:n,normalized:a}=e;if(Array.isArray(t))for(let c=0,h=t.length;c<h;c++)t[c]=o(t[c]);else t=o(t);return t;function o(e){return e=Da(r)?function(e){let t=e.elements;for(let r=0,i=t.length;r<i;r++)t[r]=l(t[r]);return e}(e):ka(r)?function(e){return e.x=l(e.x),e.y=l(e.y),"z"in e&&(e.z=l(e.z)),"w"in e&&(e.w=l(e.w)),e}(e):l(e)}function l(e){return a&&(e=function(e,t){switch(e){case"INT8":return Math.max(t/127,-1);case"INT16":return Math.max(t,32767,-1);case"INT32":return Math.max(t/2147483647,-1);case"INT64":return Math.max(Number(t)/0x8000000000000000,-1);case"UINT8":return t/255;case"UINT16":return t/65535;case"UINT32":return t/4294967295;case"UINT64":return Number(t)/0x10000000000000000}}(i,e)),(a||function(e){return/^FLOAT/.test(e)}(i))&&(e=e*s+n),e}}function ja(e,t,r=null){if(e.array){Array.isArray(t)||(t=Array(e.count||0)),t.length=null===r?e.count:r;for(let r=0,i=t.length;r<i;r++)Na(e.type,t[r])||(t[r]=Ba(e))}else Na(e.type,t)||(t=Ba(e));return t}function Wa(e,t){for(let r in t)r in e||delete t[r];for(let r in e){let i=e[r];t[r]=ja(i,t[r])}}var qa=class{constructor(e,t,r=null){this.name=t.name||null,this.description=t.description||null,this.type=t.type,this.componentType=t.componentType||null,this.enumType=t.enumType||null,this.array=t.array||!1,this.count=t.count||0,this.normalized=t.normalized||!1,this.offset=t.offset||0,this.scale=Ia(t,"scale",1),this.max=Ia(t,"max",1/0),this.min=Ia(t,"min",-1/0),this.required=t.required||!1,this.noData=Ia(t,"noData",null),this.default=Ia(t,"default",null),this.semantic=Ia(t,"semantic",null),this.enumSet=null,this.accessorProperty=r,r&&(this.offset=Ia(r,"offset",this.offset),this.scale=Ia(r,"scale",this.scale),this.max=Ia(r,"max",this.max),this.min=Ia(r,"min",this.min)),"ENUM"===t.type&&(this.enumSet=e[this.enumType],null===this.componentType&&(this.componentType=Ia(this.enumSet,"valueType","UINT16")))}shapeToProperty(e,t=null){return ja(this,e,t)}resolveDefaultElement(e){return za(this,e)}resolveDefault(e){return function(e,t=null){if(e.array){(t=t&&Array.isArray(t)?t:[]).length=e.count;for(let r=0,i=t.length;r<i;r++)t[r]=za(e,t[r])}else t=za(e,t);return t}(this,e)}resolveNoData(e){return Ga(this,e)}resolveEnumsToStrings(e){let t=this.enumSet;if("ENUM"===this.type)if(Array.isArray(e))for(let i=0,s=e.length;i<s;i++)e[i]=r(e[i]);else e=r(e);return e;function r(e){let r=t.values.find((t=>t.value===e));return null===r?"":r.name}}adjustValueScaleOffset(e){return Fa(this.type)?Ha(this,e):e}},Xa=class{constructor(e,t={},r={},i=null){this.definition=e,this.class=t[e.class],this.className=e.class,this.enums=r,this.data=i,this.name="name"in e?e.name:null,this.properties=null}getPropertyNames(){return Object.keys(this.class.properties)}includesData(e){return!!this.definition.properties[e]}dispose(){}_initProperties(e=qa){let t={};for(let r in this.class.properties)t[r]=new e(this.enums,this.class.properties[r],this.definition.properties[r]);this.properties=t}},Ka=class extends qa{constructor(e,t,r=null){super(e,t,r),this.attribute=(null==r?void 0:r.attribute)??null}},Ya=class extends Xa{constructor(...e){super(...e),this.isPropertyAttributeAccessor=!0,this._initProperties(Ka)}getData(e,t,r={}){let i=this.properties;Wa(i,r);for(let s in i)r[s]=this.getPropertyValue(s,e,t,r[s]);return r}getPropertyValue(e,t,r,i=null){if(t>=this.count)throw Error("PropertyAttributeAccessor: Requested index is outside the range of the buffer.");let s=this.properties[e],n=s.type;if(!s)throw Error("PropertyAttributeAccessor: Requested class property does not exist.");if(!this.definition.properties[e])return s.resolveDefault(i);i=s.shapeToProperty(i);let a=r.getAttribute(s.attribute.toLowerCase());if(Da(n)){let e=i.elements;for(let r=e.length;0<r;)e[0]=a.getComponent(t,0)}else if(ka(n))i.fromBufferAttribute(a,t);else{if("SCALAR"!==n&&"ENUM"!==n)throw Error("StructuredMetadata.PropertyAttributeAccessor: BOOLEAN and STRING types are not supported by property attributes.");i=a.getX(t)}return i=s.adjustValueScaleOffset(i),i=s.resolveEnumsToStrings(i),i=s.resolveNoData(i)}},Qa=class extends qa{constructor(e,t,r=null){super(e,t,r),this.values=(null==r?void 0:r.values)??null,this.valueLength=function(e){switch(e){case"ENUM":case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return-1}}(this.type),this.arrayOffsets=Ia(r,"arrayOffsets",null),this.stringOffsets=Ia(r,"stringOffsets",null),this.arrayOffsetType=Ia(r,"arrayOffsetType","UINT32"),this.stringOffsetType=Ia(r,"stringOffsetType","UINT32")}getArrayLengthFromId(e,t){let r=this.count;if(null!==this.arrayOffsets){let{arrayOffsets:i,arrayOffsetType:s}=this,n=new(Va(s))(e[i]);r=n[t+1]-n[t]}return r}getIndexOffsetFromId(e,t){let r=t;if(this.arrayOffsets){let{arrayOffsets:t,arrayOffsetType:i}=this;r=new(Va(i))(e[t])[r]}else this.array&&(r*=this.count);return r}},$a=class extends Xa{constructor(...e){super(...e),this.isPropertyTableAccessor=!0,this.count=this.definition.count,this._initProperties(Qa)}getData(e,t={}){let r=this.properties;Wa(r,t);for(let i in r)t[i]=this.getPropertyValue(i,e,t[i]);return t}_readValueAtIndex(e,t,r,i=null){let s=this.properties[e],{componentType:n,type:a}=s,o=this.data,l=o[s.values],c=new(Va(n,a))(l),h=s.getIndexOffsetFromId(o,t);if(Fa(a)||"ENUM"===a)return Oa(c,(h+r)*s.valueLength,a,i);if("STRING"===a){let e=h+r,t=0;if(null!==s.stringOffsets){let{stringOffsets:r,stringOffsetType:i}=s,n=new(Va(i))(o[r]);t=n[e+1]-n[e],e=n[e]}let n=new Uint8Array(c.buffer,e,t);i=(new TextDecoder).decode(n)}else if("BOOLEAN"===a){let e=h+r,t=e%8;i=1==(c[Math.floor(e/8)]>>t&1)}return i}getPropertyValue(e,t,r=null){if(t>=this.count)throw Error("PropertyTableAccessor: Requested index is outside the range of the table.");let i=this.properties[e];if(!i)throw Error("PropertyTableAccessor: Requested property does not exist.");if(!this.definition.properties[e])return i.resolveDefault(r);let s=i.array,n=this.data,a=i.getArrayLengthFromId(n,t);if(r=i.shapeToProperty(r,a),s)for(let o=0,l=r.length;o<l;o++)r[o]=this._readValueAtIndex(e,t,o,r[o]);else r=this._readValueAtIndex(e,t,0,r);return r=i.adjustValueScaleOffset(r),r=i.resolveEnumsToStrings(r),r=i.resolveNoData(r)}},Za=new i.Box2,Ja=class{constructor(){this._renderer=new i.WebGLRenderer,this._target=new i.WebGLRenderTarget(1,1),this._texTarget=new i.WebGLRenderTarget,this._quad=new gn(new i.ShaderMaterial({blending:i.CustomBlending,blendDst:i.ZeroFactor,blendSrc:i.OneFactor,uniforms:{map:{value:null},pixel:{value:new i.Vector2}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tuniform sampler2D map;\n\t\t\t\tuniform ivec2 pixel;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_FragColor = texelFetch( map, pixel, 0 );\n\n\t\t\t\t}\n\t\t\t"}))}increaseSizeTo(e){this._target.setSize(Math.max(this._target.width,e),1)}readDataAsync(e){let{_renderer:t,_target:r}=this;return t.readRenderTargetPixelsAsync(r,0,0,e.length/4,1,e)}readData(e){let{_renderer:t,_target:r}=this;t.readRenderTargetPixels(r,0,0,e.length/4,1,e)}renderPixelToTarget(e,t,r){let{_renderer:i,_target:s}=this;Za.min.copy(t),Za.max.copy(t),Za.max.x+=1,Za.max.y+=1,i.initRenderTarget(s),i.copyTextureToTexture(e,s.texture,Za,r,0)}},eo=new class{constructor(){let e=null;Object.getOwnPropertyNames(Ja.prototype).forEach((t=>{"constructor"!==t&&(this[t]=(...r)=>(e||(e=new Ja),e[t](...r)))}))}},to=new i.Vector2,ro=new i.Vector2,io=new i.Vector2;function so(e,t,r=[,,,]){let i=3*t,s=3*t+1,n=3*t+2;return e.index&&(i=e.index.getX(i),s=e.index.getX(s),n=e.index.getX(n)),r[0]=i,r[1]=s,r[2]=n,r}function no(e,t,r,i,s){let[n,a,o]=i,l=function(e,t){return 0===t?e.getAttribute("uv"):e.getAttribute(`uv${t}`)}(e,t);to.fromBufferAttribute(l,n),ro.fromBufferAttribute(l,a),io.fromBufferAttribute(l,o),s.set(0,0,0).addScaledVector(to,r.x).addScaledVector(ro,r.y).addScaledVector(io,r.z)}function ao(e,t,r,i){let s=e.x-Math.floor(e.x),n=e.y-Math.floor(e.y),a=Math.floor(s*t%t),o=Math.floor(n*r%r);return i.set(a,o),i}var oo=new i.Vector2,lo=new i.Vector2,co=new i.Vector2,ho=class extends qa{constructor(e,t,r=null){super(e,t,r),this.channels=Ia(r,"channels",[0]),this.index=Ia(r,"index",null),this.texCoord=Ia(r,"texCoord",null),this.valueLength=parseInt(this.type.replace(/[^0-9]/g,""))||1}readDataFromBuffer(e,t,r=null){let i=this.type;if("BOOLEAN"===i||"STRING"===i)throw Error("PropertyTextureAccessor: BOOLEAN and STRING types not supported.");return Oa(e,t*this.valueLength,i,r)}},uo=class extends Xa{constructor(...e){super(...e),this.isPropertyTextureAccessor=!0,this._asyncRead=!1,this._initProperties(ho)}getData(e,t,r,i={}){let s=this.properties;Wa(s,i);let n=Object.keys(s),a=n.map((e=>i[e]));return this.getPropertyValuesAtTexel(n,e,t,r,a),n.forEach(((e,t)=>i[e]=a[t])),i}async getDataAsync(e,t,r,i={}){let s=this.properties;Wa(s,i);let n=Object.keys(s),a=n.map((e=>i[e]));return await this.getPropertyValuesAtTexelAsync(n,e,t,r,a),n.forEach(((e,t)=>i[e]=a[t])),i}getPropertyValuesAtTexelAsync(...e){this._asyncRead=!0;let t=this.getPropertyValuesAtTexel(...e);return this._asyncRead=!1,t}getPropertyValuesAtTexel(e,t,r,i,s=[]){for(;s.length<e.length;)s.push(null);s.length=e.length,eo.increaseSizeTo(s.length);let n=this.data,a=this.definition.properties,o=this.properties,l=so(i,t);for(let u=0,d=e.length;u<d;u++){let t=e[u];if(!a[t])continue;let s=o[t],c=n[s.index];no(i,s.texCoord,r,l,oo),ao(oo,c.image.width,c.image.height,lo),co.set(u,0),eo.renderPixelToTarget(c,lo,co)}let c=new Uint8Array(4*e.length);return this._asyncRead?eo.readDataAsync(c).then((()=>(h.call(this),s))):(eo.readData(c),h.call(this),s);function h(){for(let t=0,r=e.length;t<r;t++){let r=e[t],i=o[r],n=i.type;if(s[t]=ja(i,s[t]),!i)throw Error("PropertyTextureAccessor: Requested property does not exist.");if(!a[r]){s[t]=i.resolveDefault(s);continue}let l=i.valueLength*(i.count||1),h=i.channels.map((e=>c[4*t+e])),u=new(Va(i.componentType,n))(l);if(new Uint8Array(u.buffer).set(h),i.array){let e=s[t];for(let t=0,r=e.length;t<r;t++)e[t]=i.readDataFromBuffer(u,t,e[t])}else s[t]=i.readDataFromBuffer(u,0,s[t]);s[t]=i.adjustValueScaleOffset(s[t]),s[t]=i.resolveEnumsToStrings(s[t]),s[t]=i.resolveNoData(s[t])}}}dispose(){this.data.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},po=class{constructor(e,t,r,i=null,s=null){let{schema:n,propertyTables:a=[],propertyTextures:o=[],propertyAttributes:l=[]}=e,{enums:c,classes:h}=n,u=a.map((e=>new $a(e,h,c,r))),d=[],p=[];i&&(i.propertyTextures&&(d=i.propertyTextures.map((e=>new uo(o[e],h,c,t)))),i.propertyAttributes&&(p=i.propertyAttributes.map((e=>new Ya(l[e],h,c))))),this.schema=n,this.tableAccessors=u,this.textureAccessors=d,this.attributeAccessors=p,this.object=s,this.textures=t,this.nodeMetadata=i}getPropertyTableData(e,t,r=null){if(Array.isArray(e)){r||(r=[]);let i=Math.min(e.length,t.length);r.length=i;for(let s=0;s<i;s++){let i=this.tableAccessors[e[s]];r[s]=i.getData(t[s],r[s])}}else r||(r={}),r=this.tableAccessors[e].getData(t,r);if(Array.isArray(e)!==Array.isArray(r)||Array.isArray(e)!==Array.isArray(t))throw Error("StructuralMetadata: Scalar and array inputs cannot be mixed.");return r}getPropertyTableInfo(e=null){if(null===e&&(e=this.tableAccessors.map(((e,t)=>t))),Array.isArray(e))return e.map((e=>{let t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}));{let t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}}getPropertyTextureData(e,t,r=[]){let i=this.textureAccessors;r.length=i.length;for(let s=0;s<i.length;s++)r[s]=i[s].getData(e,t,this.object.geometry,r[s]);return r}async getPropertyTextureDataAsync(e,t,r=[]){let i=this.textureAccessors;r.length=i.length;let s=[];for(let n=0;n<i.length;n++){let a=i[n].getDataAsync(e,t,this.object.geometry,r[n]).then((e=>{r[n]=e}));s.push(a)}return await Promise.all(s),r}getPropertyTextureInfo(){return this.textureAccessors}getPropertyAttributeData(e,t=[]){let r=this.attributeAccessors;t.length=r.length;for(let i=0;i<r.length;i++)t[i]=r[i].getData(e,this.object.geometry,t[i]);return t}getPropertyAttributeInfo(){return this.attributeAccessors.map((e=>({name:e.name,className:e.definition.class})))}dispose(){this.textureAccessors.forEach((e=>e.dispose())),this.tableAccessors.forEach((e=>e.dispose())),this.attributeAccessors.forEach((e=>e.dispose()))}},mo="EXT_structural_metadata";function fo(e,t=[]){var r;let i=(null==(r=e.json.textures)?void 0:r.length)||0,s=Array(i).fill(null);return t.forEach((({properties:t})=>{for(let r in t){let{index:i}=t[r];null===s[i]&&(s[i]=e.loadTexture(i))}})),Promise.all(s)}function go(e,t=[]){var r;let i=(null==(r=e.json.bufferViews)?void 0:r.length)||0,s=Array(i).fill(null);return t.forEach((({properties:t})=>{for(let r in t){let{values:i,arrayOffsets:n,stringOffsets:a}=t[r];null===s[i]&&(s[i]=e.getDependency("bufferView",i)),null===s[n]&&(s[n]=e.getDependency("bufferView",n)),null===s[a]&&(s[a]=e.getDependency("bufferView",a))}})),Promise.all(s)}var yo=class{constructor(e){this.parser=e,this.name=mo}async afterRoot({scene:e,parser:t}){let r=t.json.extensionsUsed;if(!r||!r.includes(mo))return;let s=null,n=t.json.extensions[mo];if(n.schemaUri){let{manager:e,path:r,requestHeader:a,crossOrigin:o}=t.options,l=new URL(n.schemaUri,r).toString(),c=new i.FileLoader(e);c.setCrossOrigin(o),c.setResponseType("json"),c.setRequestHeader(a),s=c.loadAsync(l).then((e=>{n={...n,schema:e}}))}let[a,o]=await Promise.all([fo(t,n.propertyTextures),go(t,n.propertyTables),s]),l=new po(n,a,o);e.userData.structuralMetadata=l,e.traverse((e=>{var r;if(t.associations.has(e)){let{meshes:i,primitives:s}=t.associations.get(e),c=null==(r=t.json.meshes[i])?void 0:r.primitives[s];if(c&&c.extensions&&c.extensions[mo]){let t=c.extensions[mo];e.userData.structuralMetadata=new po(n,a,o,t,e)}else e.userData.structuralMetadata=l}}))}},vo=new i.Vector2,To=new i.Vector2,xo=new i.Vector2;var bo=class{constructor(e,t,r){this.geometry=e,this.textures=t,this.data=r,this._asyncRead=!1,this.featureIds=r.featureIds.map((e=>{let{texture:t,...r}=e,i={label:null,propertyTable:null,nullFeatureId:null,...r};return t&&(i.texture={texCoord:0,channels:[0],...t}),i}))}getTextures(){return this.textures}getFeatureInfo(){return this.featureIds}getFeaturesAsync(...e){this._asyncRead=!0;let t=this.getFeatures(...e);return this._asyncRead=!1,t}getFeatures(e,t){let{geometry:r,textures:i,featureIds:s}=this,n=Array(s.length).fill(null),a=s.length;eo.increaseSizeTo(a);let o=so(r,e),l=o[function(e){return e.x>e.y&&e.x>e.z?0:e.y>e.z?1:2}(t)];for(let u=0,d=s.length;u<d;u++){let e=s[u],a="nullFeatureId"in e?e.nullFeatureId:null;if("texture"in e){let s=i[e.texture.index];no(r,e.texture.texCoord,t,o,vo),ao(vo,s.image.width,s.image.height,To),xo.set(u,0),eo.renderPixelToTarget(i[e.texture.index],To,xo)}else if("attribute"in e){let t=r.getAttribute(`_feature_id_${e.attribute}`).getX(l);t!==a&&(n[u]=t)}else{let e=l;e!==a&&(n[u]=e)}}let c=new Uint8Array(4*a);return this._asyncRead?eo.readDataAsync(c).then((()=>(h(),n))):(eo.readData(c),h(),n);function h(){let e=new Uint32Array(1);for(let t=0,r=s.length;t<r;t++){let r=s[t],i="nullFeatureId"in r?r.nullFeatureId:null;if("texture"in r){let{channels:s}=r.texture,a=s.map((e=>c[4*t+e]));new Uint8Array(e.buffer).set(a);let o=e[0];o!==i&&(n[t]=o)}}}}dispose(){this.textures.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},_o="EXT_mesh_features";function wo(e,t,r){e.traverse((e=>{var i;if(t.associations.has(e)){let{meshes:s,primitives:n}=t.associations.get(e),a=null==(i=t.json.meshes[s])?void 0:i.primitives[n];a&&a.extensions&&a.extensions[_o]&&r(e,a.extensions[_o])}}))}var Mo=class{constructor(e){this.parser=e,this.name=_o}async afterRoot({scene:e,parser:t}){var r;let i=t.json.extensionsUsed;if(!i||!i.includes(_o))return;let s=(null==(r=t.json.textures)?void 0:r.length)||0,n=Array(s).fill(null);wo(e,t,((e,{featureIds:r})=>{r.forEach((e=>{if(e.texture&&null===n[e.texture.index]){let r=e.texture.index;n[r]=t.loadTexture(r)}}))}));let a=await Promise.all(n);wo(e,t,((e,t)=>{e.userData.meshFeatures=new bo(e.geometry,a,t)}))}},So=class{constructor(){this.name="CESIUM_RTC"}afterRoot(e){if(e.parser.json.extensions&&e.parser.json.extensions.CESIUM_RTC){let{center:t}=e.parser.json.extensions.CESIUM_RTC;t&&(e.scene.position.x+=t[0],e.scene.position.y+=t[1],e.scene.position.z+=t[2])}}},Ao=class{constructor(e){e={metadata:!0,rtc:!0,plugins:[],dracoLoader:null,ktxLoader:null,meshoptDecoder:null,autoDispose:!0,...e},this.tiles=null,this.metadata=e.metadata,this.rtc=e.rtc,this.plugins=e.plugins,this.dracoLoader=e.dracoLoader,this.ktxLoader=e.ktxLoader,this.meshoptDecoder=e.meshoptDecoder,this._gltfRegex=/\.(gltf|glb)$/g,this._dracoRegex=/\.drc$/g,this._loader=null}init(e){let t=new Je(e.manager);this.dracoLoader&&(t.setDRACOLoader(this.dracoLoader),e.manager.addHandler(this._dracoRegex,this.dracoLoader)),this.ktxLoader&&t.setKTX2Loader(this.ktxLoader),this.meshoptDecoder&&t.setMeshoptDecoder(this.meshoptDecoder),this.rtc&&t.register((()=>new So)),this.metadata&&(t.register((()=>new yo)),t.register((()=>new Mo))),this.plugins.forEach((e=>t.register(e))),e.manager.addHandler(this._gltfRegex,t),this.tiles=e,this._loader=t}dispose(){this.tiles.manager.removeHandler(this._gltfRegex),this.tiles.manager.removeHandler(this._dracoRegex),this.autoDispose&&(this.ktxLoader.dispose(),this.dracoLoader.dispose())}},Co=class{set delay(e){this.deferCallbacks.delay=e}get delay(){return this.deferCallbacks.delay}set bytesTarget(e){this.lruCache.minBytesSize=e}get bytesTarget(){return this.lruCache.minBytesSize}get estimatedGpuBytes(){return this.lruCache.cachedBytes}constructor(e={}){let{delay:t=0,bytesTarget:r=0}=e;this.name="UNLOAD_TILES_PLUGIN",this.tiles=null,this.lruCache=new oe,this.deferCallbacks=new Eo,this.delay=t,this.bytesTarget=r}init(e){this.tiles=e;let{lruCache:t,deferCallbacks:r}=this,i=t=>{let r=t.engineData.scene;e.visibleTiles.has(t)||e.invokeOnePlugin((e=>e.unloadTileFromGPU&&e.unloadTileFromGPU(r,t)))};this._onUpdateBefore=()=>{t.unloadPriorityCallback=e.lruCache.unloadPriorityCallback,t.minSize=1/0,t.maxSize=1/0,t.maxBytesSize=1/0,t.unloadPercent=1,t.autoMarkUnused=!1},this._onVisibilityChangeCallback=({tile:s,scene:n,visible:a})=>{a?(t.add(s,i),t.setMemoryUsage(s,e.calculateBytesUsed(s,n)||1),e.markTileUsed(s),r.cancel(s)):r.run(s)},this._onDisposeModel=({tile:e})=>{t.remove(e),r.cancel(e)},r.callback=e=>{t.markUnused(e),t.scheduleUnload()},e.forEachLoadedModel(((t,r)=>{let i=e.visibleTiles.has(r);this._onVisibilityChangeCallback({tile:r,visible:i})})),e.addEventListener("tile-visibility-change",this._onVisibilityChangeCallback),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("dispose-model",this._onDisposeModel)}unloadTileFromGPU(e,t){e&&e.traverse((e=>{if(e.material){let t=e.material;t.dispose();for(let e in t){let r=t[e];r&&r.isTexture&&r.dispose()}}e.geometry&&e.geometry.dispose()}))}dispose(){let{lruCache:e,tiles:t,deferCallbacks:r}=this;t.removeEventListener("tile-visibility-change",this._onVisibilityChangeCallback),t.removeEventListener("update-before",this._onUpdateBefore),t.removeEventListener("dispose-model",this._onDisposeModel),r.cancelAll(),e.minBytesSize=0,e.minSize=0,e.maxSize=0,e.markAllUnused(),e.scheduleUnload()}},Eo=class{constructor(e=()=>{}){this.map=new Map,this.callback=e,this.delay=0}run(e){let{map:t,delay:r}=this;if(t.has(e))throw Error("DeferCallbackManager: Callback already initialized.");0===r?this.callback(e):t.set(e,setTimeout((()=>{this.callback(e),t.delete(e)}),r))}cancel(e){let{map:t}=this;t.has(e)&&(clearTimeout(t.get(e)),t.delete(e))}cancelAll(){this.map.forEach(((e,t)=>{this.cancel(t)}))}},{clamp:Ro}=i.MathUtils,Po=class{constructor(){this.duration=250,this.fadeCount=0,this._lastTick=-1,this._fadeState=new Map,this.onFadeComplete=null,this.onFadeStart=null,this.onFadeSetComplete=null,this.onFadeSetStart=null}deleteObject(e){e&&this.completeFade(e)}guaranteeState(e){let t=this._fadeState;return!t.has(e)&&(t.set(e,{fadeInTarget:0,fadeOutTarget:0,fadeIn:0,fadeOut:0}),!0)}completeFade(e){let t=this._fadeState;if(!t.has(e))return;let r=0===t.get(e).fadeOutTarget;t.delete(e),this.fadeCount--,this.onFadeComplete&&this.onFadeComplete(e,r),0===this.fadeCount&&this.onFadeSetComplete&&this.onFadeSetComplete()}completeAllFades(){this._fadeState.forEach(((e,t)=>{this.completeFade(t)}))}forEachObject(e){this._fadeState.forEach(((t,r)=>{e(r,t)}))}fadeIn(e){let t=this.guaranteeState(e),r=this._fadeState.get(e);r.fadeInTarget=1,r.fadeOutTarget=0,r.fadeOut=0,t&&(this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}fadeOut(e){let t=this.guaranteeState(e),r=this._fadeState.get(e);r.fadeOutTarget=1,t&&(r.fadeInTarget=1,r.fadeIn=1,this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}isFading(e){return this._fadeState.has(e)}isFadingOut(e){let t=this._fadeState.get(e);return t&&1===t.fadeOutTarget}update(){let e=window.performance.now();-1===this._lastTick&&(this._lastTick=e);let t=Ro((e-this._lastTick)/this.duration,0,1);this._lastTick=e,this._fadeState.forEach(((e,r)=>{let{fadeOutTarget:i,fadeInTarget:s}=e,{fadeOut:n,fadeIn:a}=e,o=Math.sign(s-a);a=Ro(a+o*t,0,1);let l=Math.sign(i-n);n=Ro(n+l*t,0,1),e.fadeIn=a,e.fadeOut=n,((1===n||0===n)&&(1===a||0===a)||n>=a)&&this.completeFade(r)}))}},Lo=Symbol("FADE_PARAMS");function Uo(e,t){if(e[Lo])return e[Lo];let r={fadeIn:{value:0},fadeOut:{value:0},fadeTexture:{value:null}};return e[Lo]=r,e.defines={...e.defines||{},FEATURE_FADE:0},e.onBeforeCompile=e=>{t&&t(e),e.uniforms={...e.uniforms,...r},e.vertexShader=e.vertexShader.replace(/void\s+main\(\)\s+{/,(e=>`\n\t\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t\tvarying float vBatchId;\n\n\t\t\t\t\t#endif\n\n\t\t\t\t\t${e}\n\n\t\t\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t\t\t// add 0.5 to the value to avoid floating error that may cause flickering\n\t\t\t\t\t\tvBatchId = getIndirectIndex( gl_DrawID ) + 0.5;\n\n\t\t\t\t\t\t#endif\n\t\t\t\t`)),e.fragmentShader=e.fragmentShader.replace(/void main\(/,(e=>`\n\t\t\t\t#if FEATURE_FADE\n\n\t\t\t\t// adapted from https://www.shadertoy.com/view/Mlt3z8\n\t\t\t\tfloat bayerDither2x2( vec2 v ) {\n\n\t\t\t\t\treturn mod( 3.0 * v.y + 2.0 * v.x, 4.0 );\n\n\t\t\t\t}\n\n\t\t\t\tfloat bayerDither4x4( vec2 v ) {\n\n\t\t\t\t\tvec2 P1 = mod( v, 2.0 );\n\t\t\t\t\tvec2 P2 = floor( 0.5 * mod( v, 4.0 ) );\n\t\t\t\t\treturn 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 );\n\n\t\t\t\t}\n\n\t\t\t\t// the USE_BATCHING define is not available in fragment shaders\n\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\t// functions for reading the fade state of a given batch id\n\t\t\t\tuniform sampler2D fadeTexture;\n\t\t\t\tvarying float vBatchId;\n\t\t\t\tvec2 getFadeValues( const in float i ) {\n\n\t\t\t\t\tint size = textureSize( fadeTexture, 0 ).x;\n\t\t\t\t\tint j = int( i );\n\t\t\t\t\tint x = j % size;\n\t\t\t\t\tint y = j / size;\n\t\t\t\t\treturn texelFetch( fadeTexture, ivec2( x, y ), 0 ).rg;\n\n\t\t\t\t}\n\n\t\t\t\t#else\n\n\t\t\t\tuniform float fadeIn;\n\t\t\t\tuniform float fadeOut;\n\n\t\t\t\t#endif\n\n\t\t\t\t#endif\n\n\t\t\t\t${e}\n\t\t\t`)).replace(/#include <dithering_fragment>/,(e=>`\n\n\t\t\t\t${e}\n\n\t\t\t\t#if FEATURE_FADE\n\n\t\t\t\t#ifdef USE_BATCHING_FRAG\n\n\t\t\t\tvec2 fadeValues = getFadeValues( vBatchId );\n\t\t\t\tfloat fadeIn = fadeValues.r;\n\t\t\t\tfloat fadeOut = fadeValues.g;\n\n\t\t\t\t#endif\n\n\t\t\t\tfloat bayerValue = bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) );\n\t\t\t\tfloat bayerBins = 16.0;\n\t\t\t\tfloat dither = ( 0.5 + bayerValue ) / bayerBins;\n\t\t\t\tif ( dither >= fadeIn ) {\n\n\t\t\t\t\tdiscard;\n\n\t\t\t\t}\n\n\t\t\t\tif ( dither < fadeOut ) {\n\n\t\t\t\t\tdiscard;\n\n\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t`))},r}var Io=class{constructor(){this._fadeParams=new WeakMap,this.fading=0}setFade(e,t,r){if(!e)return;let i=this._fadeParams;e.traverse((e=>{let s=e.material;if(s&&i.has(s)){let e=i.get(s);e.fadeIn.value=t,e.fadeOut.value=r;let n=Number(!(0===t||1===t)||!(0===r||1===r));s.defines.FEATURE_FADE!==n&&(this.fading+=1===n?1:-1,s.defines.FEATURE_FADE=n,s.needsUpdate=!0)}}))}prepareScene(e){e.traverse((e=>{e.material&&this.prepareMaterial(e.material)}))}deleteScene(e){if(!e)return;this.setFade(e,1,0);let t=this._fadeParams;e.traverse((e=>{let r=e.material;r&&t.delete(r)}))}prepareMaterial(e){let t=this._fadeParams;t.has(e)||t.set(e,Uo(e,e.onBeforeCompile))}},Fo=class{constructor(e,t=new i.MeshBasicMaterial){this.other=e,this.material=t,this.visible=!0,this.parent=null,this._instanceInfo=[],this._visibilityChanged=!0;let r=new Proxy(this,{get(t,i){if(i in t)return t[i];{let s=e[i];return s instanceof Function?(...e)=>(t.syncInstances(),s.call(r,...e)):e[i]}},set:(t,r,i)=>(r in t?t[r]=i:e[r]=i,!0),deleteProperty:(t,r)=>r in t?delete t[r]:delete e[r]});return r}syncInstances(){let e=this._instanceInfo,t=this.other._instanceInfo;for(;t.length>e.length;){let r=e.length;e.push(new Proxy({visible:!1},{get:(e,i)=>i in e?e[i]:t[r][i],set:(e,i,s)=>(i in e?e[i]=s:t[r][i]=s,!0)}))}}},ko=class extends Fo{constructor(...e){super(...e);let t=this.material,r=Uo(t,t.onBeforeCompile);t.defines.FEATURE_FADE=1,t.defines.USE_BATCHING_FRAG=1,t.needsUpdate=!0,this.fadeTexture=null,this._fadeParams=r}setFadeAt(e,t,r){this._initFadeTexture(),this.fadeTexture.setValueAt(e,255*t,255*r)}_initFadeTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=e*e*2,r=this.fadeTexture;if(!r||r.image.data.length!==t){let s=new Do(new Uint8Array(t),e,e,i.RGFormat,i.UnsignedByteType);if(r){r.dispose();let e=r.image.data,t=this.fadeTexture.image.data,i=Math.min(e.length,t.length);t.set(new e.constructor(e.buffer,0,i))}this.fadeTexture=s,this._fadeParams.fadeTexture.value=s,s.needsUpdate=!0}}dispose(){this.fadeTexture&&this.fadeTexture.dispose()}},Do=class extends i.DataTexture{setValueAt(e,...t){let{data:r,width:i,height:s}=this.image,n=Math.floor(r.length/(i*s)),a=!1;for(let o=0;o<n;o++){let i=e*n+o,s=r[i],l=t[o]||0;s!==l&&(r[i]=l,a=!0)}a&&(this.needsUpdate=!0)}},Oo=Symbol("HAS_POPPED_IN");var Bo=new i.Vector3,No=new i.Vector3,Vo=new i.Quaternion,zo=new i.Quaternion,Go=new i.Vector3;function Ho(){let e=this._fadeManager,t=this._fadeMaterialManager,r=this._fadingBefore,i=this._prevCameraTransforms,{tiles:s,maximumFadeOutTiles:n,batchedMesh:a}=this,{cameras:o}=s;e.update();let l=e.fadeCount;if(0!==r&&0!==l&&(s.dispatchEvent({type:"fade-change"}),s.dispatchEvent({type:"needs-render"})),n<this._fadingOutCount){let t=!0;o.forEach((e=>{if(!i.has(e))return;let r=e.matrixWorld,s=i.get(e);r.decompose(No,zo,Go),s.decompose(Bo,Vo,Go);let n=zo.angleTo(Vo),a=No.distanceTo(Bo);t&&(t=n>.25||a>.1)})),t&&e.completeAllFades()}if(o.forEach((e=>{i.get(e).copy(e.matrixWorld)})),e.forEachObject(((e,{fadeIn:r,fadeOut:i})=>{let n=e.engineData.scene;s.markTileUsed(e),n&&t.setFade(n,r,i),this.forEachBatchIds(e,((e,t,s)=>{t.setFadeAt(e,r,i),t.setVisibleAt(e,!0),s.batchedMesh.setVisibleAt(e,!1)}))})),a){let e=s.getPluginByName("BATCHED_TILES_PLUGIN").batchedMesh.material;a.material.map=e.map}}var jo=class{get fadeDuration(){return this._fadeManager.duration}set fadeDuration(e){this._fadeManager.duration=Number(e)}get fadingTiles(){return this._fadeManager.fadeCount}constructor(e){e={maximumFadeOutTiles:50,fadeRootTiles:!1,fadeDuration:250,...e},this.name="FADE_TILES_PLUGIN",this.priority=-2,this.tiles=null,this.batchedMesh=null,this._quickFadeTiles=new Set,this._fadeManager=new Po,this._fadeMaterialManager=new Io,this._prevCameraTransforms=null,this._fadingOutCount=0,this.maximumFadeOutTiles=e.maximumFadeOutTiles,this.fadeRootTiles=e.fadeRootTiles,this.fadeDuration=e.fadeDuration}init(e){this._onLoadModel=({scene:e})=>{this._fadeMaterialManager.prepareScene(e)},this._onDisposeModel=({tile:e,scene:t})=>{this.tiles.visibleTiles.has(e)&&this._quickFadeTiles.add(e.parent),this._fadeManager.deleteObject(e),this._fadeMaterialManager.deleteScene(t)},this._onAddCamera=({camera:e})=>{this._prevCameraTransforms.set(e,new i.Matrix4)},this._onDeleteCamera=({camera:e})=>{this._prevCameraTransforms.delete(e)},this._onTileVisibilityChange=({tile:e})=>{this.forEachBatchIds(e,((e,t,r)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),r.batchedMesh.setVisibleAt(e,!1)}))},this._onUpdateBefore=()=>{this._fadingBefore=this._fadeManager.fadeCount},this._onUpdateAfter=()=>{Ho.call(this)},e.addEventListener("load-model",this._onLoadModel),e.addEventListener("dispose-model",this._onDisposeModel),e.addEventListener("add-camera",this._onAddCamera),e.addEventListener("delete-camera",this._onDeleteCamera),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("update-after",this._onUpdateAfter),e.addEventListener("tile-visibility-change",this._onTileVisibilityChange);let t=this._fadeManager;t.onFadeSetStart=()=>{e.dispatchEvent({type:"fade-start"}),e.dispatchEvent({type:"needs-render"})},t.onFadeSetComplete=()=>{e.dispatchEvent({type:"fade-end"}),e.dispatchEvent({type:"needs-render"})},t.onFadeComplete=(t,r)=>{this._fadeMaterialManager.setFade(t.engineData.scene,0,0),this.forEachBatchIds(t,((e,t,i)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),i.batchedMesh.setVisibleAt(e,r)})),r||(e.invokeOnePlugin((e=>e!==this&&e.setTileVisible&&e.setTileVisible(t,!1))),this._fadingOutCount--)};let r=new Map;e.cameras.forEach((e=>{r.set(e,new i.Matrix4)})),e.forEachLoadedModel(((e,t)=>{this._onLoadModel({scene:e})})),this.tiles=e,this._fadeManager=t,this._prevCameraTransforms=r}initBatchedMesh(){var e;let t=null==(e=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"))?void 0:e.batchedMesh;if(t){if(null===this.batchedMesh){this._onBatchedMeshDispose=()=>{this.batchedMesh.dispose(),this.batchedMesh.removeFromParent(),this.batchedMesh=null,t.removeEventListener("dispose",this._onBatchedMeshDispose)};let e=t.material.clone();e.onBeforeCompile=t.material.onBeforeCompile,this.batchedMesh=new ko(t,e),this.tiles.group.add(this.batchedMesh)}}else null!==this.batchedMesh&&(this._onBatchedMeshDispose(),this._onBatchedMeshDispose=null)}setTileVisible(e,t){let r=this._fadeManager,i=r.isFading(e);if(!function(e){let t=e;for(;t;){if(t.traversal.wasSetActive)return t.traversal.wasInFrustum;t=t.parent}return!1}(e))return i&&r.completeFade(e),!1;if(r.isFadingOut(e)&&this._fadingOutCount--,t?1===e.internal.depthFromRenderedParent?((e[Oo]||this.fadeRootTiles)&&this._fadeManager.fadeIn(e),e[Oo]=!0):this._fadeManager.fadeIn(e):(this._fadingOutCount++,r.fadeOut(e)),this._quickFadeTiles.has(e)&&(this._fadeManager.completeFade(e),this._quickFadeTiles.delete(e)),i)return!0;let s=this._fadeManager.isFading(e);return!(t||!s)}dispose(){let e=this.tiles;this._fadeManager.completeAllFades(),null!==this.batchedMesh&&this._onBatchedMeshDispose(),e.removeEventListener("load-model",this._onLoadModel),e.removeEventListener("dispose-model",this._onDisposeModel),e.removeEventListener("add-camera",this._onAddCamera),e.removeEventListener("delete-camera",this._onDeleteCamera),e.removeEventListener("update-before",this._onUpdateBefore),e.removeEventListener("update-after",this._onUpdateAfter),e.removeEventListener("tile-visibility-change",this._onTileVisibilityChange),e.forEachLoadedModel(((e,t)=>{this._fadeManager.deleteObject(t)}))}forEachBatchIds(e,t){if(this.initBatchedMesh(),this.batchedMesh){let r=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"),i=r.getTileBatchIds(e);i&&i.forEach((e=>{t(e,this.batchedMesh,r)}))}}};new gn(new i.MeshBasicMaterial),new i.DataTexture(new Uint8Array([255,255,255,255]),1,1).needsUpdate=!0;const Wo="#include <opaque_fragment>",qo=`\n float grayscale = dot(outgoingLight, vec3(0.299, 0.587, 0.114));\n outgoingLight = vec3(grayscale);\n ${Wo}\n`;function Xo(e){const t=e.onBeforeCompile;e.onBeforeCompile=r=>{t.call(e,r),r.fragmentShader=r.fragmentShader.replace(Wo,qo)},e.needsUpdate=!0}class Ko extends p{constructor(e,t,r,i={}){super(),this.scene=e,this.camera=t,this.renderer=r,this.tiles=null,this.dracoLoader=null,this.ownsDecoders=!i.decoders,this.decoders=i.decoders??new Qs(r),this.apiToken=i.apiToken,this.googleMapsToken=i.googleMapsToken,this.googleMapsToken&&this.initTiles()}initTiles(){this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),this.dracoLoader=this.decoders.getDraco(),this.tiles=new vi,this.tiles.errorTarget=40,this.tiles.registerPlugin(new rn({apiToken:this.googleMapsToken,autoRefreshToken:!0})),this.tiles.registerPlugin(new Ua),this.tiles.registerPlugin(new Ra),this.tiles.registerPlugin(new Co),this.tiles.registerPlugin(new jo),this.tiles.registerPlugin(new Ao({dracoLoader:this.dracoLoader,autoDispose:!1})),this.scene.add(this.tiles.group),this.tiles.setResolutionFromRenderer(this.camera,this.renderer),this.tiles.setCamera(this.camera),this.tiles.addEventListener("load-model",(({scene:e})=>{e.traverse((e=>{Array.isArray(e.material)?e.material.forEach(Xo):e.material&&Xo(e.material),e.layers.set(0)}))}))}update(){this.tiles&&(this.tiles.setResolutionFromRenderer(this.camera,this.renderer),this.tiles.setCamera(this.camera),this.tiles.errorTarget=20,this.tiles.update())}dispose(){this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),this.ownsDecoders&&this.decoders.dispose(),this.listeners={}}}var Yo=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-Yo.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*Yo.Bounce.In(2*e):.5*Yo.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),Qo=function(){return performance.now()},$o=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map((function(t){return e._tweens[t]}))},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];for(var i=0,s=t;i<s.length;i++){var n=s[i];null===(e=n._group)||void 0===e||e.remove(n),n._group=this,this._tweens[n.getId()]=n,this._tweensAddedDuringUpdate[n.getId()]=n}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var r=0,i=e;r<i.length;r++){var s=i[r];s._group=void 0,delete this._tweens[s.getId()],delete this._tweensAddedDuringUpdate[s.getId()]}},e.prototype.allStopped=function(){return this.getAll().every((function(e){return!e.isPlaying()}))},e.prototype.update=function(e,t){void 0===e&&(e=Qo()),void 0===t&&(t=!0);var r=Object.keys(this._tweens);if(0!==r.length)for(;r.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<r.length;i++){var s=this._tweens[r[i]],n=!t;s&&!1===s.update(e,n)&&!t&&this.remove(s)}r=Object.keys(this._tweensAddedDuringUpdate)}},e}(),Zo={Linear:function(e,t){var r=e.length-1,i=r*t,s=Math.floor(i),n=Zo.Utils.Linear;return t<0?n(e[0],e[1],i):t>1?n(e[r],e[r-1],r-i):n(e[s],e[s+1>r?r:s+1],i-s)},Utils:{Linear:function(e,t,r){return(t-e)*r+e}}},Jo=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),el=new $o,tl=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=Yo.Linear.None,this._interpolationFunction=Zo.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Jo.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=el,el.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=Qo()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var r in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var s in this._valuesEnd)i[s]=this._valuesEnd[s];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,r,i,s){for(var n in r){var a=e[n],o=Array.isArray(a),l=o?"array":typeof a,c=!o&&Array.isArray(r[n]);if("undefined"!==l&&"function"!==l){if(c){if(0===(g=r[n]).length)continue;for(var h=[a],u=0,d=g.length;u<d;u+=1){var p=this._handleRelativeValue(a,g[u]);if(isNaN(p)){c=!1;break}h.push(p)}c&&(r[n]=h)}if("object"!==l&&!o||!a||c)(void 0===t[n]||s)&&(t[n]=a),o||(t[n]*=1),i[n]=c?r[n].slice().reverse():t[n]||0;else{t[n]=o?[]:{};var m=a;for(var f in m)t[n][f]=m[f];i[n]=o?[]:{};var g=r[n];if(!this._isDynamic){var y={};for(var f in g)y[f]=g[f];r[n]=g=y}this._setupProperties(m,t[n],g,i[n],s)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=Qo()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=Qo()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):this},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=Yo.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=Zo.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,r){var i,s,n=this;if(void 0===t&&(t=Qo()),void 0===r&&(r=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!r)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),l=this._duration+this._repeat*o,c=function(){if(0===n._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,r=Math.min(t/n._duration,1);return 0===r&&a===n._duration?1:r}(),h=this._easingFunction(c);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,h),this._onUpdateCallback&&this._onUpdateCallback(this._object,c),0===this._duration||a>=this._duration){if(this._repeat>0){var u=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(s in isFinite(this._repeat)&&(this._repeat-=u),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[s]||(this._valuesStartRepeat[s]=this._valuesStartRepeat[s]+parseFloat(this._valuesEnd[s])),this._yoyo&&this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*u,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,r,i){for(var s in r)if(void 0!==t[s]){var n=t[s]||0,a=r[s],o=Array.isArray(e[s]),l=Array.isArray(a);!o&&l?e[s]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[s],n,a,i):"number"==typeof(a=this._handleRelativeValue(n,a))&&(e[s]=n+(a-n)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],r=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof r?this._valuesStartRepeat[e]+parseFloat(r):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();Jo.nextId;var rl=el;rl.getAll.bind(rl),rl.removeAll.bind(rl),rl.add.bind(rl),rl.remove.bind(rl),rl.update.bind(rl);const il={CESIUM:void 0,GOOGLEMAPS:void 0},sl=2e3;({Easing:Yo}).Easing.Quartic.InOut;class nl extends i.DataTextureLoader{constructor(e){super(e),this.type=i.HalfFloatType}parse(e){const t=function(e,t){switch(e){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(t||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(t||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(t||""));default:throw new Error("THREE.HDRLoader: Memory Error: "+(t||""))}},r=function(e,t,r){t=t||1024;let i=e.pos,s=-1,n=0,a="",o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(i,i+128)));for(;0>(s=o.indexOf("\n"))&&n<t&&i<e.byteLength;)a+=o,n+=o.length,i+=128,o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(i,i+128)));return-1<s&&(e.pos+=n+s+1,a+o.slice(0,s))},s=function(e,t,r,i){const s=e[t+3],n=Math.pow(2,s-128)/255;r[i+0]=e[t+0]*n,r[i+1]=e[t+1]*n,r[i+2]=e[t+2]*n,r[i+3]=1},n=function(e,t,r,s){const n=e[t+3],a=Math.pow(2,n-128)/255;r[s+0]=i.DataUtils.toHalfFloat(Math.min(e[t+0]*a,65504)),r[s+1]=i.DataUtils.toHalfFloat(Math.min(e[t+1]*a,65504)),r[s+2]=i.DataUtils.toHalfFloat(Math.min(e[t+2]*a,65504)),r[s+3]=i.DataUtils.toHalfFloat(1)},a=new Uint8Array(e);a.pos=0;const o=function(e){const i=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,s=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,n=/^\s*FORMAT=(\S+)\s*$/,a=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,o={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let l,c;for((e.pos>=e.byteLength||!(l=r(e)))&&t(1,"no header found"),(c=l.match(/^#\?(\S+)/))||t(3,"bad initial token"),o.valid|=1,o.programtype=c[1],o.string+=l+"\n";l=r(e),!1!==l;)if(o.string+=l+"\n","#"!==l.charAt(0)){if((c=l.match(i))&&(o.gamma=parseFloat(c[1])),(c=l.match(s))&&(o.exposure=parseFloat(c[1])),(c=l.match(n))&&(o.valid|=2,o.format=c[1]),(c=l.match(a))&&(o.valid|=4,o.height=parseInt(c[1],10),o.width=parseInt(c[2],10)),2&o.valid&&4&o.valid)break}else o.comments+=l+"\n";return 2&o.valid||t(3,"missing format specifier"),4&o.valid||t(3,"missing image size specifier"),o}(a),l=o.width,c=o.height,h=function(e,r,i){const s=r;if(s<8||s>32767||2!==e[0]||2!==e[1]||128&e[2])return new Uint8Array(e);s!==(e[2]<<8|e[3])&&t(3,"wrong scanline width");const n=new Uint8Array(4*r*i);n.length||t(4,"unable to allocate buffer space");let a=0,o=0;const l=4*s,c=new Uint8Array(4),h=new Uint8Array(l);let u=i;for(;u>0&&o<e.byteLength;){o+4>e.byteLength&&t(1),c[0]=e[o++],c[1]=e[o++],c[2]=e[o++],c[3]=e[o++],2==c[0]&&2==c[1]&&(c[2]<<8|c[3])==s||t(3,"bad rgbe scanline format");let r,i=0;for(;i<l&&o<e.byteLength;){r=e[o++];const s=r>128;if(s&&(r-=128),(0===r||i+r>l)&&t(3,"bad scanline data"),s){const t=e[o++];for(let e=0;e<r;e++)h[i++]=t}else h.set(e.subarray(o,o+r),i),i+=r,o+=r}const d=s;for(let e=0;e<d;e++){let t=0;n[a]=h[e+t],t+=s,n[a+1]=h[e+t],t+=s,n[a+2]=h[e+t],t+=s,n[a+3]=h[e+t],a+=4}u--}return n}(a.subarray(a.pos),l,c);let u,d,p;switch(this.type){case i.FloatType:p=h.length/4;const e=new Float32Array(4*p);for(let r=0;r<p;r++)s(h,4*r,e,4*r);u=e,d=i.FloatType;break;case i.HalfFloatType:p=h.length/4;const t=new Uint16Array(4*p);for(let r=0;r<p;r++)n(h,4*r,t,4*r);u=t,d=i.HalfFloatType;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:l,height:c,data:u,header:o.string,gamma:o.gamma,exposure:o.exposure,type:d,colorSpace:i.LinearSRGBColorSpace,minFilter:i.LinearFilter,magFilter:i.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}class al extends nl{constructor(e){super(e)}}function ol(e,t={}){return new Promise(((r,s)=>{const n=new al;n.setDataType(t.floatType||i.HalfFloatType),n.load(e,(e=>{r(e)}),(e=>{}),(e=>{s(e)}))}))}var ll,cl,hl={exports:{}};ll||(ll=1,hl.exports=((cl=function(){function e(e){return i.appendChild(e.dom),e}function t(e){for(var t=0;t<i.children.length;t++)i.children[t].style.display=t===e?"block":"none";r=e}var r=0,i=document.createElement("div");i.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",i.addEventListener("click",(function(e){e.preventDefault(),t(++r%i.children.length)}),!1);var s=(performance||Date).now(),n=s,a=0,o=e(new cl.Panel("FPS","#0ff","#002")),l=e(new cl.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var c=e(new cl.Panel("MB","#f08","#201"));return t(0),{REVISION:16,dom:i,addPanel:e,showPanel:t,begin:function(){s=(performance||Date).now()},end:function(){a++;var e=(performance||Date).now();if(l.update(e-s,200),e>n+1e3&&(o.update(1e3*a/(e-n),100),n=e,a=0,c)){var t=performance.memory;c.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return e},update:function(){s=this.end()},domElement:i,setMode:t}}).Panel=function(e,t,r){var i=1/0,s=0,n=Math.round,a=n(window.devicePixelRatio||1),o=80*a,l=48*a,c=3*a,h=2*a,u=3*a,d=15*a,p=74*a,m=30*a,f=document.createElement("canvas");f.width=o,f.height=l,f.style.cssText="width:80px;height:48px";var g=f.getContext("2d");return g.font="bold "+9*a+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=r,g.fillRect(0,0,o,l),g.fillStyle=t,g.fillText(e,c,h),g.fillRect(u,d,p,m),g.fillStyle=r,g.globalAlpha=.9,g.fillRect(u,d,p,m),{dom:f,update:function(l,y){i=Math.min(i,l),s=Math.max(s,l),g.fillStyle=r,g.globalAlpha=1,g.fillRect(0,0,o,d),g.fillStyle=t,g.fillText(n(l)+" "+e+" ("+n(i)+"-"+n(s)+")",c,h),g.drawImage(f,u+a,d,p-a,m,u,d,p-a,m),g.fillRect(u+p-a,d,a,m),g.fillStyle=r,g.globalAlpha=.9,g.fillRect(u+p-a,d,a,n((1-l/y)*m))}}},cl));const ul={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class dl{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register((function(e){return new Wl(e)})),this.register((function(e){return new ql(e)})),this.register((function(e){return new Ql(e)})),this.register((function(e){return new $l(e)})),this.register((function(e){return new Zl(e)})),this.register((function(e){return new Jl(e)})),this.register((function(e){return new Xl(e)})),this.register((function(e){return new Kl(e)})),this.register((function(e){return new Yl(e)})),this.register((function(e){return new ec(e)})),this.register((function(e){return new tc(e)})),this.register((function(e){return new rc(e)})),this.register((function(e){return new ic(e)})),this.register((function(e){return new sc(e)}))}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}setTextureUtils(e){return this.textureUtils=e,this}parse(e,t,r,i){const s=new jl,n=[];for(let a=0,o=this.pluginCallbacks.length;a<o;a++)n.push(this.pluginCallbacks[a](s));s.setPlugins(n),s.setTextureUtils(this.textureUtils),s.writeAsync(e,t,i).catch(r)}parseAsync(e,t){const r=this;return new Promise((function(i,s){r.parse(e,i,s,t)}))}}const pl=0,ml=1,fl=2,gl=3,yl=4,vl=5120,Tl=5121,xl=5122,bl=5123,_l=5124,wl=5125,Ml=5126,Sl=34962,Al=34963,Cl=9728,El=9729,Rl=9984,Pl=9985,Ll=9986,Ul=9987,Il=33071,Fl=33648,kl=10497,Dl="KHR_mesh_quantization",Ol={};Ol[i.NearestFilter]=Cl,Ol[i.NearestMipmapNearestFilter]=Rl,Ol[i.NearestMipmapLinearFilter]=Ll,Ol[i.LinearFilter]=El,Ol[i.LinearMipmapNearestFilter]=Pl,Ol[i.LinearMipmapLinearFilter]=Ul,Ol[i.ClampToEdgeWrapping]=Il,Ol[i.RepeatWrapping]=kl,Ol[i.MirroredRepeatWrapping]=Fl;const Bl={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},Nl=new i.Color;function Vl(e,t){return e.length===t.length&&e.every((function(e,r){return e===t[r]}))}function zl(e){return 4*Math.ceil(e/4)}function Gl(e,t=0){const r=zl(e.byteLength);if(r!==e.byteLength){const i=new Uint8Array(r);if(i.set(new Uint8Array(e)),0!==t)for(let s=e.byteLength;s<r;s++)i[s]=t;return i.buffer}return e}function Hl(){return"undefined"==typeof document&&"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")}class jl{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+i.REVISION}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map,normalMaps:new Map},this.textureUtils=null}setPlugins(e){this.plugins=e}setTextureUtils(e){this.textureUtils=e}async writeAsync(e,t,r={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1,copyright:null},r),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);const i=this,s=i.buffers,n=i.json;r=i.options;const a=i.extensionsUsed,o=i.extensionsRequired,l=new Blob(s,{type:"application/octet-stream"}),c=Object.keys(a),h=Object.keys(o);if(c.length>0&&(n.extensionsUsed=c),h.length>0&&(n.extensionsRequired=h),n.buffers&&n.buffers.length>0&&(n.buffers[0].byteLength=l.size),r.copyright&&(n.asset.copyright=r.copyright),!0===r.binary){const e=new FileReader;e.readAsArrayBuffer(l),e.onloadend=function(){const r=Gl(e.result),i=new DataView(new ArrayBuffer(8));i.setUint32(0,r.byteLength,!0),i.setUint32(4,5130562,!0);const s=Gl((a=JSON.stringify(n),(new TextEncoder).encode(a).buffer),32);var a;const o=new DataView(new ArrayBuffer(8));o.setUint32(0,s.byteLength,!0),o.setUint32(4,1313821514,!0);const l=new ArrayBuffer(12),c=new DataView(l);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0);const h=12+o.byteLength+s.byteLength+i.byteLength+r.byteLength;c.setUint32(8,h,!0);const u=new Blob([l,o,s,i,r],{type:"application/octet-stream"}),d=new FileReader;d.readAsArrayBuffer(u),d.onloadend=function(){t(d.result)}}}else if(n.buffers&&n.buffers.length>0){const e=new FileReader;e.readAsDataURL(l),e.onloadend=function(){const r=e.result;n.buffers[0].uri=r,t(n)}}else t(n)}serializeUserData(e,t){if(0===Object.keys(e.userData).length)return;const r=this.options,i=this.extensionsUsed;try{const s=JSON.parse(JSON.stringify(e.userData));if(r.includeCustomExtensions&&s.gltfExtensions){void 0===t.extensions&&(t.extensions={});for(const e in s.gltfExtensions)t.extensions[e]=s.gltfExtensions[e],i[e]=!0;delete s.gltfExtensions}Object.keys(s).length>0&&(t.extras=s)}catch(s){}}getUID(e,t=!1){if(!1===this.uids.has(e)){const t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const t=new i.Vector3;for(let r=0,i=e.count;r<i;r++)if(Math.abs(t.fromBufferAttribute(e,r).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);const r=e.clone(),s=new i.Vector3;for(let i=0,n=r.count;i<n;i++)s.fromBufferAttribute(r,i),0===s.x&&0===s.y&&0===s.z?s.setX(1):s.normalize(),r.setXYZ(i,s.x,s.y,s.z);return t.attributesNormalized.set(e,r),r}applyTextureTransform(e,t){let r=!1;const i={};0===t.offset.x&&0===t.offset.y||(i.offset=t.offset.toArray(),r=!0),0!==t.rotation&&(i.rotation=t.rotation,r=!0),1===t.repeat.x&&1===t.repeat.y||(i.scale=t.repeat.toArray(),r=!0),r&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=i,this.extensionsUsed.KHR_texture_transform=!0)}async buildMetalRoughTextureAsync(e,t){if(e===t)return e;function r(e){return e.colorSpace===i.SRGBColorSpace?function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}:function(e){return e}}e instanceof i.CompressedTexture&&(e=await this.decompressTextureAsync(e)),t instanceof i.CompressedTexture&&(t=await this.decompressTextureAsync(t));const s=e?e.image:null,n=t?t.image:null,a=Math.max(s?s.width:0,n?n.width:0),o=Math.max(s?s.height:0,n?n.height:0),l=Hl();l.width=a,l.height=o;const c=l.getContext("2d",{willReadFrequently:!0});c.fillStyle="#00ffff",c.fillRect(0,0,a,o);const h=c.getImageData(0,0,a,o);if(s){c.drawImage(s,0,0,a,o);const t=r(e),i=c.getImageData(0,0,a,o).data;for(let e=2;e<i.length;e+=4)h.data[e]=256*t(i[e]/256)}if(n){c.drawImage(n,0,0,a,o);const e=r(t),i=c.getImageData(0,0,a,o).data;for(let t=1;t<i.length;t+=4)h.data[t]=256*e(i[t]/256)}c.putImageData(h,0,0);const u=(e||t).clone();return u.source=new i.TextureSource(l),u.colorSpace=i.NoColorSpace,u.channel=(e||t).channel,e&&t&&(e.channel,t.channel),u}async buildNormalMapTextureAsync(e,t,r){e instanceof i.CompressedTexture&&(e=await this.decompressTextureAsync(e));const s=e.image,n=Hl();n.width=s.width,n.height=s.height;const a=n.getContext("2d",{willReadFrequently:!0});a.drawImage(s,0,0,n.width,n.height);const o=a.getImageData(0,0,n.width,n.height),l=o.data;for(let i=0;i<l.length;i+=4)t&&(l[i+0]=255-l[i+0]),r&&(l[i+1]=255-l[i+1]);a.putImageData(o,0,0);const c=e.clone();return c.source=new i.TextureSource(n),c}async decompressTextureAsync(e,t=1/0){if(null===this.textureUtils)throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.");return await this.textureUtils.decompress(e,t)}processBuffer(e){const t=this.json,r=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),r.push(e),0}processBufferView(e,t,r,s,n){const a=this.json;let o;switch(a.bufferViews||(a.bufferViews=[]),t){case vl:case Tl:o=1;break;case xl:case bl:o=2;break;default:o=4}let l=e.itemSize*o;n===Sl&&(l=4*Math.ceil(l/4));const c=zl(s*l),h=new DataView(new ArrayBuffer(c));let u=0;for(let p=r;p<r+s;p++){for(let r=0;r<e.itemSize;r++){let s;e.itemSize>4?s=e.array[p*e.itemSize+r]:(0===r?s=e.getX(p):1===r?s=e.getY(p):2===r?s=e.getZ(p):3===r&&(s=e.getW(p)),!0===e.normalized&&(s=i.MathUtils.normalize(s,e.array))),t===Ml?h.setFloat32(u,s,!0):t===_l?h.setInt32(u,s,!0):t===wl?h.setUint32(u,s,!0):t===xl?h.setInt16(u,s,!0):t===bl?h.setUint16(u,s,!0):t===vl?h.setInt8(u,s):t===Tl&&h.setUint8(u,s),u+=o}u%l!=0&&(u+=l-u%l)}const d={buffer:this.processBuffer(h.buffer),byteOffset:this.byteOffset,byteLength:c};void 0!==n&&(d.target=n),n===Sl&&(d.byteStride=l),this.byteOffset+=c,a.bufferViews.push(d);return{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,r=t.json;return r.bufferViews||(r.bufferViews=[]),new Promise((function(i){const s=new FileReader;s.readAsArrayBuffer(e),s.onloadend=function(){const e=Gl(s.result),n={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};t.byteOffset+=e.byteLength,i(r.bufferViews.push(n)-1)}}))}processAccessor(e,t,r,s){const n=this.json;let a;if(e.array.constructor===Float32Array)a=Ml;else if(e.array.constructor===Int32Array)a=_l;else if(e.array.constructor===Uint32Array)a=wl;else if(e.array.constructor===Int16Array)a=xl;else if(e.array.constructor===Uint16Array)a=bl;else if(e.array.constructor===Int8Array)a=vl;else{if(e.array.constructor!==Uint8Array)throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);a=Tl}if(void 0===r&&(r=0),void 0!==s&&s!==1/0||(s=e.count),0===s)return null;const o=function(e,t,r){const s={min:new Array(e.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(e.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let n=t;n<t+r;n++)for(let t=0;t<e.itemSize;t++){let r;e.itemSize>4?r=e.array[n*e.itemSize+t]:(0===t?r=e.getX(n):1===t?r=e.getY(n):2===t?r=e.getZ(n):3===t&&(r=e.getW(n)),!0===e.normalized&&(r=i.MathUtils.normalize(r,e.array))),s.min[t]=Math.min(s.min[t],r),s.max[t]=Math.max(s.max[t],r)}return s}(e,r,s);let l;void 0!==t&&(l=e===t.index?Al:Sl);const c=this.processBufferView(e,a,r,s,l),h={bufferView:c.id,byteOffset:c.byteOffset,componentType:a,count:s,max:o.max,min:o.min,type:{1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"}[e.itemSize]};return!0===e.normalized&&(h.normalized=!0),n.accessors||(n.accessors=[]),n.accessors.push(h)-1}processImage(e,t,r,s="image/png"){if(null!==e){const t=this,n=t.cache,a=t.json,o=t.options,l=t.pending;n.images.has(e)||n.images.set(e,{});const c=n.images.get(e),h=s+":flipY/"+r.toString();if(void 0!==c[h])return c[h];a.images||(a.images=[]);const u={mimeType:s},d=Hl();d.width=Math.min(e.width,o.maxTextureSize),d.height=Math.min(e.height,o.maxTextureSize);const p=d.getContext("2d",{willReadFrequently:!0});if(!0===r&&(p.translate(0,d.height),p.scale(1,-1)),void 0!==e.data){i.RGBAFormat,e.width>o.maxTextureSize||(e.height,o.maxTextureSize);const t=new Uint8ClampedArray(e.height*e.width*4);for(let r=0;r<t.length;r+=4)t[r+0]=e.data[r+0],t[r+1]=e.data[r+1],t[r+2]=e.data[r+2],t[r+3]=e.data[r+3];p.putImageData(new ImageData(t,e.width,e.height),0,0)}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");p.drawImage(e,0,0,d.width,d.height)}!0===o.binary?l.push(function(e,t){if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){let r;return"image/jpeg"===t?r=.92:"image/webp"===t&&(r=.8),e.convertToBlob({type:t,quality:r})}return new Promise((r=>e.toBlob(r,t)))}(d,s).then((e=>t.processBufferViewImage(e))).then((e=>{u.bufferView=e}))):u.uri=i.ImageUtils.getDataURL(d,s);const m=a.images.push(u)-1;return c[h]=m,m}throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const t=this.json;t.samplers||(t.samplers=[]);const r={magFilter:Ol[e.magFilter],minFilter:Ol[e.minFilter],wrapS:Ol[e.wrapS],wrapT:Ol[e.wrapT]};return t.samplers.push(r)-1}async processTextureAsync(e){const t=this.options,r=this.cache,s=this.json;if(r.textures.has(e))return r.textures.get(e);s.textures||(s.textures=[]),e instanceof i.CompressedTexture&&(e=await this.decompressTextureAsync(e,t.maxTextureSize));const n=e.userData.mimeType,a=this.processImage(e.image,e.format,e.flipY,n),o={sampler:this.processSampler(e)};"image/webp"===n?(o.extensions=o.extensions||{},o.extensions.EXT_texture_webp={source:a},this.extensionsUsed.EXT_texture_webp=!0,this.extensionsRequired.EXT_texture_webp=!0):o.source=a,e.name&&(o.name=e.name),await this._invokeAllAsync((async function(t){t.writeTexture&&await t.writeTexture(e,o)}));const l=s.textures.push(o)-1;return r.textures.set(e,l),l}async processMaterialAsync(e,t){const r=this.cache,s=this.json,n=void 0!==t&&t.hasAttribute("tangent"),a=e.normalMap?e.uuid+":"+n:e.uuid;if(r.materials.has(a))return r.materials.get(a);if(e.isShaderMaterial)return null;s.materials||(s.materials=[]);const o={pbrMetallicRoughness:{}};!0!==e.isMeshStandardMaterial&&e.isMeshBasicMaterial;const l=e.color.toArray().concat([e.opacity]);if(Vl(l,[1,1,1,1])||(o.pbrMetallicRoughness.baseColorFactor=l),e.isMeshStandardMaterial?(o.pbrMetallicRoughness.metallicFactor=e.metalness,o.pbrMetallicRoughness.roughnessFactor=e.roughness):(o.pbrMetallicRoughness.metallicFactor=0,o.pbrMetallicRoughness.roughnessFactor=1),e.metalnessMap||e.roughnessMap){const t=await this.buildMetalRoughTextureAsync(e.metalnessMap,e.roughnessMap),r={index:await this.processTextureAsync(t),texCoord:t.channel};this.applyTextureTransform(r,t),o.pbrMetallicRoughness.metallicRoughnessTexture=r}if(e.map){const t={index:await this.processTextureAsync(e.map),texCoord:e.map.channel};this.applyTextureTransform(t,e.map),o.pbrMetallicRoughness.baseColorTexture=t}if(e.emissive){const t=e.emissive;if(Math.max(t.r,t.g,t.b)>0&&(o.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const t={index:await this.processTextureAsync(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(t,e.emissiveMap),o.emissiveTexture=t}}if(e.normalMap){const t=e.normalScale,i=t.x<0,s=n?t.y<0:t.y>0;let a=e.normalMap;if(i||s){!1===r.normalMaps.has(e.normalMap)&&r.normalMaps.set(e.normalMap,{});const t=r.normalMaps.get(e.normalMap),n=`${i}:${s}`;void 0===t[n]&&(t[n]=await this.buildNormalMapTextureAsync(e.normalMap,i,s)),a=t[n]}const l={index:await this.processTextureAsync(a),texCoord:e.normalMap.channel};1!==Math.abs(t.x)&&(l.scale=Math.abs(t.x)),this.applyTextureTransform(l,e.normalMap),o.normalTexture=l}if(e.aoMap){const t={index:await this.processTextureAsync(e.aoMap),texCoord:e.aoMap.channel};1!==e.aoMapIntensity&&(t.strength=e.aoMapIntensity),this.applyTextureTransform(t,e.aoMap),o.occlusionTexture=t}e.transparent?o.alphaMode="BLEND":e.alphaTest>0&&(o.alphaMode="MASK",o.alphaCutoff=e.alphaTest),e.side===i.DoubleSide&&(o.doubleSided=!0),""!==e.name&&(o.name=e.name),this.serializeUserData(e,o),await this._invokeAllAsync((async function(t){t.writeMaterialAsync&&await t.writeMaterialAsync(e,o)}));const c=s.materials.push(o)-1;return r.materials.set(a,c),c}async processMeshAsync(e){const t=this.cache,r=this.json,i=[e.geometry.uuid];if(Array.isArray(e.material))for(let T=0,x=e.material.length;T<x;T++)i.push(e.material[T].uuid);else i.push(e.material.uuid);const s=i.join(":");if(t.meshes.has(s))return t.meshes.get(s);const n=e.geometry;let a;a=e.isLineSegments?ml:e.isLineLoop?fl:e.isLine?gl:e.isPoints?pl:e.material.wireframe?ml:yl;const o={},l={},c=[],h=[],u={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},d=n.getAttribute("normal");void 0===d||this.isNormalizedNormalAttribute(d)||n.setAttribute("normal",this.createNormalizedNormalAttribute(d));let p=null;for(let T in n.attributes){if("morph"===T.slice(0,5))continue;const e=n.attributes[T];T=u[T]||T.toUpperCase();if(/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(T)||T.startsWith("_")||(T="_"+T),t.attributes.has(this.getUID(e))){l[T]=t.attributes.get(this.getUID(e));continue}p=null;const r=e.array;"JOINTS_0"!==T||r instanceof Uint16Array||r instanceof Uint8Array?(r instanceof Uint32Array||r instanceof Int32Array)&&!T.startsWith("_")&&(p=dl.Utils.toTypedBufferAttribute(e,Float32Array)):p=dl.Utils.toTypedBufferAttribute(e,Uint16Array);const i=this.processAccessor(p||e,n);null!==i&&(T.startsWith("_")||this.detectMeshQuantization(T,e),l[T]=i,t.attributes.set(this.getUID(e),i))}if(void 0!==d&&n.setAttribute("normal",d),0===Object.keys(l).length)return null;if(void 0!==e.morphTargetInfluences&&e.morphTargetInfluences.length>0){const r=[],i=[],s={};if(void 0!==e.morphTargetDictionary)for(const t in e.morphTargetDictionary)s[e.morphTargetDictionary[t]]=t;for(let a=0;a<e.morphTargetInfluences.length;++a){const o={};let l=!1;for(const e in n.morphAttributes){if("position"!==e&&"normal"!==e){l||(l=!0);continue}const r=n.morphAttributes[e][a],i=e.toUpperCase(),s=n.attributes[e];if(t.attributes.has(this.getUID(r,!0))){o[i]=t.attributes.get(this.getUID(r,!0));continue}const c=r.clone();if(!n.morphTargetsRelative)for(let e=0,t=r.count;e<t;e++)for(let i=0;i<r.itemSize;i++)0===i&&c.setX(e,r.getX(e)-s.getX(e)),1===i&&c.setY(e,r.getY(e)-s.getY(e)),2===i&&c.setZ(e,r.getZ(e)-s.getZ(e)),3===i&&c.setW(e,r.getW(e)-s.getW(e));o[i]=this.processAccessor(c,n),t.attributes.set(this.getUID(s,!0),o[i])}h.push(o),r.push(e.morphTargetInfluences[a]),void 0!==e.morphTargetDictionary&&i.push(s[a])}o.weights=r,i.length>0&&(o.extras={},o.extras.targetNames=i)}const m=Array.isArray(e.material);if(m&&0===n.groups.length)return null;let f=!1;if(m&&null===n.index){const e=[];for(let t=0,r=n.attributes.position.count;t<r;t++)e[t]=t;n.setIndex(e),f=!0}const g=m?e.material:[e.material],y=m?n.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let T=0,x=y.length;T<x;T++){const e={mode:a,attributes:l};if(this.serializeUserData(n,e),h.length>0&&(e.targets=h),null!==n.index){let r=this.getUID(n.index);void 0===y[T].start&&void 0===y[T].count||(r+=":"+y[T].start+":"+y[T].count),t.attributes.has(r)?e.indices=t.attributes.get(r):(e.indices=this.processAccessor(n.index,n,y[T].start,y[T].count),t.attributes.set(r,e.indices)),null===e.indices&&delete e.indices}const r=await this.processMaterialAsync(g[y[T].materialIndex],n);null!==r&&(e.material=r),c.push(e)}!0===f&&n.setIndex(null),o.primitives=c,r.meshes||(r.meshes=[]),await this._invokeAllAsync((function(t){t.writeMesh&&t.writeMesh(e,o)}));const v=r.meshes.push(o)-1;return t.meshes.set(s,v),v}detectMeshQuantization(e,t){if(this.extensionsUsed[Dl])return;let r;switch(t.array.constructor){case Int8Array:r="byte";break;case Uint8Array:r="unsigned byte";break;case Int16Array:r="short";break;case Uint16Array:r="unsigned short";break;default:return}t.normalized&&(r+=" normalized");const i=e.split("_",1)[0];ul[i]&&ul[i].includes(r)&&(this.extensionsUsed[Dl]=!0,this.extensionsRequired[Dl]=!0)}processCamera(e){const t=this.json;t.cameras||(t.cameras=[]);const r=e.isOrthographicCamera,s={type:r?"orthographic":"perspective"};return r?s.orthographic={xmag:2*e.right,ymag:2*e.top,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:s.perspective={aspectRatio:e.aspect,yfov:i.MathUtils.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},""!==e.name&&(s.name=e.type),t.cameras.push(s)-1}processAnimation(e,t){const r=this.json,s=this.nodeMap;r.animations||(r.animations=[]);const n=(e=dl.Utils.mergeMorphTargetTracks(e.clone(),t)).tracks,a=[],o=[];for(let c=0;c<n.length;++c){const e=n[c],r=i.PropertyBinding.parseTrackName(e.name);let l=i.PropertyBinding.findNode(t,r.nodeName);const h=Bl[r.propertyName];if("bones"===r.objectName&&(l=!0===l.isSkinnedMesh?l.skeleton.getBoneByName(r.objectIndex):void 0),!l||!h)continue;const u=1;let d,p=e.values.length/e.times.length;h===Bl.morphTargetInfluences&&(p/=l.morphTargetInfluences.length),!0===e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(d="CUBICSPLINE",p/=3):d=e.getInterpolation()===i.InterpolateDiscrete?"STEP":"LINEAR",o.push({input:this.processAccessor(new i.BufferAttribute(e.times,u)),output:this.processAccessor(new i.BufferAttribute(e.values,p)),interpolation:d}),a.push({sampler:o.length-1,target:{node:s.get(l),path:h}})}const l={name:e.name||"clip_"+r.animations.length,samplers:o,channels:a};return this.serializeUserData(e,l),r.animations.push(l),r.animations.length-1}processSkin(e){const t=this.json,r=this.nodeMap,s=t.nodes[r.get(e)],n=e.skeleton;if(void 0===n)return null;const a=e.skeleton.bones[0];if(void 0===a)return null;const o=[],l=new Float32Array(16*n.bones.length),c=new i.Matrix4;for(let i=0;i<n.bones.length;++i)o.push(r.get(n.bones[i])),c.copy(n.boneInverses[i]),c.multiply(e.bindMatrix).toArray(l,16*i);void 0===t.skins&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new i.BufferAttribute(l,16)),joints:o,skeleton:r.get(a)});return s.skin=t.skins.length-1}async processNodeAsync(e){const t=this.json,r=this.options,i=this.nodeMap;if(t.nodes||(t.nodes=[]),null!==e.pivot)return await this._processNodeWithPivotAsync(e);const s={};if(r.trs){const t=e.quaternion.toArray(),r=e.position.toArray(),i=e.scale.toArray();Vl(t,[0,0,0,1])||(s.rotation=t),Vl(r,[0,0,0])||(s.translation=r),Vl(i,[1,1,1])||(s.scale=i)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===Vl(e.matrix.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])&&(s.matrix=e.matrix.elements);if(""!==e.name&&(s.name=String(e.name)),this.serializeUserData(e,s),e.isMesh||e.isLine||e.isPoints){const t=await this.processMeshAsync(e);null!==t&&(s.mesh=t)}else e.isCamera&&(s.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const n=t.nodes.push(s)-1;if(i.set(e,n),e.children.length>0){const t=[];for(let i=0,s=e.children.length;i<s;i++){const s=e.children[i];if(s.visible||!1===r.onlyVisible){const e=await this.processNodeAsync(s);null!==e&&t.push(e)}}t.length>0&&(s.children=t)}return await this._invokeAllAsync((function(t){t.writeNode&&t.writeNode(e,s)})),n}async _processNodeWithPivotAsync(e){const t=this.json,r=this.options,i=this.nodeMap,s=e.pivot,n={},a=e.quaternion.toArray(),o=[e.position.x+s.x,e.position.y+s.y,e.position.z+s.z],l=e.scale.toArray();Vl(a,[0,0,0,1])||(n.rotation=a),Vl(o,[0,0,0])||(n.translation=o),Vl(l,[1,1,1])||(n.scale=l),n.extras={pivot:s.toArray()},""!==e.name&&(n.name=String(e.name)),this.serializeUserData(e,n);const c=t.nodes.push(n)-1;i.set(e,c);const h={},u=[-s.x,-s.y,-s.z];if(Vl(u,[0,0,0])||(h.translation=u),e.isMesh||e.isLine||e.isPoints){const t=await this.processMeshAsync(e);null!==t&&(h.mesh=t)}else e.isCamera&&(h.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const d=[t.nodes.push(h)-1];if(e.children.length>0){const t=[];for(let i=0,s=e.children.length;i<s;i++){const s=e.children[i];if(s.visible||!1===r.onlyVisible){const e=await this.processNodeAsync(s);null!==e&&t.push(e)}}t.length>0&&(h.children=t)}return n.children=d,await this._invokeAllAsync((function(t){t.writeNode&&t.writeNode(e,n)})),c}async processSceneAsync(e){const t=this.json,r=this.options;t.scenes||(t.scenes=[],t.scene=0);const i={};""!==e.name&&(i.name=e.name),t.scenes.push(i);const s=[];for(let n=0,a=e.children.length;n<a;n++){const t=e.children[n];if(t.visible||!1===r.onlyVisible){const e=await this.processNodeAsync(t);null!==e&&s.push(e)}}s.length>0&&(i.nodes=s),this.serializeUserData(e,i)}async processObjectsAsync(e){const t=new i.Scene;t.name="AuxScene";for(let r=0;r<e.length;r++)t.children.push(e[r]);await this.processSceneAsync(t)}async processInputAsync(e){const t=this.options;e=e instanceof Array?e:[e],await this._invokeAllAsync((function(t){t.beforeParse&&t.beforeParse(e)}));const r=[];for(let s=0;s<e.length;s++)e[s]instanceof i.Scene?await this.processSceneAsync(e[s]):r.push(e[s]);r.length>0&&await this.processObjectsAsync(r);for(let i=0;i<this.skins.length;++i)this.processSkin(this.skins[i]);if(1===e.length)for(let i=0;i<t.animations.length;++i)this.processAnimation(t.animations[i],e[0]);else for(let i=0;i<e.length;i++){const r=t.animations[i]||[];for(let t=0;t<r.length;++t)this.processAnimation(r[t],e[i])}await this._invokeAllAsync((function(t){t.afterParse&&t.afterParse(e)}))}async _invokeAllAsync(e){for(let t=0,r=this.plugins.length;t<r;t++)await e(this.plugins[t])}}class Wl{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight)return;const r=this.writer,i=r.json,s=r.extensionsUsed,n={};e.name&&(n.name=e.name),n.color=e.color.toArray(),n.intensity=e.intensity,e.isDirectionalLight?n.type="directional":e.isPointLight?(n.type="point",e.distance>0&&(n.range=e.distance)):e.isSpotLight&&(n.type="spot",e.distance>0&&(n.range=e.distance),n.spot={},n.spot.innerConeAngle=(1-e.penumbra)*e.angle,n.spot.outerConeAngle=e.angle),void 0!==e.decay&&e.decay,e.target&&(e.target.parent!==e||0!==e.target.position.x||0!==e.target.position.y||e.target.position.z),s[this.name]||(i.extensions=i.extensions||{},i.extensions[this.name]={lights:[]},s[this.name]=!0);const a=i.extensions[this.name].lights;a.push(n),t.extensions=t.extensions||{},t.extensions[this.name]={light:a.length-1}}}class ql{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,t){if(!e.isMeshBasicMaterial)return;const r=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},r[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}}class Xl{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.clearcoat)return;const r=this.writer,i=r.extensionsUsed,s={};if(s.clearcoatFactor=e.clearcoat,e.clearcoatMap){const t={index:await r.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};r.applyTextureTransform(t,e.clearcoatMap),s.clearcoatTexture=t}if(s.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){const t={index:await r.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};r.applyTextureTransform(t,e.clearcoatRoughnessMap),s.clearcoatRoughnessTexture=t}if(e.clearcoatNormalMap){const t={index:await r.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};1!==e.clearcoatNormalScale.x&&(t.scale=e.clearcoatNormalScale.x),r.applyTextureTransform(t,e.clearcoatNormalMap),s.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class Kl{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.dispersion)return;const r=this.writer.extensionsUsed,i={};i.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}}class Yl{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.iridescence)return;const r=this.writer,i=r.extensionsUsed,s={};if(s.iridescenceFactor=e.iridescence,e.iridescenceMap){const t={index:await r.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};r.applyTextureTransform(t,e.iridescenceMap),s.iridescenceTexture=t}if(s.iridescenceIor=e.iridescenceIOR,s.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],s.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],e.iridescenceThicknessMap){const t={index:await r.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};r.applyTextureTransform(t,e.iridescenceThicknessMap),s.iridescenceThicknessTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class Ql{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const r=this.writer,i=r.extensionsUsed,s={};if(s.transmissionFactor=e.transmission,e.transmissionMap){const t={index:await r.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};r.applyTextureTransform(t,e.transmissionMap),s.transmissionTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class $l{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const r=this.writer,i=r.extensionsUsed,s={};if(s.thicknessFactor=e.thickness,e.thicknessMap){const t={index:await r.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};r.applyTextureTransform(t,e.thicknessMap),s.thicknessTexture=t}e.attenuationDistance!==1/0&&(s.attenuationDistance=e.attenuationDistance),s.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class Zl{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1.5===e.ior)return;const r=this.writer.extensionsUsed,i={};i.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}}class Jl{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(Nl)&&!e.specularIntensityMap&&!e.specularColorMap)return;const r=this.writer,i=r.extensionsUsed,s={};if(e.specularIntensityMap){const t={index:await r.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};r.applyTextureTransform(t,e.specularIntensityMap),s.specularTexture=t}if(e.specularColorMap){const t={index:await r.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};r.applyTextureTransform(t,e.specularColorMap),s.specularColorTexture=t}s.specularFactor=e.specularIntensity,s.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class ec{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.sheen)return;const r=this.writer,i=r.extensionsUsed,s={};if(e.sheenRoughnessMap){const t={index:await r.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};r.applyTextureTransform(t,e.sheenRoughnessMap),s.sheenRoughnessTexture=t}if(e.sheenColorMap){const t={index:await r.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};r.applyTextureTransform(t,e.sheenColorMap),s.sheenColorTexture=t}s.sheenRoughnessFactor=e.sheenRoughness,s.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class tc{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.anisotropy)return;const r=this.writer,i=r.extensionsUsed,s={};if(e.anisotropyMap){const t={index:await r.processTextureAsync(e.anisotropyMap)};r.applyTextureTransform(t,e.anisotropyMap),s.anisotropyTexture=t}s.anisotropyStrength=e.anisotropy,s.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class rc{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.emissiveIntensity)return;const r=this.writer.extensionsUsed,i={};i.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=i,r[this.name]=!0}}class ic{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.bumpScale&&!e.bumpMap)return;const r=this.writer,i=r.extensionsUsed,s={};if(e.bumpMap){const t={index:await r.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};r.applyTextureTransform(t,e.bumpMap),s.bumpTexture=t}s.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=s,i[this.name]=!0}}class sc{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;const r=this.writer,s=e,n=new Float32Array(3*s.count),a=new Float32Array(4*s.count),o=new Float32Array(3*s.count),l=new i.Matrix4,c=new i.Vector3,h=new i.Quaternion,u=new i.Vector3;for(let i=0;i<s.count;i++)s.getMatrixAt(i,l),l.decompose(c,h,u),c.toArray(n,3*i),h.toArray(a,4*i),u.toArray(o,3*i);const d={TRANSLATION:r.processAccessor(new i.BufferAttribute(n,3)),ROTATION:r.processAccessor(new i.BufferAttribute(a,4)),SCALE:r.processAccessor(new i.BufferAttribute(o,3))};s.instanceColor&&(d._COLOR_0=r.processAccessor(s.instanceColor)),t.extensions=t.extensions||{},t.extensions[this.name]={attributes:d},r.extensionsUsed[this.name]=!0,r.extensionsRequired[this.name]=!0}}function nc(e,t,r,s){const{lon:n,lat:a,alt:o}=i.ecefToGeodeticPosition(e,t,r),{east:l,north:c,up:h}=i.getEnuBasis(n,a),u=(new i.Matrix4).makeBasis((new i.Vector3).fromArray(l),(new i.Vector3).fromArray(c),(new i.Vector3).fromArray(h)),d=(new i.Quaternion).setFromRotationMatrix(u).clone().invert().multiply(s),p=(new i.Euler).setFromQuaternion(d,"ZYX");return{lon:n,lat:a,alt:o,pitch:i.MathUtils.radToDeg(p.x)-90,yaw:i.MathUtils.radToDeg(p.z),roll:i.MathUtils.radToDeg(p.y)}}function ac(e,t){return(new i.Vector3).fromArray(i.getEnuBasis(e,t).up)}function oc(e,t,r,s,n){const a=i.getEnuBasis(e,t);r+=90;const o=(new i.Matrix4).makeBasis((new i.Vector3).fromArray(a.east),(new i.Vector3).fromArray(a.north),(new i.Vector3).fromArray(a.up)),l=new i.Euler(i.MathUtils.degToRad(r),i.MathUtils.degToRad(n),i.MathUtils.degToRad(s),"ZYX"),c=(new i.Quaternion).setFromEuler(l);return(new i.Quaternion).setFromRotationMatrix(o).multiply(c)}function lc(e,t){const r=(new i.Vector3).subVectors(t,e).normalize(),s=e.clone().normalize();Math.abs(r.dot(s))>.99&&s.set(0,0,1);const n=(new i.Vector3).crossVectors(r,s).normalize();return(new i.Vector3).crossVectors(n,r).normalize()}dl.Utils={insertKeyframe:function(e,t){const r=.001,i=e.getValueSize(),s=new e.TimeBufferType(e.times.length+1),n=new e.ValueBufferType(e.values.length+i),a=e.createInterpolant(new e.ValueBufferType(i));let o;if(0===e.times.length){s[0]=t;for(let e=0;e<i;e++)n[e]=0;o=0}else if(t<e.times[0]){if(Math.abs(e.times[0]-t)<r)return 0;s[0]=t,s.set(e.times,1),n.set(a.evaluate(t),0),n.set(e.values,i),o=0}else if(t>e.times[e.times.length-1]){if(Math.abs(e.times[e.times.length-1]-t)<r)return e.times.length-1;s[s.length-1]=t,s.set(e.times,0),n.set(e.values,0),n.set(a.evaluate(t),e.values.length),o=s.length-1}else for(let l=0;l<e.times.length;l++){if(Math.abs(e.times[l]-t)<r)return l;if(e.times[l]<t&&e.times[l+1]>t){s.set(e.times.slice(0,l+1),0),s[l+1]=t,s.set(e.times.slice(l+1),l+2),n.set(e.values.slice(0,(l+1)*i),0),n.set(a.evaluate(t),(l+1)*i),n.set(e.values.slice((l+1)*i),(l+2)*i),o=l+1;break}}return e.times=s,e.values=n,o},mergeMorphTargetTracks:function(e,t){const r=[],s={},n=e.tracks;for(let a=0;a<n.length;++a){let e=n[a];const o=i.PropertyBinding.parseTrackName(e.name),l=i.PropertyBinding.findNode(t,o.nodeName);if("morphTargetInfluences"!==o.propertyName||void 0===o.propertyIndex){r.push(e);continue}if(e.createInterpolant!==e.InterpolantFactoryMethodDiscrete&&e.createInterpolant!==e.InterpolantFactoryMethodLinear){if(e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");e=e.clone(),e.setInterpolation(i.InterpolateLinear)}const c=l.morphTargetInfluences.length,h=l.morphTargetDictionary[o.propertyIndex];if(void 0===h)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let u;if(void 0===s[l.uuid]){u=e.clone();const t=new u.ValueBufferType(c*u.times.length);for(let e=0;e<u.times.length;e++)t[e*c+h]=u.values[e];u.name=(o.nodeName||"")+".morphTargetInfluences",u.values=t,s[l.uuid]=u,r.push(u);continue}const d=e.createInterpolant(new e.ValueBufferType(1));u=s[l.uuid];for(let t=0;t<u.times.length;t++)u.values[t*c+h]=d.evaluate(u.times[t]);for(let t=0;t<e.times.length;t++){const r=this.insertKeyframe(u,e.times[t]);u.values[r*c+h]=e.values[t]}}return e.tracks=r,e},toTypedBufferAttribute:function(e,t){const r=new i.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!1);if(!e.normalized&&!e.isInterleavedBufferAttribute)return r.array.set(e.array),r;for(let i=0,s=e.count;i<s;i++)for(let t=0;t<e.itemSize;t++)r.setComponent(i,t,e.getComponent(i,t));return r}};class cc extends p{constructor(e){super(),this.camera=e,this.lookAt=new i.Vector3,this.cameraTween=null,this.lookAtTween=null,this.activeTransition=null,this.is2D=!1}animateTo(e,t,r=sl){return this.cancel(),new Promise((s=>{const n=this.camera.position.clone(),a=this.camera.quaternion.clone(),o=e.clone(),l=t.clone(),c={resolve:s,toPosition:o,toQuaternion:l};this.activeTransition=c;const h=o.clone().sub(n).length(),u=l.clone().multiply(a.clone().invert()),d=Math.acos(Math.min(1,u.w));if(r<=0||h<1&&d<1)this.camera.position.copy(o),this.camera.quaternion.copy(l),this.camera.updateMatrixWorld(!0),this.activeTransition=null,s(!0);else{const e=new i.Vector3(0,0,.25*-h).applyQuaternion(a).add(n),t=new i.Vector3(0,0,.25*-h).applyQuaternion(l).add(o),s=lc(n,e),u=lc(o,t);this.camera.up.copy(s),this.lookAt.copy(e),this.lookAtTween=new tl(this.lookAt).to(t,r).easing(Yo.Quartic.InOut).onComplete((()=>{this.lookAt.copy(t),this.lookAtTween=null,this.complete(c)})).start(),this.cameraTween=new tl(this.camera).to({position:o,up:u},r).easing(Yo.Quartic.InOut).onComplete((()=>{this.camera.position.copy(o),this.cameraTween=null,this.complete(c)})).start()}}))}complete(e){this.activeTransition!==e||this.cameraTween||this.lookAtTween||(this.camera.position.copy(e.toPosition),this.camera.quaternion.copy(e.toQuaternion),this.camera.updateMatrixWorld(!0),this.activeTransition=null,e.resolve(!0))}update(e){this.cameraUpTween&&this.cameraUpTween.update(e),this.cameraTween&&this.cameraTween.update(e),this.lookAtTween&&this.lookAtTween.update(e),(this.cameraTween||this.lookAtTween)&&this.camera.lookAt(this.lookAt)}cancel(){const e=this.activeTransition;this.activeTransition=null,this.cameraTween&&(this.cameraTween.stop(),this.cameraTween=null),this.lookAtTween&&(this.lookAtTween.stop(),this.lookAtTween=null),this.cameraUpTween&&(this.cameraUpTween.stop(),this.cameraUpTween=null),null==e||e.resolve(!1)}}class hc extends i.Mesh{constructor(){const e=new i.ShaderMaterial({name:"SkyMaterial",uniforms:{turbidity:{value:5},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.5},sunPosition:{value:new i.Vector3},up:{value:new i.Vector3(0,1,0)},surfaceUp:{value:new i.Vector3(0,1,0)}},vertexShader:"uniform vec3 sunPosition;uniform float rayleigh;uniform float turbidity;uniform float mieCoefficient;uniform vec3 up;varying vec3 vWorldPosition;varying vec3 vSunDirection;varying float vSunfade;varying vec3 vBetaR;varying vec3 vBetaM;varying float vSunE;const float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 totalRayleigh=vec3(5.804542996261093E-6,1.3562911419845635E-5,3.0265902468824876E-5);const float v=4.0;const vec3 K=vec3(0.686,0.678,0.666);const vec3 MieConst=vec3(1.8399918514433978E14,2.7798023919660528E14,4.0790479543861094E14);const float cutoffAngle=1.6110731556870734;const float steepness=1.5;const float EE=1000.0;float sunIntensity(float zenithAngleCos){zenithAngleCos=clamp(zenithAngleCos,-1.0,1.0);return EE*max(0.0,1.0-pow(e,-((cutoffAngle-acos(zenithAngleCos))/steepness)));}vec3 totalMie(float T){float c=(0.2*T)*10E-18;return 0.434*c*MieConst;}void main(){vec4 worldPosition=modelMatrix*vec4(position,1.0);vWorldPosition=worldPosition.xyz;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);gl_Position.z=gl_Position.w;vSunDirection=normalize(sunPosition);vSunE=sunIntensity(dot(vSunDirection,up));vSunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-vSunfade));vBetaR=totalRayleigh*rayleighCoefficient;vBetaM=totalMie(turbidity)*mieCoefficient;}",fragmentShader:"varying vec3 vWorldPosition;varying vec3 vSunDirection;varying float vSunfade;varying vec3 vBetaR;varying vec3 vBetaM;varying float vSunE;uniform float mieDirectionalG;uniform vec3 up;uniform vec3 surfaceUp;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float THREE_OVER_SIXTEENPI=0.05968310365946075;const float ONE_OVER_FOURPI=0.07957747154594767;float rayleighPhase(float cosTheta){return THREE_OVER_SIXTEENPI*(1.0+pow(cosTheta,2.0));}float hgPhase(float cosTheta,float g){float g2=pow(g,2.0);float inverse=1.0/pow(1.0-2.0*g*cosTheta+g2,1.5);return ONE_OVER_FOURPI*((1.0-g2)*inverse);}void main(){vec3 direction=normalize(vWorldPosition-cameraPosition);float zenithAngle=acos(max(0.0,dot(surfaceUp,direction)));float inverse=1.0/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sR=rayleighZenithLength*inverse;float sM=mieZenithLength*inverse;vec3 Fex=exp(-(vBetaR*sR+vBetaM*sM));float cosTheta=dot(direction,vSunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=vBetaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=vBetaM*mPhase;vec3 Lin=pow(vSunE*((betaRTheta+betaMTheta)/(vBetaR+vBetaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(vSunE*((betaRTheta+betaMTheta)/(vBetaR+vBetaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,vSunDirection),5.0),0.0,1.0));float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(vSunE*19000.0*Fex)*sundisk;vec3 texColor=(Lin+L0)*0.04+vec3(0.0,0.0003,0.00075);vec3 retColor=pow(texColor,vec3(1.0/(1.2+(1.2*vSunfade))));gl_FragColor=vec4(retColor,1.0);\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n}",side:i.BackSide,depthWrite:!1});super(new i.BoxGeometry(1,1,1),e),this.isSky=!0,this.type="Sky",this.material=e}setSurfaceUp(e){this.material.uniforms.surfaceUp.value.copy(e)}}class uc extends i.Object3D{constructor(){super(),this.type="ContentLayer",this.isContentLayer=!0,this.contentLayerId=null,this.labels=new Set}setLabels(e){this.labels.clear();for(let t=0;t<e.length;t++)this.labels.add(e[t])}setEnabled(e){this.visible=e}update(){}dispose(){super.dispose()}disposeObjectResources(e=this){e.traverse((e=>{var t,r,i,s,n;null==(r=null==(t=e.geometry)?void 0:t.dispose)||r.call(t);const a=Array.isArray(e.material)?e.material:e.material?[e.material]:[];for(const o of a){for(const e of Object.values(o))(null==e?void 0:e.isTexture)&&(null==(i=e.dispose)||i.call(e));null==(s=o.dispose)||s.call(o)}e!==this&&(null==(n=e.dispose)||n.call(e))}))}}class dc extends uc{constructor(e,t={},r={}){super(),this.type="TilesLayer",this.isTilesLayer=!0;const s=(null==t?void 0:t.renderOrder)??0,n=(null==t?void 0:t.implicit)??!1,a="overlay"==(null==t?void 0:t.blendeMode),o=i.normalizeLayerOffset(t.offset,"3D Tiles offset"),l=0!==o.lon||0!==o.lat||0!==o.alt;let c=!1;this.firstSet=(null==t?void 0:t.firstSet)??null,this.camera=(null==t?void 0:t.camera)??null,this.renderer=(null==t?void 0:t.renderer)??null,this.ownsDecoders=!t.decoders,this.decoders=t.decoders??new Qs(this.renderer),this.dracoLoader=this.decoders.getDraco(),this.ktx2loader=this.decoders.getKTX2(),this.layers.set(s);const h=new vi(e);e.startsWith("http")||h.registerPlugin(new Ca({apiToken:il.CESIUM,assetId:e,autoRefreshToken:!0})),n&&h.registerPlugin(new cn),h.registerPlugin(new Ao({rtc:!0,dracoLoader:this.dracoLoader,ktxLoader:this.ktx2loader,autoDispose:!1})),h.errorTarget=20,this.firstSet&&(h.lruCache=this.firstSet.lruCache,h.downloadQueue=this.firstSet.downloadQueue,h.parseQueue=this.firstSet.parseQueue,h.processNodeQueue=this.firstSet.processNodeQueue),h.setCamera(this.camera),h.setResolutionFromRenderer(this.camera,this.renderer),h.addEventListener("load-model",(e=>{var t;if(l&&!c)try{const e=new i.Sphere;if(!h.getBoundingSphere(e))throw new Error("3D Tiles offset requires root bounds");const t=i.ecefToGeodeticPosition(...e.center.toArray()),r=i.geodeticOffsetToEcefDelta(t,o);h.group.position.add((new i.Vector3).fromArray(r)),c=!0}catch(s){null==(t=r.onError)||t.call(r,s instanceof Error?s:new Error(String(s)))}e.scene.traverse((e=>{e.layers.mask=this.layers.mask,e.material&&(e.material.isPointsMaterial?(e.material.sizeAttenuation=!0,e.material.size=.2,e.material.map=(new i.TextureLoader).load("/assets/viewer/dot.png",(e=>{})),e.material.alphaTest=.1,e.material.transparent=!0,e.material.onBeforeCompile=e=>{e.vertexShader="uniform float size;uniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\nvarying vec2 vUv;uniform mat3 uvTransform;\n#endif\nvoid main(){\n#ifdef USE_POINTS_UV\nvUv=(uvTransform*vec3(uv,1)).xy;\n#endif\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <project_vertex>\ngl_PointSize=size;bool isPerspective=isPerspectiveMatrix(projectionMatrix);if(isPerspective){gl_PointSize*=(scale/-mvPosition.z);gl_PointSize=max(gl_PointSize,5.0);}\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <fog_vertex>\n}",e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\nvec3 outgoingLight=vec3(0.0);\n#include <logdepthbuf_fragment>\n#include <map_particle_fragment>\n#include <color_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\noutgoingLight=diffuseColor.rgb;\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n}"}):(e.material.onBeforeCompile=e=>{a&&(e.vertexShader="#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main(){\n#include <uv_vertex>\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <batching_vertex>\n#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#endif\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <envmap_vertex>\n#include <fog_vertex>\n}",e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nuniform float overlayMode;void main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <color_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\ngl_FragColor=mix(gl_FragColor,vec4(gl_FragColor.rgb,gl_FragColor.a*pow(gl_FragColor.b,0.667)),overlayMode);}",e.uniforms.overlayMode={value:a?1:0})},a&&(e.material.transparent=!0,e.material.alphaTest=.1)))}))})),this.tiles=h,this.add(h.group)}update(){super.update(),this.visible&&this.tiles.update()}dispose(){super.dispose(),this.tiles&&(this.tiles.dispose(),this.remove(this.tiles.group),this.tiles=null),this.ownsDecoders&&this.decoders.dispose()}}class pc extends uc{constructor(e,t={},r={}){super(),this.type="MeshLayer",this.isMeshLayer=!0;const s=(null==t?void 0:t.renderOrder)??0,n=i.normalizeLayerOffset(t.offset,"Mesh offset"),a=0!==n.lon||0!==n.lat||0!==n.alt;(new Je).load(e,(e=>{var s;const o=e.scene;if(o.traverse((e=>{e.layers.set(6);const t=Array.isArray(e.material)?e.material:e.material?[e.material]:[];for(const r of t)r.transparent=!0,r.onBeforeCompile=e=>{e.fragmentShader="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n#include <dithering_fragment>\n#ifdef USE_COLOR\ngl_FragColor.a=vColor.r;\n#endif\n}"}})),this.mesh=o,this.add(o),a)try{const e=t.offsetOrigin,r=i.validateGeodeticPosition(null==e?void 0:e.longitude,null==e?void 0:e.latitude,null==e?void 0:e.altitude,"Mesh offset origin");this.position.fromArray(i.geodeticOffsetToEcefDelta({lon:r.longitude,lat:r.latitude,alt:r.altitude},n))}catch(l){null==(s=r.onError)||s.call(r,l instanceof Error?l:new Error(String(l)))}}),void 0,(e=>{var t;return null==(t=r.onError)?void 0:t.call(r,e instanceof Error?e:new Error(String(e)))})),this.layers.set(s)}dispose(){super.dispose(),this.mesh&&(this.disposeObjectResources(this.mesh),this.mesh.removeFromParent(),this.mesh=null)}}var mc="#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying float vOpacity;void main(){\n#include <uv_vertex>\n#include <color_vertex>\n#include <morphinstance_vertex>\n#include <morphcolor_vertex>\n#include <batching_vertex>\n#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#endif\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#include <worldpos_vertex>\n#include <envmap_vertex>\n#include <fog_vertex>\nvOpacity=smoothstep(100.0,500.0,-mvPosition.z);}",fc="uniform vec3 diffuse;uniform float opacity;\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying float vOpacity;void main(){vec4 diffuseColor=vec4(diffuse,opacity);\n#include <clipping_planes_fragment>\n#include <logdepthbuf_fragment>\n#include <map_fragment>\n#include <color_fragment>\n#include <alphamap_fragment>\n#include <alphatest_fragment>\n#include <alphahash_fragment>\n#include <specularmap_fragment>\nReflectedLight reflectedLight=ReflectedLight(vec3(0.0),vec3(0.0),vec3(0.0),vec3(0.0));\n#ifdef USE_LIGHTMAP\nvec4 lightMapTexel=texture2D(lightMap,vLightMapUv);reflectedLight.indirectDiffuse+=lightMapTexel.rgb*lightMapIntensity*RECIPROCAL_PI;\n#else\nreflectedLight.indirectDiffuse+=vec3(1.0);\n#endif\n#include <aomap_fragment>\nreflectedLight.indirectDiffuse*=diffuseColor.rgb;vec3 outgoingLight=reflectedLight.indirectDiffuse;\n#include <envmap_fragment>\n#include <opaque_fragment>\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n#include <fog_fragment>\n#include <premultiplied_alpha_fragment>\n#include <dithering_fragment>\ngl_FragColor.a*=vOpacity;}";const gc=new class{constructor(e=4){this.limit=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this.onMessage.bind(this,e)),this.workers[e]=t}}getIdleWorker(){for(let e=0;e<this.limit;e++)if(!(this.workerStatus&1<<e))return e;return-1}onMessage(e,t){const r=this.workersResolve[e];if(r&&r(t),this.queue.length){const{resolve:t,msg:r,transfer:i}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(r,i)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.limit=e}postMessage(e,t){return new Promise((r=>{const i=this.getIdleWorker();-1!==i?(this.initWorker(i),this.workerStatus|=1<<i,this.workersResolve[i]=r,this.workers[i].postMessage(e,t)):this.queue.push({resolve:r,msg:e,transfer:t})}))}dispose(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};function yc(e=new Date(-864e13),t=new Date(864e13),r,i){return r&&i?r<=t&&i>e:r?r<=t:!i||i>e}gc.setWorkerCreator((function(e){return new Worker(new URL("./assets/viewer/geojson.worker-D3uq_RbR.js", require("url").pathToFileURL(__filename)),{name:null==e?void 0:e.name})}));class vc extends i.Object3D{constructor(e,t={},r={}){var s,n,a;super(),this.type="ArrowFeature",this.isArrowFeature=!0,this.timeStart=(null==(s=null==e?void 0:e.properties)?void 0:s.timeStart)?new Date(e.properties.timeStart):null,this.timeEnd=(null==(n=null==e?void 0:e.properties)?void 0:n.timeEnd)?new Date(e.properties.timeEnd):null;const o=(null==t?void 0:t.renderOrder)??0,l=(null==(a=null==e?void 0:e.properties)?void 0:a.color)??15955057;gc.postMessage({type:"arrow",data:e,color:l}).then((e=>{var t;const{success:s,error:n,origin:a,meshVertexBuffer:c}=e.data;if(s){this.position.fromArray(a);const e=new i.BufferGeometry;e.setAttribute("position",new i.BufferAttribute(c,3));const t=new i.MeshBasicMaterial({color:l,side:i.DoubleSide,depthTest:!1,opacity:.75,transparent:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=mc,e.fragmentShader=fc};const r=new i.Mesh(e,t);r.layers.set(o),this.add(r)}else null==(t=r.onError)||t.call(r,new Error((null==n?void 0:n.message)??String(n)))}))}}class Tc extends i.Object3D{constructor(e,t={},r={}){var s,n,a;super(),this.type="PerimeterFeature",this.isPerimeterFeature=!0,this.timeStart=(null==(s=null==e?void 0:e.properties)?void 0:s.timeStart)?new Date(e.properties.timeStart):null,this.timeEnd=(null==(n=null==e?void 0:e.properties)?void 0:n.timeEnd)?new Date(e.properties.timeEnd):null;const o=(null==t?void 0:t.renderOrder)??0,l=(null==(a=null==e?void 0:e.properties)?void 0:a.color)??15955057;gc.postMessage({type:"perimeter",data:e,color:l}).then((e=>{var t;const{success:s,error:n,origin:a,lineVertexBuffer:l,lineVertexRGBBuffer:c,meshVertexBuffer:h,meshVertexRGBBuffer:u,meshIndexBuffer:d}=e.data;if(s){this.position.fromArray(a);const e=new i.BufferGeometry;e.setAttribute("position",new i.BufferAttribute(h,3)),e.setAttribute("color",new i.BufferAttribute(u,3,!0)),e.setIndex(new i.BufferAttribute(d,1));const t=new i.MeshBasicMaterial({opacity:.2,transparent:!0,side:i.DoubleSide,depthTest:!1,vertexColors:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=mc,e.fragmentShader=fc};const r=new i.Mesh(e,t);r.layers.set(o);const s=new i.BufferGeometry;s.setAttribute("position",new i.BufferAttribute(l,3)),s.setAttribute("color",new i.BufferAttribute(c,3,!0));const n=new i.LineSegments(s,new i.LineBasicMaterial({vertexColors:!0,toneMapped:!1}));n.layers.set(o),n.add(r),this.add(n)}else null==(t=r.onError)||t.call(r,new Error((null==n?void 0:n.message)??String(n)))}))}}class xc extends uc{constructor(e,t={},r={}){var i;super(),this.type="GeojsonLayer",this.isGeojsonLayer=!0;for(let s=0;s<(null==(i=e.features)?void 0:i.length);s++){const i=e.features[s];switch(i.properties.type){case"arrow":const e=new vc(i,t,r);this.add(e);break;case"perimeter":const s=new Tc(i,t,r);this.add(s)}}}setTimeFrame(e,t){e&&!e.isDate&&(e=new Date(e)),t&&!t.isDate&&(t=new Date(t));for(let r=0;r<this.children.length;r++){const i=this.children[r],s=i.timeStart,n=i.timeEnd;i.visible=yc(e,t,s,n)}}dispose(){super.dispose(),this.disposeObjectResources(),this.clear()}}const bc=new Set(["ply","sog","spz","rad"]);function _c(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`${t} must be a non-empty string.`)}function wc(e){var t,r,s,n;if(!e||"object"!=typeof e)throw new Error("Gaussian splat layer definition must be an object.");if(_c(e.id,"id"),_c(e.name,"name"),"gaussian-splat"!==e.type)throw new Error('type must be "gaussian-splat".');if(!Array.isArray(e.labels)||!e.labels.every((e=>"string"==typeof e)))throw new Error("labels must be an array of strings.");if(_c(null==(t=e.data)?void 0:t.url,"data.url"),!bc.has(null==(r=e.data)?void 0:r.format))throw new Error('data.format must be "ply", "sog", "spz", or "rad".');if(0!==((null==(s=e.options)?void 0:s.renderOrder)??0))throw new Error("Gaussian splat layers only support renderOrder 0.");const a=null==(n=e.options)?void 0:n.transform,o=null==a?void 0:a.anchor;if(!o)throw new Error("options.transform.anchor must contain finite longitude, latitude, and altitude values.");i.validateGeodeticPosition(o.longitude,o.latitude,o.altitude,"Gaussian anchor");const l=a.translationENU??[0,0,0],c=a.rotationDegrees??[0,0,0],h=a.scale??1;return i.validateTuple(l,"translationENU"),i.validateTuple(c,"rotationDegrees"),i.validateScale(h,"scale"),{...e,labels:[...e.labels],data:{...e.data},options:{...e.options,renderOrder:0,transform:{anchor:{...o},translationENU:[...l],rotationDegrees:[...c],scale:h}}}}function Mc(e,t){return{ply:e.SplatFileType.PLY,sog:e.SplatFileType.PCSOGSZIP,spz:e.SplatFileType.SPZ,rad:e.SplatFileType.RAD}[t]}class Sc extends uc{constructor(e,t={}){super(),this.type="GaussianSplatLayer",this.isGaussianSplatLayer=!0,this.contentLayerId=e.id,this.definition=e,this.callbacks=t,this.loadState="idle",this.loadAttempt=0,this.abortController=null,this.splatMesh=null,this.visible=!1,this.layers.set(0),this.setLabels(e.labels),this.transformMatrix=function(e){const{anchor:t,translationENU:r,rotationDegrees:s,scale:n}=e,a=i.getEnuBasis(t.longitude,t.latitude),o=(new i.Vector3).fromArray(a.east),l=(new i.Vector3).fromArray(a.north),c=(new i.Vector3).fromArray(a.up),h=(new i.Matrix4).makeBasis(o,l,c);h.setPosition((new i.Vector3).fromArray(i.geodeticToEcefPosition(t.longitude,t.latitude,t.altitude)));const u=(new i.Quaternion).setFromEuler(new i.Euler(s[0]*Math.PI/180,s[1]*Math.PI/180,s[2]*Math.PI/180,"XYZ")),d=(new i.Matrix4).compose((new i.Vector3).fromArray(r),u,new i.Vector3(n,n,n));return h.multiply(d)}(e.options.transform)}setEnabled(e){if("disposed"===this.loadState)return;const t=this.visible;this.visible=e,!e||t||"idle"!==this.loadState&&"error"!==this.loadState||this.load()}async load(){var e,t,r,i,s,n,a,o,l,c;if("loading"===this.loadState||"ready"===this.loadState||"disposed"===this.loadState)return;const h=++this.loadAttempt;this.loadState="loading";let u=null;try{null==(t=(e=this.callbacks).onStart)||t.call(e,this);const o=await d();if("disposed"===this.loadState||h!==this.loadAttempt)return;if(await(null==(i=(r=this.callbacks).ensureRenderer)?void 0:i.call(r)),"disposed"===this.loadState||h!==this.loadAttempt)return;if(u="rad"===this.definition.data.format?this.createPagedMesh(o):await this.createDirectMesh(o,h),u.layers.set(0),u.matrix.copy(this.transformMatrix),u.matrix.decompose(u.position,u.quaternion,u.scale),u.matrixAutoUpdate=!1,u.matrixWorldNeedsUpdate=!0,this.splatMesh=u,this.add(u),"rad"===this.definition.data.format){if(!(null==(s=u.paged)?void 0:s.getRadMeta))throw new Error("Failed to initialize paged RAD streaming.");await Promise.all([u.initialized,u.paged.getRadMeta()])}else await u.initialized;if("disposed"===this.loadState||h!==this.loadAttempt)return void this.disposeMesh(u);this.abortController=null,this.loadState="ready",null==(a=(n=this.callbacks).onReady)||a.call(n,this)}catch(p){this.disposeMesh(u);const e=null==(o=this.abortController)?void 0:o.signal.aborted;if(this.abortController=null,"disposed"===this.loadState||h!==this.loadAttempt||e)return;this.loadState="error",null==(c=(l=this.callbacks).onError)||c.call(l,this,function(e){return e instanceof Error?e:new Error(String(e))}(p))}}createPagedMesh(e){const t=new e.PagedSplats({rootUrl:this.definition.data.url,fileType:Mc(e,this.definition.data.format)});return new e.SplatMesh({paged:t})}async createDirectMesh(e,t){this.abortController=new AbortController;const r=await fetch(this.definition.data.url,{signal:this.abortController.signal});if(!r.ok)throw new Error(`Failed to load Gaussian splat: ${r.status} ${r.statusText}`);if(!r.body)throw new Error("Failed to load Gaussian splat: response body is unavailable.");const i=r.headers.get("Content-Length"),s=null===i?void 0:Number.parseInt(i,10);return new e.SplatMesh({stream:r.body,streamLength:Number.isFinite(s)&&s>=0?s:void 0,fileType:Mc(e,this.definition.data.format),onProgress:e=>{var r,i;"disposed"!==this.loadState&&t===this.loadAttempt&&(null==(i=(r=this.callbacks).onProgress)||i.call(r,this,{loaded:e.loaded,total:e.total,lengthComputable:e.lengthComputable}))}})}disposeMesh(e){e&&!e.userData.gaussianSplatDisposed&&(e.userData.gaussianSplatDisposed=!0,e.removeFromParent(),e.dispose(),this.splatMesh===e&&(this.splatMesh=null))}dispose(){var e;"disposed"!==this.loadState&&(this.loadState="disposed",this.loadAttempt++,null==(e=this.abortController)||e.abort(),this.abortController=null,this.disposeMesh(this.splatMesh),this.callbacks={},super.dispose())}}function Ac(e,t,r={}){var s,n,a;const o=r.source??"all";if(!["all","splats","globe","content"].includes(o))throw new TypeError("Unknown surface pick source.");const l=r.layerIds&&new Set(r.layerIds);let c=null;const h=(e,t,r)=>{e&&(!c||e.distance<c.distance)&&(c={...e,source:t,layerId:r})},u=(e,r,s)=>{var n,a;if(!e||!e.visible)return;if(e===(null==(n=e.parent)?void 0:n.splatMesh))return void h(function(e,t){if(!e||!1===e.visible||!1===e.raycastable||0===e.opacity)return null;if(!e.matrixWorld.determinant())return null;const r=e.matrixWorld.clone().invert(),s=t.ray.origin.clone().applyMatrix4(r),n=t.ray.direction.clone().applyMatrix3((new i.Matrix3).setFromMatrix4(r)),a=new i.Vector3,o=new i.Vector3,l=new i.Quaternion,c=Math.max(0,t.near);let h=t.far,u=-1;return e.forEachSplat(((t,r,i,d,p)=>{if(!Number.isFinite(p)||p<(e.minRaycastOpacity??.2))return;const m=4*Math.max(p,1)-3,f=i.x*m,g=i.y*m,y=i.z*m;if(![f,g,y].every(Number.isFinite)||Math.min(f,g,y)<0)return;l.copy(d).normalize().conjugate(),a.copy(s).sub(r).applyQuaternion(l),o.copy(n).applyQuaternion(l);const v=.01*Math.max(f,g,y);let T;if(y<v||g<v||f<v){const e=y<v?"z":g<v?"y":"x",[t,r,i,s]="z"===e?["x","y",f,g]:"y"===e?["x","z",f,y]:["y","z",g,y];if(Math.abs(o[e])<1e-12||0===i||0===s)return;if(T=-a[e]/o[e],((a[t]+T*o[t])/i)**2+((a[r]+T*o[r])/s)**2>1)return}else{if(0===v)return;a.set(a.x/f,a.y/g,a.z/y),o.set(o.x/f,o.y/g,o.z/y);const e=o.lengthSq();if(!Number.isFinite(e)||0===e)return;const t=-a.dot(o)/e;a.addScaledVector(o,t);const r=1-a.lengthSq();if(r<0)return;const i=Math.sqrt(r/e);T=t-i,T<c&&(T=t+i)}Number.isFinite(T)&&T>=c&&T<=h&&(h=T,u=t)})),u<0?null:{distance:h,point:t.ray.at(h,new i.Vector3),object:e,splatIndex:u}}(e,t),"splats",s);const o=[];null==(a=e.raycast)||a.call(e,t,o);for(const t of o)h(t,r,s);for(const t of e.children)u(t,r,s)},d=t.layers.mask;t.layers.enableAll();try{if(!l&&("all"===o||"globe"===o)){const t=null==(n=null==(s=e.globeManager)?void 0:s.tiles)?void 0:n.group;null==t||t.updateWorldMatrix(!0,!0),u(t,"globe",null)}if("globe"!==o)for(const t of(null==(a=e.content)?void 0:a.children)??[])!t.visible||l&&!l.has(t.contentLayerId)||("splats"!==o||t.isGaussianSplatLayer)&&(t.updateWorldMatrix(!0,!0),u(t,t.isGaussianSplatLayer?"splats":"content",t.contentLayerId??null))}finally{t.layers.mask=d}return c}const Cc=document.createElement("canvas");Cc.width=128,Cc.height=128;const Ec=Cc.getContext("2d"),Rc=Cc.width/2,Pc=Cc.height/2,Lc=Math.min(Cc.width,Cc.height)/2,Uc="0, 0, 0",Ic=Ec.createRadialGradient(Rc,Pc,0,Rc,Pc,Lc);Ic.addColorStop(0,`rgba(${Uc}, 1)`),Ic.addColorStop(.5,`rgba(${Uc}, 0.25)`),Ic.addColorStop(1,`rgba(${Uc}, 0)`),Ec.fillStyle=Ic,Ec.fillRect(0,0,Cc.width,Cc.height);const Fc={APPENDED:"viewer-appended",READY:"viewer-ready",ANIMATED:"viewer-animated",TRANSITIONED:"viewer-transitioned",CONTENT_LAYER_LOAD_START:"content-layer-load-start",CONTENT_LAYER_LOAD_PROGRESS:"content-layer-load-progress",CONTENT_LAYER_READY:"content-layer-ready",CONTENT_LAYER_ERROR:"content-layer-error"};exports.FullScreenQuad=gn,exports.Viewer=class extends p{constructor(e,t={}){super(),this.isViewer=!0,this.type="viewer",this.disposed=!1,this.sparkRenderer=null,this.transparentBackground=t.transparentBackground??!0,il.CESIUM=t.cesiumToken||void 0,il.GOOGLEMAPS=t.googleMapsToken||void 0,this.state=new T({time:{type:"f",value:0},loaded:!1,added:!1,ready:!1}),this.renderer=new i.WebGLRenderer({antialias:!0,powerPreference:"high-performance",alpha:this.transparentBackground,premultipliedAlpha:!0}),this.renderer.setClearColor(this.transparentBackground?0:16777215,this.transparentBackground?0:1),this.renderer.toneMapping=i.AgXToneMapping,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMappingExposure=1,this.renderer.supportedFloatType=this.renderer.getContext().getSupportedExtensions().indexOf("OES_texture_float_linear")>=0?i.FloatType:i.HalfFloatType,this.renderer.autoClear=!1,this.css2DRenderer=new h,this.css2DRenderer.domElement.style.setProperty("position","absolute"),this.css2DRenderer.domElement.style.setProperty("left","0"),this.css2DRenderer.domElement.style.setProperty("top","0"),this.css2DRenderer.domElement.style.setProperty("pointer-events","none"),this.clock=new i.Clock,this.camera=new i.PerspectiveCamera(90,1,10,1e8),this.camera.up.set(0,0,1),this.camera.position.fromArray(i.geodeticToEcefPosition(-105.18896,39.93,9e3)),this.camera.lookAt((new i.Vector3).fromArray(i.geodeticToEcefPosition(-105.18896,40,0))),this.cameraForward=new i.Vector3,this.cameraRight=new i.Vector3,this.cameraUp=new i.Vector3,this.scene=new i.Scene,this.content=new i.Group,this.scene.add(this.content),this.topLayerIndex=0,this.enabledLayers=[],this.labels=new Map,this.features=new Map,this.globeControls=new Fi(this.scene,this.camera,this.renderer.domElement),this.globeControls.enableDamping=!0,this._onGlobeControlsStart=()=>{this.transitionControls.cancel()},this.globeControls.addEventListener("start",this._onGlobeControlsStart),this.transitionControls=new cc(this.camera),this.tileDecoders=new Qs(this.renderer),this.globeManager=new Ko(this.scene,this.camera,this.renderer,{apiToken:il.CESIUM,googleMapsToken:il.GOOGLEMAPS,decoders:this.tileDecoders}),this.globeManager.tiles&&(this.globeManager.tiles.group.visible=!this.transparentBackground,this.globeControls.setTilesRenderer(this.globeManager.tiles)),this.camera.updateMatrixWorld(!0),this.cameraCoords=nc(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.pointerCoords={},this.pointerXYZ=new i.Vector3,this.keysDown={},this._keysEnabled=!0,this.movementSpeed=100,this.boostMultiplier=5,this.movementKeys={BOOST:["ShiftLeft","ShiftRight"],FRONT:["KeyW"],BACK:["KeyS"],LEFT:["KeyA"],RIGHT:["KeyD"],UP:["KeyE"],DOWN:["KeyQ"]},this.movementState={BOOST:!1,FRONT:!1,BACK:!1,LEFT:!1,RIGHT:!1,UP:!1,DOWN:!1},this._onKeyDown=e=>{e.repeat&&!this.keysDown[e.code]||(this.keysDown[e.code]=!0,this.updateMovementState())},this._onKeyUp=e=>{this.keysDown[e.code]=!1,this.updateMovementState()},this._onResize=e=>{this.resizeView(e)},window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),window.addEventListener("resize",this._onResize),e&&this.appendTo(e),this.sky=new hc,this.sky.scale.setScalar(2e7),this.sky.visible=!this.transparentBackground,this.scene.add(this.sky);const r=i.MathUtils.degToRad(80),s=i.MathUtils.degToRad(180),n=(new i.Vector3).setFromSphericalCoords(1,r,s);this.sky.material.uniforms.sunPosition.value=n,this.pointerRaycaster=new i.Raycaster,this._onPointerMove=e=>{if(!this.globeManager.tiles)return void(this.pointerCoords={});const t={};t.x=e.clientX/window.innerWidth*2-1,t.y=-e.clientY/window.innerHeight*2+1,this.pointerRaycaster.setFromCamera(t,this.camera);const r=this.pointerRaycaster.intersectObject(this.globeManager.tiles.group,!0);if(r.length>0){const e=r[0];e?(this.pointerCoords=i.ecefToGeodeticPosition(e.point.x,e.point.y,e.point.z),this.pointerXYZ.copy(e.point)):this.pointerCoords={}}else this.pointerCoords={}},window.addEventListener("pointermove",this._onPointerMove),this.setAnimate()}get keysEnabled(){return this._keysEnabled}set keysEnabled(e){if(e!==this._keysEnabled){this._keysEnabled=e,this.keysDown={};for(const e in this.movementState)this.movementState[e]=!1}}updateMovementState(){if(this.keysEnabled)for(const e in this.movementKeys){this.movementState[e]=!1;for(let t=0;t<this.movementKeys[e].length;t++){const r=this.movementKeys[e][t];if(this.keysDown[r]){this.movementState[e]=!0;break}}}}getElevation(e,t,r={}){i.validateGeodeticPosition(e,t,1e4,"Elevation query");const s=(new i.Vector3).fromArray(i.geodeticToEcefPosition(e,t,1e4)),n=ac(e,t).negate(),a=new i.Raycaster;a.ray.set(s,n);const o=this._raycastSurfaces(a,r);if(!o)throw new Error(`Elevation query found no loaded surface at ${e}, ${t}.`);const l=i.ecefToGeodeticPosition(o.point.x,o.point.y,o.point.z);return i.validateGeodeticPosition(l.lon,l.lat,l.alt,"Computed elevation"),{...l,source:o.source,layerId:o.layerId}}updateCoordsElevation(e){for(let t=0;t<e.length;t++){const[r,i]=e[t];e[t][2]=this.getElevation(r,i).alt}return e}setBackgroundColor(e){this.renderer.setClearColor(e,this.transparentBackground?0:1)}appendTo(e){this.container=e,this.container.appendChild(this.renderer.domElement),this.container.appendChild(this.css2DRenderer.domElement),this.resizeView(),this.state.update({added:!0}),this.dispatchEvent({type:Fc.APPENDED})}updateCameraDirections(){const e=new i.Matrix4;e.extractRotation(this.camera.matrixWorld),this.cameraForward.set(0,0,-1).applyMatrix4(e),this.cameraRight.set(1,0,0).applyMatrix4(e),this.cameraUp.set(0,1,0).applyMatrix4(e)}setAnimate(e=!0){e?this.renderer.setAnimationLoop(((e,t)=>{this.animate(e)})):this.renderer.setAnimationLoop(null)}resizeView(e){if(this.container){const e=this.container.offsetWidth,t=this.container.offsetHeight;this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t),this.css2DRenderer.setSize(e,t),this.renderer.render(this.scene,this.camera),this.css2DRenderer.render(this.scene,this.camera)}}async loadEnv(e){const t=await new ol(e,{floatType:this.renderer.supportedFloatType});t.mapping=i.EquirectangularReflectionMapping,this.scene.environment=t,this.scene.environmentRotation.set(Math.PI/2,0,0)}clearContentLayers(){for(var e;this.content.children.length>0;){const t=this.content.children[0];null==(e=t.dispose)||e.call(t),this.content.remove(t)}this.disposeSparkRenderer()}async ensureSparkRenderer(){if(this.sparkRenderer)return this.sparkRenderer;const e=this.sparkRendererGeneration??0,{SparkRenderer:t}=await d();return this.disposed||e!==(this.sparkRendererGeneration??0)?null:(this.sparkRenderer||(this.sparkRenderer=new t({renderer:this.renderer}),this.sparkRenderer.layers.set(0),this.scene.add(this.sparkRenderer)),this.sparkRenderer)}disposeSparkRenderer(){var e,t;this.sparkRendererGeneration=(this.sparkRendererGeneration??0)+1,this.sparkRenderer&&(this.sparkRenderer.removeFromParent(),null==(t=(e=this.sparkRenderer).clearSplats)||t.call(e),this.sparkRenderer.dispose(),this.sparkRenderer=null)}defineContentLayers(e=[]){var t,r,i;this.topLayerIndex=0,this.clearContentLayers();for(let n=0;n<e.length;n++){const a=e[n];try{const e="gaussian-splat"===(null==a?void 0:a.type)?wc(a):a;switch(this.topLayerIndex=Math.max(this.topLayerIndex,(null==(t=null==e?void 0:e.options)?void 0:t.renderOrder)??0),null==e?void 0:e.type){case"3d-tiles":{const t=new dc(e.data.url,{camera:this.camera,renderer:this.renderer,...e.options,decoders:this.tileDecoders},{onError:t=>this.dispatchEvent({type:Fc.CONTENT_LAYER_ERROR,layerId:e.id,error:t})});t.contentLayerId=e.id,t.setLabels(e.labels),null==(r=t.setTimeFrame)||r.call(t,this.timeFrameStart,this.timeFrameEnd),t.setEnabled(!1),this.content.add(t);break}case"mesh":{const t=new pc(e.data.url,{...e.options},{onError:t=>this.dispatchEvent({type:Fc.CONTENT_LAYER_ERROR,layerId:e.id,error:t})});t.contentLayerId=e.id,t.setLabels(e.labels),t.setEnabled(!1),this.content.add(t);break}case"geojson":{const t=new xc(e.data,e.options,{onError:t=>this.dispatchEvent({type:Fc.CONTENT_LAYER_ERROR,layerId:e.id,error:t})});t.contentLayerId=e.id,t.setLabels(e.labels),null==(i=t.setTimeFrame)||i.call(t,this.timeFrameStart,this.timeFrameEnd),t.setEnabled(!1),this.content.add(t);break}case"gaussian-splat":{const t=new Sc(e,{ensureRenderer:()=>this.ensureSparkRenderer(),onStart:e=>this.dispatchEvent({type:Fc.CONTENT_LAYER_LOAD_START,layerId:e.contentLayerId}),onProgress:(e,t)=>this.dispatchEvent({type:Fc.CONTENT_LAYER_LOAD_PROGRESS,layerId:e.contentLayerId,progress:t}),onReady:e=>this.dispatchEvent({type:Fc.CONTENT_LAYER_READY,layerId:e.contentLayerId}),onError:(e,t)=>this.dispatchEvent({type:Fc.CONTENT_LAYER_ERROR,layerId:e.contentLayerId,error:t})});this.content.add(t);break}default:throw new Error(`Unsupported content layer type: ${String(null==e?void 0:e.type)}`)}}catch(s){this.dispatchEvent({type:Fc.CONTENT_LAYER_ERROR,layerId:"string"==typeof(null==a?void 0:a.id)&&a.id.length>0?a.id:null,error:s instanceof Error?s:new Error(String(s))})}}this.globeControls.pivotMesh.layers.set(this.topLayerIndex),this.enableContentLayers(this.enabledLayers)}enableContentLayers(e=[]){this.enabledLayers=e;for(let t=0;t<this.content.children.length;t++){const r=this.content.children[t];let i=!1;for(let t=0;t<e.length;t++){const s=e[t];if(r.labels.has(s)){i=!0;break}}r.setEnabled(i)}}setTimeFrame(e,t){var r;this.timeFrameStart=e?new Date(e):null,this.timeFrameEnd=t?new Date(t):null;for(let i=0;i<this.content.children.length;i++){const e=this.content.children[i];null==(r=e.setTimeFrame)||r.call(e,this.timeFrameStart,this.timeFrameEnd)}}updateLabel(e,t){var r,n;const{longitude:a,latitude:o,altitude:l}=i.validateGeodeticPosition(null==t?void 0:t.lon,null==t?void 0:t.lat,null==t?void 0:t.alt,"Label position"),c=t.visible??!0,h=t.hovered??!1,u=t.selected??!1;let d=null;if(this.labels.has(e))d=this.labels.get(e);else{const r=t.element??document.createElement("div");d=new s(r);const n=new i.Mesh(new i.PlaneGeometry(1e3,1e3),new i.MeshBasicMaterial({map:new i.CanvasTexture(Cc),opacity:1,transparent:!0,side:i.DoubleSide}));n.layers.set(this.topLayerIndex),d.add(n),d.lookAt(0,0,0),this.scene.add(d),this.labels.set(e,d)}return t.element&&t.element!==d.element&&(null==(n=(r=d.element).remove)||n.call(r),d.element=new s(t.element).element),d.position.fromArray(i.geodeticToEcefPosition(a,o,l)),d.lookAt(0,0,0),d.visible=c,h?d.element.classList.add("hovered"):d.element.classList.remove("hovered"),u?d.element.classList.add("selected"):d.element.classList.remove("selected"),d.element}animate(e){this.stats&&this.stats.begin(),this.transitionControls.update(e),this.state.get("time").value=e;const t=this.clock.getDelta();this.globeControls.update(),this.camera.updateMatrixWorld(),this.updateCameraDirections(),this.cameraCoords=nc(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.sky.setSurfaceUp(ac(this.cameraCoords.lon,this.cameraCoords.lat)),this.keysEnabled&&function(e,t,r,i,s,n,a,o){const l=a*n*(s.BOOST?o:1);s.FRONT&&e.addScaledVector(t,l),s.BACK&&e.addScaledVector(t,-l),s.LEFT&&e.addScaledVector(r,-l),s.RIGHT&&e.addScaledVector(r,l),s.UP&&e.addScaledVector(i,l),s.DOWN&&e.addScaledVector(i,-l)}(this.camera.position,this.cameraForward,this.cameraRight,this.cameraUp,this.movementState,t,this.movementSpeed,this.boostMultiplier),this.globeManager.update();for(let r=0;r<this.content.children.length;r++){this.content.children[r].update()}for(const[r,s]of this.labels)if(s.element){s.element.classList.remove("far"),s.element.classList.remove("mid"),s.element.classList.remove("close");const e=(new i.Vector3).subVectors(s.position,this.camera.position).dot(this.cameraForward);s.scale.setScalar(e/1e4),s.children[0].material.opacity=Math.min(Math.max(1-e/2e3,.1),1),e>3200?s.element.classList.add("far"):e>1e3?s.element.classList.add("mid"):s.element.classList.add("close")}for(let r=0;r<this.topLayerIndex+1;r++)this.camera.layers.set(r),0==r?(this.renderer.clear(),this.render()):(this.renderer.clearDepth(),this.renderer.render(this.scene,this.camera));this.cameraCoords=nc(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.dispatchEvent({type:Fc.ANIMATED,time:e,deltaTime:t}),this.stats&&this.stats.end()}render(){this.renderer.render(this.scene,this.camera),this.css2DRenderer.render(this.scene,this.camera),!0===this.state.get("added")&&!1===this.state.get("ready")&&(this.state.update({ready:!0}),window.setTimeout((()=>{this.dispatchEvent({type:Fc.READY})}),0))}pickCoordinates(e,t,r={}){var s;const n=null==(s=this.renderer)?void 0:s.domElement.getBoundingClientRect();if(!n||n.width<=0||n.height<=0||!Number.isFinite(e)||!Number.isFinite(t)||e<n.left||e>n.right||t<n.top||t>n.bottom)return null;this.pickRaycaster??(this.pickRaycaster=new i.Raycaster),this.camera.updateMatrixWorld(),this.pickRaycaster.setFromCamera({x:(e-n.left)/n.width*2-1,y:-(t-n.top)/n.height*2+1},this.camera);const a=this._raycastSurfaces(this.pickRaycaster,r);if(!a)return null;const o=i.ecefToGeodeticPosition(a.point.x,a.point.y,a.point.z);return i.validateGeodeticPosition(o.lon,o.lat,o.alt,"Picked coordinates"),{...o,point:a.point.clone(),source:a.source,layerId:a.layerId}}_raycastSurfaces(e,t){return Ac(this,e,t)}getCameraPivot(){let e=null;const t=new i.Raycaster;if(t.setFromCamera({x:0,y:0},this.camera),this.globeManager.tiles){const r=t.intersectObject(this.globeManager.tiles.group,!0);if(r.length>0){const t=r[0];t&&(e=t.point.clone())}}return e||(e=(new i.Vector3).subVectors(this.camera.position,this.cameraForward.clone().multiplyScalar(2e3))),e}async alignCamera(e,t,r,s,n,a,o){const l=i.validateGeodeticPosition(e,t,r,"Camera position"),c=i.validateRotation(s??this.cameraCoords.pitch,n??this.cameraCoords.yaw,a??this.cameraCoords.roll,"Camera rotation"),h=i.requireFiniteNumber(o??sl,"Camera transition duration"),u=(new i.Vector3).fromArray(i.geodeticToEcefPosition(l.longitude,l.latitude,l.altitude)),d=oc(l.longitude,l.latitude,c.pitch,c.yaw,c.roll);return this.transitionControls.animateTo(u,d,h).then((i=>{i&&this.dispatchEvent({type:Fc.TRANSITIONED,lon:e,lat:t,alt:r,...c})}))}async focusCamera(e,t,r,s,n,a){const o=i.validateGeodeticPosition(e,t,r,"Camera focus"),l=i.requireFiniteNumber(s??2e3,"Camera focus distance"),c=i.validateRotation(n??this.cameraCoords.pitch,0,0,"Camera rotation"),h=i.requireFiniteNumber(a??sl,"Camera transition duration"),u=(new i.Vector3).fromArray(i.geodeticToEcefPosition(o.longitude,o.latitude,o.altitude)),d=oc(o.longitude,o.latitude,c.pitch,c.yaw,c.roll),p=new i.Vector3(0,0,1).applyQuaternion(d);return u.addScaledVector(p,l),this.transitionControls.animateTo(u,d,h).then((i=>{i&&this.dispatchEvent({type:Fc.TRANSITIONED,lon:e,lat:t,alt:r})}))}async angleCamera(e,t,r){const s=i.validateRotation(e??this.cameraCoords.pitch,t??this.cameraCoords.yaw,0,"Camera rotation"),n=i.requireFiniteNumber(r??sl,"Camera transition duration"),a=this.getCameraPivot(),{lon:o,lat:l,alt:c}=i.ecefToGeodeticPosition(a.x,a.y,a.z),h=this.camera.position.distanceTo(a),u=(new i.Vector3).fromArray(i.geodeticToEcefPosition(o,l,c)),d=oc(o,l,s.pitch,s.yaw,s.roll),p=new i.Vector3(0,0,1).applyQuaternion(d);return u.addScaledVector(p,h),this.transitionControls.animateTo(u,d,n).then((e=>{e&&this.dispatchEvent({type:Fc.TRANSITIONED,lon:o,lat:l,alt:c})}))}setViewMode(e="3d"){return"3d"==e?(this.globeControls.rotationSpeed=1,this.angleCamera(-60,void 0,500)):(this.globeControls.rotationSpeed=0,this.angleCamera(-90,0,500))}exportScene(){return e=this.scene,void(new dl).parse(e,(e=>{const t=new Blob([e],{type:"application/octet-stream"}),r=URL.createObjectURL(t),i=document.createElement("a");i.href=r,i.download="scene.glb",document.body.appendChild(i),i.click(),document.body.removeChild(i)}),(e=>{}),{binary:!0});var e}saveScreenshot(e="screenshot"){for(let i=0;i<this.topLayerIndex+1;i++)this.camera.layers.set(i),0==i?(this.renderer.clear(),this.render()):(this.renderer.clearDepth(),this.renderer.render(this.scene,this.camera));const t=this.renderer.domElement.toDataURL(),r=document.createElement("a");r.setAttribute("href",t),r.setAttribute("target","_blank"),r.setAttribute("download",`${e}.png`),r.click()}dispose(){var e,t,r,i,s,n,a,o,l,c,h,u,d,p,m;if(!this.disposed){this.disposed=!0,this.setAnimate(!1),this.transitionControls.cancel(),this.clearContentLayers(),window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("resize",this._onResize),window.removeEventListener("pointermove",this._onPointerMove),this.globeControls.removeEventListener("start",this._onGlobeControlsStart),this.globeControls.dispose(),this.globeManager.dispose(),this.tileDecoders.dispose();for(const e of this.labels.values())e.traverse((e=>{var t,r,i,s,n;if(null==(r=null==(t=e.geometry)?void 0:t.dispose)||r.call(t),e.material){const t=Array.isArray(e.material)?e.material:[e.material];for(const e of t)null==(s=null==(i=e.map)?void 0:i.dispose)||s.call(i),null==(n=e.dispose)||n.call(e)}})),e.removeFromParent();this.labels.clear(),this.features.clear(),null==(t=null==(e=this.scene.environment)?void 0:e.dispose)||t.call(e),this.scene.environment=null,null==(s=null==(i=null==(r=this.sky)?void 0:r.geometry)?void 0:i.dispose)||s.call(i),null==(o=null==(a=null==(n=this.sky)?void 0:n.material)?void 0:a.dispose)||o.call(a),null==(l=this.sky)||l.removeFromParent(),null==(h=null==(c=this.stats)?void 0:c.dom)||h.remove(),this.css2DRenderer.domElement.remove(),this.renderer.domElement.remove(),null==(d=null==(u=this.renderer.renderLists)?void 0:u.dispose)||d.call(u),this.renderer.dispose(),null==(m=(p=this.renderer).forceContextLoss)||m.call(p),this.container=null,this.listeners={}}}},exports.ViewerEvents=Fc;