@splnlss/3d-story-viewer 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/assets/viewer/{geojson.worker-QNi-d8kU.js → geojson.worker-D3uq_RbR.js} +1 -1
- package/build/assets/viewer/spark-a62bdfe36d20.wasm +0 -0
- package/build/assets/viewer/{spark-worker-5ec8a483b87c.js → spark-worker-c1a6c013b888.js} +194 -43
- package/build/computeElevation.cjs +1 -1
- package/build/computeElevation.js +2 -2
- package/build/index-D87IZDc6.cjs +1 -0
- package/build/{index-CsZhc21b.js → index-Hz3jbrou.js} +1302 -829
- package/build/main-Bdopx4KL.js +15819 -0
- package/build/main-CaYKxosA.cjs +1 -0
- package/build/spark.module-B1FWS-vq.js +18168 -0
- package/build/spark.module-BUdzSHba.cjs +1 -0
- package/build/types/src/viewer/ContentLayer/GaussianSplatLayer.d.ts +4 -6
- package/build/types/src/viewer/ContentLayer/MeshLayer.d.ts +1 -1
- package/build/types/src/viewer/ContentLayer/TilesLayer.d.ts +4 -2
- package/build/types/src/viewer/ContentLayer/gaussianSplatUtils.d.ts +2 -1
- package/build/types/src/viewer/ContentLayer/index.d.ts +5 -3
- package/build/types/src/viewer/EnvironmentControls.d.ts +18 -12
- package/build/types/src/viewer/GlobeControls.d.ts +9 -6
- package/build/types/src/viewer/GlobeManager.d.ts +2 -1
- package/build/types/src/viewer/Sky.d.ts +5 -2
- package/build/types/src/viewer/TransitionControls.d.ts +2 -1
- package/build/types/src/viewer/index.d.ts +48 -18
- package/build/types/src/viewer/loadSpark.d.ts +1 -0
- package/build/types/src/viewer/mods.d.ts +1 -0
- package/build/types/src/viewer/shaders/chunks.d.ts +1 -0
- package/build/types/src/viewer/surfacePicking.d.ts +31 -0
- package/build/types/src/viewer/utils.d.ts +6 -4
- package/build/types/src/workers/geojson.worker.d.ts +2 -2
- package/build/types/utils/elevation/gltf.d.ts +2 -1
- package/build/viewer.cjs +1 -1
- package/build/viewer.js +5 -28044
- package/package.json +18 -16
- package/build/assets/viewer/spark-8b93f8c03d97.wasm +0 -0
- package/build/assets/viewer/spark-old-worker-932b4a2c87ca.js +0 -8168
- package/build/assets/viewer/spark-worker-015de49d2d00.wasm +0 -0
- package/build/index-wUFLgXbb.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e,t=Object.defineProperty,i=(e,i,r)=>((e,i,r)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[i]=r)(e,"symbol"!=typeof i?i+"":i,r);const r=require("./index-D87IZDc6.cjs");r.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",r.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",r.ShaderChunk.bayer_dither_hash_pars_vertex="#ifdef USE_HASH\nvarying float vCameraDistance;\n#endif\n",r.ShaderChunk.bayer_dither_hash_vertex="#ifdef USE_HASH\nvCameraDistance=-mvPosition.z;\n#endif\n";class s extends r.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 r.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 r.Vector3,a=new r.Matrix4,o=new r.Matrix4,l=new r.Vector3,c=new r.Vector3;class h{constructor(e={}){const t=this;let i,r,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,i=e.children.length;t<i;t++)p(e.children[t])}function m(e,i,r){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(r.layers),l=e.element;if(l.style.display=!0===a?"":"none",!0===a){e.onBeforeRender(t,i,r);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,i,r)}const c={distanceToCameraSquared:f(r,e)};u.objects.set(e,c)}for(let t=0,s=e.children.length;t<s;t++)m(e.children[t],i,r)}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:i,height:r}},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})),i=t.length;for(let r=0,s=t.length;r<s;r++)t[r].element.style.zIndex=i-r}(e)},this.setSize=function(e,t){i=e,r=t,s=i/2,h=r/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-BUdzSHba.cjs"))).catch((e=>{throw u=null,e}))),u}class p{constructor(){this.listeners={}}addEventListener(e,t){const i=this.listeners;void 0===i[e]&&(i[e]=[]),-1===i[e].indexOf(t)&&i[e].push(t)}hasEventListener(e,t){const i=this.listeners;return void 0!==i[e]&&-1!==i[e].indexOf(t)}removeEventListener(e,t){const i=this.listeners[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this.listeners[e.type];if(void 0!==t){e.target=this;const i=t.slice(0);for(let t=0,r=i.length;t<r;t+=1)i[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 i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let s of i)if(!r.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 i={};for(const r in e)if(Object.hasOwnProperty.call(e,r)){const s=e[r];Object.hasOwnProperty.call(this.initialValues,r)?t&&(this.initialValues[r]=s,this.values[r]=s,i[r]=s):(this.initialValues[r]=s,this.values[r]=s,i[r]=s)}return m(i)||this.dispatchEvent({type:g,values:i}),i}update(e={},t={}){let i={};const r={},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||(r[a]=this.values[a],n||(this.values[a]=t),i[a]=t))}return n||m(i)||this.dispatchEvent({type:y,values:this.values,changes:i,before:r}),i}get(e){let t={};if(e){Array.isArray(e)||(e=[e]);for(let i=0;i<e.length;i++){const r=e[i];Object.hasOwnProperty.call(this.values,r)&&(t[r]=this.values[r])}}else t={...this.values};return 1==e.length?t[e[0]]:t}reset(e){const t={},i={};if(e){Array.isArray(e)||(e=[e]);for(let r=0;r<e.length;r++){const s=e[r];Object.hasOwnProperty.call(this.initialValues,s)&&(i[s]=this.values[s],this.values[s]=this.initialValues[s],t[s]=this.initialValues[s])}}else for(const r in this.initialValues)Object.hasOwnProperty.call(this.initialValues,r)&&(this.values[r]=this.initialValues[r],t[r]=this.initialValues[r]);return m(t)||this.dispatchEvent({type:y,values:this.values,changes:t,before:i}),t}delete(e=[]){const t={};Array.isArray(e)||(e=[e]);for(let i=0;i<e.length;i++){const r=e[i];Object.hasOwnProperty.call(this.values,r)&&(t[r]=this.values[r],delete this.values[r],delete this.initialValues[r])}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 r.Mesh{constructor(){super(new r.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 r.ShaderMaterial{constructor(){super({depthWrite:!1,depthTest:!1,transparent:!0,uniforms:{resolution:{value:new r.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 r.Vector2,w=new r.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 r.Vector2,this.hoverSet=!1}reset(){this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new r.Vector2,this.hoverSet=!1}updateFrame(){const{previousPositions:e,pointerPositions:t}=this;for(const i in t)e[i].copy(t[i])}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 i=(this.domElement?this.domElement:e.target).getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top;t.set(r,s)}addPointer(e){const t=e.pointerId,i=new r.Vector2;this.getAdjustedPointer(e,i),this.pointerOrder.push(t),this.pointerPositions[t]=i,this.previousPositions[t]=i.clone(),this.startPositions[t]=i.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,i=this.pointerOrder;i.splice(i.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 i=this.pointerOrder;if(1===this.getPointerCount()||"mouse"===this.getPointerType()){const r=i[0];return e.copy(t[r]),e}if(2===this.getPointerCount()){const i=this.pointerOrder[0],r=this.pointerOrder[1],s=t[i],n=t[r];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,i=t[0],r=t[1],s=e[i],n=e[r];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 r.Matrix4;function A(e,t,i){return i.makeTranslation(-e.x,-e.y,-e.z),S.makeRotationFromQuaternion(t),i.premultiply(S),S.makeTranslation(e.x,e.y,e.z),i.premultiply(S),i}function C(e,t,i){i.x=e.x/t.clientWidth*2-1,i.y=-e.y/t.clientHeight*2+1,i.isVector3&&(i.z=0)}function E(e,t,i){const s=e instanceof r.Ray?e:e.ray,{origin:n,direction:a}=s;n.set(t.x,t.y,-1).unproject(i),a.set(t.x,t.y,1).unproject(i).sub(n),e.isRay||(e.near=0,e.far=a.length(),e.camera=i),a.normalize()}const R=.05,P=.025,L=new r.Matrix4,U=new r.Matrix4,I=new r.Vector3,F=new r.Vector3,k=new r.Vector3,D=new r.Vector3,O=new r.Vector3,B=new r.Vector3,N=new r.Vector3,V=new r.Vector3,z=new r.Quaternion,G=new r.Plane,H=new r.Vector3,j=new r.Vector3,W=new r.Vector3,q=new r.Quaternion,X=new r.Ray,K=new r.Vector2,Y=new r.Vector2,Q=new r.Vector2,$=new r.Vector2,Z=new r.Vector2,J=new r.Vector2,ee={type:"change"},te={type:"start"},ie={type:"end"};class re extends r.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,i=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 r.Plane(new r.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 r.Vector3,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.zoomDirection=new r.Vector3,this.zoomPoint=new r.Vector3,this.zoomDelta=0,this.rotationInertiaPivot=new r.Vector3,this.rotationInertia=new r.Vector2,this.dragInertia=new r.Vector3,this.inertiaTargetDistance=1/0,this.inertiaStableFrames=0,this.pivotMesh=new x,this.pivotMesh.raycast=()=>{},this.pivotMesh.scale.setScalar(.25),this.raycaster=new r.Raycaster,this.raycaster.firstHitOnly=!0,this.up=new r.Vector3(0,1,0),this.clock=new r.Clock,this._detachCallback=null,this._upInitialized=!1,this._lastUsedState=0,this._zoomPointWasSet=!1,this._tilesOnChangeCallback=()=>this.zoomPointSet=!1,i&&this.attach(i),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()},i=e=>{if(!this.enabled)return;e.preventDefault();const{camera:t,raycaster:i,domElement:r,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())r.setPointerCapture(e.pointerId);else if(a.getPointerCount()>2)return void this.resetState();a.getCenterPoint(Y),C(Y,r,Y),E(i,Y,t);const h=Math.abs(i.ray.direction.dot(s));if(h<R||h<P)return;const u=this._raycast(i);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 r=!1;const s=e=>{const{pointerTracker:t}=this;if(!this.enabled)return;e.preventDefault();const{pivotMesh:i,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()&&(r||(r=!0,queueMicrotask((()=>{r=!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,i=Z.distanceTo(J);(Math.abs(a)>e||i>e)&&(Math.abs(a)>i?(this.setState(3),this.zoomDirectionSet=!1):this.setState(2))}if(3===this.state){const e=t.getPreviousTouchPointerDistance();this.zoomDelta+=n-e,i.visible=!1}else 2===this.state&&(i.visible=s)})))),this.dispatchEvent(ee))},n=t=>{const{pointerTracker:i}=this;this.enabled&&0!==i.getPointerCount()&&(i.deletePointer(t),"touch"===i.getPointerType()&&0===i.getPointerCount()&&e.releasePointerCapture(t.pointerId),this.resetState(),this.needsUpdate=!0)},a=e=>{if(!this.enabled)return;e.preventDefault();const{pointerTracker:t}=this;let i;switch(t.setHoverEvent(e),t.updatePointer(e),this.dispatchEvent(te),e.deltaMode){case 2:i=800*e.deltaY;break;case 1:i=40*e.deltaY;break;case 0:i=e.deltaY}const r=Math.sign(i),s=Math.abs(i);this.zoomDelta-=.25*r*s,this.needsUpdate=!0,this._lastUsedState=3,this.dispatchEvent(ie)},o=e=>{this.enabled&&this.resetState()};e.addEventListener("contextmenu",t),e.addEventListener("pointerdown",i),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",i),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:i,raycaster:r}=this;null!==t&&(F.copy(t).project(i),(F.x<-1||F.x>1||F.y<-1||F.y>1)&&(t=null)),E(r,{x:0,y:0},i);const s=this._raycast(r);return s&&(null===t||s.distance<t.distanceTo(r.ray.origin))&&(t=e.copy(s.point)),t}resetState(){0!==this.state&&this.dispatchEvent(ie),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:i,pivotPoint:r,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 i=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(r).sub(t.position).dot(O)):0===n&&this._updateInertia(e),(0!==n||0!==i||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),r.addScaledVector(s,-e),h&&(h.distance-=e)}if(this.actionHeightOffset=0,h){const e=h.distance;if(e<i){const n=i-e;t.position.addScaledVector(s,n),r.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:i}=this;if(e.isPerspectiveCamera){this.getUpDirection(e.position,H);const r=t&&this._getPointBelowCamera(e.position,H)||null;if(r){const t=r.distance;t<i&&e.position.addScaledVector(H,i-t)}}}dispose(){this.detach()}_updateInertia(e){const{rotationInertia:t,pivotPoint:i,dragInertia:r,enableDamping:s,dampingFactor:n,camera:a,cameraRadius:o,minDistance:l,inertiaTargetDistance:c}=this;if(!this.enableDamping||this.inertiaStableFrames>1)return r.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(i).normalize(),I.sub(i).normalize();const r=F.angleTo(I)/e;t.multiplyScalar(h),(t.lengthSq()<r**2||!s)&&t.set(0,0)}if(r.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;r.multiplyScalar(h),(r.lengthSq()<t**2||!s)&&r.set(0,0,0)}t.lengthSq()>0&&this._applyRotation(t.x*e,t.y*e,i),r.lengthSq()>0&&(a.position.addScaledVector(r,e),a.updateMatrixWorld())}_inertiaNeedsUpdate(){const{rotationInertia:e,dragInertia:t}=this;return 0!==e.lengthSq()||0!==t.lengthSq()}_updateZoom(){const{zoomPoint:e,zoomDirection:t,camera:i,minDistance:r,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),i.isOrthographicCamera){this._updateZoomDirection();const e=this.zoomPointSet||this._updateZoomPoint();j.unproject(i);const t=Math.pow(.95,Math.abs(.05*u));let r=u>0?1/Math.abs(t):t;r*=c,r>1?l<i.zoom*r&&(r=1):o>i.zoom*r&&(r=1),i.zoom*=r,i.updateProjectionMatrix(),e&&(C(Y,a,W),W.unproject(i),i.position.sub(W).add(j),i.updateMatrixWorld())}else{this._updateZoomDirection();const n=F.copy(t);if(this.zoomPointSet||this._updateZoomPoint()){const n=e.distanceTo(i.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-r);u=u*Math.max(n-r,0)*c*.0025,u=Math.min(u,e)}i.position.addScaledVector(t,u),i.updateMatrixWorld()}else{const e=this._getPointBelowCamera();if(e){const t=e.distance;n.set(0,0,-1).transformDirection(i.matrixWorld),i.position.addScaledVector(n,u*t*.01),i.updateMatrixWorld()}}}}_updateZoomDirection(){if(this.zoomDirectionSet)return;const{domElement:e,raycaster:t,camera:i,zoomDirection:r,pointerTracker:s}=this;s.getLatestPoint(Y),C(Y,e,j),E(t,j,i),r.copy(t.ray.direction).normalize(),this.zoomDirectionSet=!0}_updateZoomPoint(){const{camera:e,zoomDirectionSet:t,zoomDirection:i,raycaster:r,zoomPoint:s,pointerTracker:n,domElement:a}=this;if(this._zoomPointWasSet=!1,!t)return!1;e.isOrthographicCamera&&n.getLatestPoint(K)?(C(K,a,K),E(r,K,e)):(r.ray.origin.copy(e.position),r.ray.direction.copy(i),r.near=0,r.far=1/0);const o=this._raycast(r);return!!o&&(s.copy(o.point),this.zoomPointSet=!0,this._zoomPointWasSet=!0,!0)}_getPointBelowCamera(e=this.camera.position,t=this.up){const{raycaster:i}=this;i.ray.direction.copy(t).multiplyScalar(-1),i.ray.origin.copy(e).addScaledVector(t,1e5),i.near=0,i.far=1/0;const r=this._raycast(i);return r&&(r.distance-=1e5),r}_updatePosition(e){const{raycaster:t,camera:i,pivotPoint:r,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,r),E(t,Y,i),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(r,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(r,F),i.position.add(I),i.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:i,domElement:r,state:s,rotationInertia:n}=this;2===s&&(i.getCenterPoint(Y),i.getPreviousCenterPoint(Q),$.subVectors(Y,Q).multiplyScalar(2*Math.PI/r.clientHeight),this._applyRotation($.x,$.y,t),$.multiplyScalar(1/e),i.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(n.copy($),this.inertiaStableFrames=0))}_applyRotation(e,t,i){if(0===e&&0===t)return;const{camera:r,minAltitude:s,maxAltitude:n,rotationSpeed:a}=this,o=-e*a;let l,c=t*a;if(O.set(0,0,1).transformDirection(r.matrixWorld),B.set(1,0,0).transformDirection(r.matrixWorld),this.getUpDirection(i,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(i,z,L),r.matrixWorld.premultiply(L),B.set(1,0,0).transformDirection(r.matrixWorld),z.setFromAxisAngle(B,-c),A(i,z,L),r.matrixWorld.premultiply(L),r.matrixWorld.decompose(r.position,r.quaternion,F)}_setFrame(e){const{up:t,camera:i,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=r.MathUtils.mapLinear(e,0,.5,0,1),e=Math.min(e,1),i.isOrthographicCamera&&(e*=.1),z.slerp(q,1-e)}A(s,z,L),i.updateMatrixWorld(),i.matrixWorld.premultiply(L),i.matrixWorld.decompose(i.position,i.quaternion,F),this.zoomDirectionSet=!1,this._updateZoomDirection()}t.copy(e),i.updateMatrixWorld()}_raycast(e){const{scene:t,useFallbackPlane:i,fallbackPlane:r}=this,s=e.intersectObject(t)[0]||null;if(s)return s;if(i){const t=r;if(e.ray.intersectPlane(t,F)){return{point:F.clone(),distance:e.ray.origin.distanceTo(F)}}}return null}_alignCameraUp(e,t=1){const{camera:i,state:s,pivotPoint:n,zoomPoint:a,zoomPointSet:o}=this;i.updateMatrixWorld(),O.set(0,0,-1).transformDirection(i.matrixWorld),B.set(-1,0,0).transformDirection(i.matrixWorld);let l=r.MathUtils.mapLinear(1-Math.abs(O.dot(e)),0,.2,0,1);l=r.MathUtils.clamp(l,0,1),t*=l,N.crossVectors(e,O),N.lerp(B,1-t).normalize(),z.setFromUnitVectors(B,N),i.quaternion.premultiply(z);let c=null;1===s||2===s?c=k.copy(n):o&&(c=k.copy(a)),c&&(U.copy(i.matrixWorld).invert(),F.copy(c).applyMatrix4(U),i.updateMatrixWorld(),F.applyMatrix4(i.matrixWorld),D.subVectors(c,F),i.position.add(D)),i.updateMatrixWorld()}_clampRotation(e){const{camera:t,minAltitude:i,maxAltitude:r,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>r)c=r;else{if(!(l<i))return;c=i}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,i=e.indexOf("?"),r=e.indexOf("#");-1!==i&&(t=Math.min(t,i)),-1!==r&&(t=Math.min(t,r));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=(i(e=class{static setXRSession(e){e!==this.session&&(this.flushPending(),this.session=e)}static requestAnimationFrame(e){let t,{session:i,pending:r}=this,s=()=>{r.delete(t),e()};return t=i?i.requestAnimationFrame(s):requestAnimationFrame(s),r.set(t,e),t}static cancelAnimationFrame(e){let{pending:t,session:i}=this;t.delete(e),i?i.cancelAnimationFrame(e):cancelAnimationFrame(e)}static flushPending(){this.pending.forEach(((e,t)=>{e(),this.cancelAnimationFrame(t)}))}},"pending",new Map),i(e,"session",null),e),ae=2**30,oe=class{get unloadPriorityCallback(){return this._unloadPriorityCallback}set unloadPriorityCallback(e){1===e.length?this._unloadPriorityCallback=(t,i)=>{let r=e(t),s=e(i);return r<s?-1:+(r>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:i,itemSet:r}=this;r.has(e)&&(this.cachedBytes-=i.get(e)||0,i.set(e,t),this.cachedBytes+=t)}add(e,t){let i=this.itemSet;if(i.has(e)||this.isFull())return!1;let r=this.usedSet,s=this.itemList,n=this.callbacks;return s.push(e),r.add(e),i.set(e,Date.now()),n.set(e,t),!0}has(e){return this.itemSet.has(e)}remove(e){let t=this.usedSet,i=this.itemSet,r=this.itemList,s=this.bytesMap,n=this.callbacks,a=this.loadedSet;if(i.has(e)){this.cachedBytes-=s.get(e)||0,s.delete(e),n.get(e)(e);let o=r.indexOf(e);return r.splice(o,1),t.delete(e),i.delete(e),n.delete(e),a.delete(e),!0}return!1}setLoaded(e,t){let{itemSet:i,loadedSet:r}=this;i.has(e)&&(!0===t?r.add(e):r.delete(e))}markUsed(e){let t=this.itemSet,i=this.usedSet;t.has(e)&&!i.has(e)&&(t.set(e,Date.now()),i.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:i,itemList:r,itemSet:s,usedSet:n,loadedSet:a,callbacks:o,bytesMap:l,minBytesSize:c,maxBytesSize:h}=this,u=r.length-n.size,d=r.length-a.size,p=Math.max(Math.min(r.length-t,u),0),m=this.cachedBytes-c,f=this.unloadPriorityCallback||this.defaultPriorityCallback,g=!1,y=p>0&&u>0||d&&r.length>i;if(u&&this.cachedBytes>c||d&&this.cachedBytes>h||y){r.sort(((e,t)=>{let i=n.has(e);if(i===n.has(t)){let i=a.has(e);return i===a.has(t)?-f(e,t):i?1:-1}return i?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||r.length-x>i;){let e=r[x],t=l.get(e)||0;if(n.has(e)&&a.has(e)||this.cachedBytes-b-t<h&&r.length-x<=i)break;b+=t,x++}for(;b<T||x<y;){let e=r[x],t=l.get(e)||0;if(n.has(e)||this.cachedBytes-b-t<c&&x>=y)break;b+=t,x++}r.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 i={callback:t,reject:null,resolve:null,promise:null};return i.promise=new Promise(((t,r)=>{let s=this.items,n=this.callbacks;i.resolve=t,i.reject=r,s.unshift(e),n.set(e,i),this.autoUpdate&&this.scheduleJobRun()})),i.promise}remove(e){let t=this.items,i=this.callbacks,r=t.indexOf(e);if(-1!==r){let s=i.get(e);s.promise.catch((e=>{if("AbortError"!==e.name)throw e})),s.reject(new le),t.splice(r,1),i.delete(e)}}removeByFilter(e){let{items:t}=this;for(let i=0;i<t.length;i++){let r=t[i];e(r)&&(this.remove(r),i--)}}tryRunJobs(){this.sort();let e=this.items,t=this.callbacks,i=this.maxJobs,r=0,s=()=>{this.currJobs--,this.autoUpdate&&this.scheduleJobRun()};for(;i>this.currJobs&&e.length>0&&r<i;){this.currJobs++,r++;let i,a=e.pop(),{callback:o,resolve:l,reject:c}=t.get(a);t.delete(a);try{i=o(a)}catch(n){c(n),s();continue}i instanceof Promise?i.then(l).catch(c).finally(s):(l(i),s())}}flush(e){let{items:t,callbacks:i}=this,r=t.indexOf(e);if(!i.has(e))return;let s,{callback:n,resolve:a,reject:o}=i.get(e);i.delete(e),t.splice(r,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,i=0===t.length||me(t[t.length-1]),r=!e.internal.hasUnrenderableContent||de(e.internal.loadingState);return i&&r}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,i=!1){if(ye(e,t),i?t.markTileUsed(e):xe(e),ge(e)&&fe(e)){let r=e.children;for(let e=0,s=r.length;e<s;e++)ve(r[e],t,i)}}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 i=e.children;for(let e=0,r=i.length;e<r;e++)Te(i[e],t)}}function xe(e){e.traversal.used=!0}function be(e,t){let{frameCount:i}=t,{children:r}=e;for(let s=0,n=r.length;s<n;s++){let e=r[s];pe(e,i)&&(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 i=e.parent;if(i&&"ADD"===i.refine&&e.geometricError>0&&e.traversal.error*(i.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 r=!1,s=!1,n=e.children;for(let a=0,o=n.length;a<o;a++){let e=n[a];we(e,t),r||(r=pe(e,t.frameCount)),s||(s=e.traversal.inFrustum)}if("REPLACE"!==e.refine||s||0===n.length){if(xe(e),"REPLACE"===e.refine&&r&&(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,i=n.length;e<i;e++)ve(n[e],t,!0)}}function Me(e,t){let i=t.frameCount;if(!pe(e,i))return;let r=e.children,s=!1;for(let a=0,o=r.length;a<o;a++){let e=r[a];s||(s=pe(e,i))}if(s){for(let e=0,i=r.length;e<i;e++)Me(r[e],t);let s=!0;for(let e=0,t=r.length;e<t;e++){let t=r[e];if(pe(t,i)){let e=!ge(t),i=!t.internal.hasContent||de(t.internal.loadingState);e&&i||t.traversal.allChildrenLoaded||(s=!1)}}e.traversal.allChildrenLoaded=s}else e.traversal.isLeaf=!0;let n=!0;for(let a=0,o=r.length;a<o;a++){let e=r[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 i=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,r=i.length;e<r;e++)Te(i[e],t);return}let r=i.length>0;for(let s=0,n=i.length;s<n;s++){let e=i[s];Se(e,t),pe(e,t.frameCount)&&(!e.traversal.active||!_e(e))&&!e.traversal.allChildrenReady&&(r=!1)}e.traversal.allChildrenReady=r,"REPLACE"===e.refine&&!r&&e.traversal.wasSetActive&&_e(e)&&(e.traversal.active=!0,be(e,t))}function Ae(e,t){ye(e,t);let i=pe(e,t.frameCount);if(i&&(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++),i||me(e)&&e.traversal.usedLastFrame){let r=!1,s=!1;i?(r=e.traversal.active,s=t.displayActiveTiles&&e.traversal.active||e.traversal.visible):ye(e,t),e.internal.hasRenderableContent&&4===e.internal.loadingState?(r&&t.stats.active++,s&&t.stats.visible++,e.traversal.wasSetActive!==r&&t.invokeOnePlugin((t=>t.setTileActive&&t.setTileActive(e,r))),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=r;let n=e.children;for(let e=0,i=n.length;e<i;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,i=null){let r=[];for(r.push(e),r.push(null),r.push(0);r.length>0;){let e=r.pop(),s=r.pop(),n=r.pop();if(t&&t(n,s,e))return void(i&&i(n,s,e));let a=n.children;if(a)for(let t=a.length-1;t>=0;t--)r.push(a[t]),r.push(n),r.push(e+1);i&&i(n,s,e)}}var Re=Symbol("PLUGIN_REGISTERED"),Pe={inView:!0,error:0,distance:1/0},Le=(e,t)=>{let i=e.priority??1/0,r=t.priority??1/0;if(i!==r)return i>r?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 i=e.priority||0,r=t.priority||0;return i===r?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:i>r?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,i,r=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,i);return null!==r&&(r.aborted?this.remove(t):r.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 i=e.parent,r=t.parent;return i===r?0:i?r?Le(i,r):-1:1};var De=class{get root(){let e=this.rootTileset;return e?e.root:null}get loadProgress(){let{stats:e,isLoading:t}=this,i=e.queued+e.downloading+e.parsing,r=e.inCacheSinceLoad+ +!!t;return 0===r?1:1-i/r}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,i=e.priority||0,r=t.length;for(let s=0;s<t.length;s++)if((t[s].priority||0)>i){r=s;break}t.splice(r,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 i=t.indexOf(e);return t.splice(i,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 i=0;i<t.length;i++){let r=e(t[i]);if(r)return r}return null}invokeAllPlugins(e){let t=[...this.plugins,this],i=[];for(let r=0;r<t.length;r++){let s=e(t[r]);s&&i.push(s)}return 0===i.length?null:Promise.all(i)}traverse(e,t,i=!0){this.root&&Ee(this.root,((t,...r)=>(i&&this.ensureChildrenArePreprocessed(t,!0),!!e&&e(t,...r))),t)}getAttributions(e=[]){return this.invokeAllPlugins((t=>t!==this&&t.getAttributions&&t.getAttributions(e))),e}update(){let{lruCache:e,usedSet:t,stats:i,root:r,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})}))),!r)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"}),i.inFrustum=0,i.used=0,i.active=0,i.visible=0,i.tilesProcessed=0,this.frameCount++,t.forEach((t=>e.markUnused(t))),t.clear(),this.prepareForTraversal(),Ce(r,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(),i.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:i,errorFalloffDensity:r}=this;if(i>0&&Number.isFinite(t.distanceFromCamera)){let e=t.distanceFromCamera*r;t.error-=i*(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 i=0,r=t.length;i<r;i++)e.remove(t[i]);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,i){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,i=null){var r;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=i,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==(r=e.content)?void 0:r.uri){let t=se(e.content.uri),i=!(!t||!/json$/.test(t));e.internal.hasContent=!0,e.internal.hasUnrenderableContent=i,e.internal.hasRenderableContent=!i}else e.internal.hasContent=!1,e.internal.hasUnrenderableContent=!1,e.internal.hasRenderableContent=!1;i?(e.internal.depth=i.internal.depth+1,e.internal.depthFromRenderedParent=i.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===i?e.refine||"REPLACE":e.refine||i.refine,e.engineData={scene:null,metadata:null,boundingVolume:null},Object.defineProperty(e,"cached",{get(){return this.engineData},enumerable:!1,configurable:!0}),this.invokeAllPlugins((r=>{r!==this&&r.preprocessNode&&r.preprocessNode(e,t,i)}))}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,i=[];for(let r of t)!e.isUsed(r)&&1===r.internal.loadingState&&i.push(r);for(let r=0;r<i.length;r++)e.remove(i[r])}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 i=e.children;if(0===i.length||i[i.length-1].traversal)return;let r=t=>{for(let i=0,r=t.length;i<r;i++){let r=t[i];r&&!r.traversal&&this.preprocessNode(r,e.internal.basePath,e)}};t?(this.processNodeQueue.remove(e),r(i)):this.processNodeQueue.has(e)||this.processNodeQueue.add(e,(e=>{r(e.children),this._dispatchNeedsUpdateEvent()}))}getBytesUsed(e){let t=0;return this.invokeAllPlugins((i=>{i.calculateBytesUsed&&(t+=i.calculateBytesUsed(e,e.engineData.scene)||0)})),t}recalculateBytesUsed(e=null){let{lruCache:t,processedTiles:i}=this;null===e?t.itemSet.forEach((e=>{i.has(e)&&t.setMemoryUsage(e,this.getBytesUsed(e))})):t.setMemoryUsage(e,this.getBytesUsed(e))}preprocessTileset(e,t,i=null){let[r,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,i)}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,i=null,r=new URL(e.content.uri,e.internal.basePath+"/").toString();this.invokeAllPlugins((t=>r=t.preprocessURL?t.preprocessURL(r,e):r));let s=this.stats,n=this.lruCache,a=this.downloadQueue,o=this.parseQueue,l=this.loadingTiles,c=se(r),h=new AbortController,u=h.signal;return n.add(e,(i=>{h.abort(),t?i.children.length=0:this.invokeAllPlugins((e=>{e.disposeTile&&e.disposeTile(i)})),s.inCache--,this.cachedSinceLoadComplete.has(e)&&(this.cachedSinceLoadComplete.delete(e),s.inCacheSinceLoad--),1===i.internal.loadingState?s.queued--:2===i.internal.loadingState?s.downloading--:3===i.internal.loadingState?s.parsing--:4===i.internal.loadingState&&s.loaded--,i.internal.loadingState=0,o.remove(i),a.remove(i),l.delete(i)}))?(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(r,e,(t=>{if(u.aborted)return Promise.resolve();e.internal.loadingState=2,s.downloading++,s.queued--;let i=this.invokeOnePlugin((e=>e.fetchData&&e.fetchData(r,{...this.fetchOptions,signal:u})));return this.dispatchEvent({type:"tile-download-start",tile:e,url:r,get uri(){return this.url}}),i})).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,r,e),e.children.push(n.root),i=n,t=!0,Promise.resolve()):this.invokeOnePlugin((e=>e.parseTile&&e.parseTile(n,s,c,r,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:i,url:r}),e.engineData.scene&&this.dispatchEvent({type:"load-model",scene:e.engineData.scene,tile:e,url:r}))})).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:r})))}))):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 i="";for(let r=0;r<4;r++)i+=String.fromCharCode(t.getUint8(r));return i}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,i,r,s,n){let a;switch(r){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=i*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,i,r){this.buffer=e,this.binOffset=t+i,this.binLength=r;let s=null;if(0!==i){let r=new Uint8Array(e,t,i);s=JSON.parse(Ne(r))}else s={};this.header=s}getKeys(){return Object.keys(this.header).filter((e=>"extensions"!==e))}getData(e,t,i=null,r=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||r,h=n.componentType||i;if("type"in n&&r&&n.type!==r)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:i,binOffset:r}=this;return i.slice(r+e,r+e+t)}},je=class{constructor(e){this.batchTable=e;let t=e.header.extensions["3DTILES_batch_table_hierarchy"];this.classes=t.classes;for(let r of this.classes){let e=r.instances;for(let t in e)r.instances[t]=this._parseProperty(e[t],r.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 i={};for(let r of this.classIds)i[r]=i[r]??0,this.instancesIds.push(i[r]),i[r]++}_parseProperty(e,t,i){if(Array.isArray(e))return e;{let{buffer:r,binOffset:s}=this.batchTable;return Ge(r,s+e.byteOffset,t,"SCALAR",e.componentType||"UNSIGNED_SHORT",i)}}getDataFromId(e,t={}){let i=this.parentCounts[e];if(this.parentIds&&i>0){let r=0;for(let t=0;t<e;t++)r+=this.parentCounts[t];for(let s=0;s<i;s++){let i=this.parentIds[r+s];i!==e&&this.getDataFromId(i,t)}}let r=this.classIds[e],s=this.classes[r].instances,n=this.classes[r].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,i,r,s){super(e,i,r,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 i of this.getKeys())t[i]=super.getData(i,this.count)[e];for(let i in this.extensions){let r=this.extensions[i];r.getDataFromId instanceof Function&&(t[i]=t[i]||{},r.getDataFromId(e,t[i]))}return t}getPropertyArray(e){return super.getData(e,this.count)}},qe=class extends ze{parse(e){let t=new DataView(e),i=(Oe(t),t.getUint32(4,!0)),r=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:i,featureTable:l,batchTable:h,glbBytes:new Uint8Array(e,u,r-u)}}},Xe=class extends ze{parse(e){let t=new DataView(e),i=(Oe(t),t.getUint32(4,!0)),r=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,r-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:i,featureTable:c,batchTable:u,glbBytes:m,gltfWorkingPath:g})))}},Ke=class extends ze{parse(e){let t=new DataView(e),i=(Oe(t),t.getUint32(4,!0)),r=(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+r+s),0,r,s),l=28+r+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:i,featureTable:o,batchTable:c})}},Ye=class extends ze{parse(e){let t=new DataView(e),i=(Oe(t),t.getUint32(4,!0)),r=(t.getUint32(8,!0),t.getUint32(12,!0)),s=[],n=16;for(let a=0;a<r;a++){let t=new DataView(e,n,12),i=Oe(t),r=t.getUint32(4,!0),a=t.getUint32(8,!0),o=new Uint8Array(e,n,a);s.push({type:i,buffer:o,version:r}),n+=a}return{version:i,tiles:s}}};function Qe(e,t){if(t===r.TrianglesDrawMode)return e;if(t===r.TriangleFanDrawMode||t===r.TriangleStripDrawMode){let i=e.getIndex();if(null===i){const t=[],r=e.getAttribute("position");if(void 0===r)return e;for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),i=e.getIndex()}const s=i.count-2,n=[];if(t===r.TriangleFanDrawMode)for(let e=1;e<=s;e++)n.push(i.getX(0)),n.push(i.getX(e)),n.push(i.getX(e+1));else for(let e=0;e<s;e++)e%2==0?(n.push(i.getX(e)),n.push(i.getX(e+1)),n.push(i.getX(e+2))):(n.push(i.getX(e+2)),n.push(i.getX(e+1)),n.push(i.getX(e)));return n.length,e.setIndex(n),e.clearGroups(),e}return e}function $e(e){const t=new Map,i=new Map,r=e.clone();return Ze(e,r,(function(e,r){t.set(r,e),i.set(e,r)})),r.traverse((function(e){if(!e.isSkinnedMesh)return;const r=e,s=t.get(e),n=s.skeleton.bones;r.skeleton=s.skeleton.clone(),r.bindMatrix.copy(s.bindMatrix),r.skeleton.bones=n.map((function(e){return i.get(e)})),r.bind(r.skeleton,r.bindMatrix)})),r}function Ze(e,t,i){i(e,t);for(let r=0;r<e.children.length;r++)Ze(e.children[r],t.children[r],i)}class Je extends r.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 rt(e)})),this.register((function(e){return new Tt(e,it.EXT_MESHOPT_COMPRESSION)})),this.register((function(e){return new Tt(e,it.KHR_MESHOPT_COMPRESSION)})),this.register((function(e){return new xt(e)}))}load(e,t,i,s){const n=this;let a;if(""!==this.resourcePath)a=this.resourcePath;else if(""!==this.path){const t=r.LoaderUtils.extractUrlBase(e);a=r.LoaderUtils.resolveURL(t,this.path)}else a=r.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const o=function(t){s&&s(t),n.manager.itemError(e),n.manager.itemEnd(e)},l=new r.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,(function(i){try{n.parse(i,a,(function(i){t(i),n.manager.itemEnd(e)}),o)}catch(r){o(r)}}),i,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,i,r){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[it.KHR_BINARY_GLTF]=new Mt(e)}catch(c){return void(r&&r(c))}s=JSON.parse(n[it.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(r&&r(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 it.KHR_MATERIALS_UNLIT:n[e]=new st;break;case it.KHR_DRACO_MESH_COMPRESSION:n[e]=new St(s,this.dracoLoader);break;case it.KHR_TEXTURE_TRANSFORM:n[e]=new At;break;case it.KHR_MESH_QUANTIZATION:n[e]=new Ct;break;default:t.indexOf(e)>=0&&a[e]}}l.setExtensions(n),l.setPlugins(a),l.parse(i,r)}parseAsync(e,t){const i=this;return new Promise((function(r,s){i.parse(e,t,r,s)}))}}function et(){let e={};return{get:function(t){return e[t]},add:function(t,i){e[t]=i},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function tt(e,t,i){const r=e.json.materials[t];return r.extensions&&r.extensions[i]?r.extensions[i]:null}const it={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 rt{constructor(e){this.parser=e,this.name=it.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i<r;i++){const r=t[i];r.extensions&&r.extensions[this.name]&&void 0!==r.extensions[this.name].light&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let s=t.cache.get(i);if(s)return s;const n=t.json,a=((n.extensions&&n.extensions[this.name]||{}).lights||[])[e];let o;const l=new r.Color(16777215);void 0!==a.color&&l.setRGB(a.color[0],a.color[1],a.color[2],r.LinearSRGBColorSpace);const c=void 0!==a.range?a.range:0;switch(a.type){case"directional":o=new r.DirectionalLight(l),o.target.position.set(0,0,-1),o.add(o.target);break;case"point":o=new r.PointLight(l),o.distance=c;break;case"spot":o=new r.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(i,s),s}getDependency(e,t){if("light"===e)return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,r=i.json.nodes[e],s=(r.extensions&&r.extensions[this.name]||{}).light;return void 0===s?null:this._loadLight(s).then((function(e){return i._getNodeRef(t.cache,s,e)}))}}let st=class{constructor(){this.name=it.KHR_MATERIALS_UNLIT}getMaterialType(){return r.MeshBasicMaterial}extendParams(e,t,i){const s=[];e.color=new r.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],r.LinearSRGBColorSpace),e.opacity=t[3]}void 0!==n.baseColorTexture&&s.push(i.assignTexture(e,"map",n.baseColorTexture,r.SRGBColorSpace))}return Promise.all(s)}},nt=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);return null===i||void 0!==i.emissiveStrength&&(t.emissiveIntensity=i.emissiveStrength),Promise.resolve()}},at=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const s=[];if(void 0!==i.clearcoatFactor&&(t.clearcoat=i.clearcoatFactor),void 0!==i.clearcoatTexture&&s.push(this.parser.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),void 0!==i.clearcoatRoughnessFactor&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),void 0!==i.clearcoatRoughnessTexture&&s.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),void 0!==i.clearcoatNormalTexture&&(s.push(this.parser.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),void 0!==i.clearcoatNormalTexture.scale)){const e=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new r.Vector2(e,e)}return Promise.all(s)}},ot=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_DISPERSION}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);return null===i||(t.dispersion=void 0!==i.dispersion?i.dispersion:0),Promise.resolve()}},lt=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const r=[];return void 0!==i.iridescenceFactor&&(t.iridescence=i.iridescenceFactor),void 0!==i.iridescenceTexture&&r.push(this.parser.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),void 0!==i.iridescenceIor&&(t.iridescenceIOR=i.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==i.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),void 0!==i.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),void 0!==i.iridescenceThicknessTexture&&r.push(this.parser.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(r)}},ct=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_SHEEN}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const s=[];if(t.sheenColor=new r.Color(0,0,0),t.sheenRoughness=0,t.sheen=1,void 0!==i.sheenColorFactor){const e=i.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace)}return void 0!==i.sheenRoughnessFactor&&(t.sheenRoughness=i.sheenRoughnessFactor),void 0!==i.sheenColorTexture&&s.push(this.parser.assignTexture(t,"sheenColorMap",i.sheenColorTexture,r.SRGBColorSpace)),void 0!==i.sheenRoughnessTexture&&s.push(this.parser.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(s)}},ht=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const r=[];return void 0!==i.transmissionFactor&&(t.transmission=i.transmissionFactor),void 0!==i.transmissionTexture&&r.push(this.parser.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(r)}},ut=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_VOLUME}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const s=[];t.thickness=void 0!==i.thicknessFactor?i.thicknessFactor:0,void 0!==i.thicknessTexture&&s.push(this.parser.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;const n=i.attenuationColor||[1,1,1];return t.attenuationColor=(new r.Color).setRGB(n[0],n[1],n[2],r.LinearSRGBColorSpace),Promise.all(s)}},dt=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_IOR}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);return null===i||(t.ior=void 0!==i.ior?i.ior:1.5,0===t.ior&&(t.ior=1e3)),Promise.resolve()}},pt=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_SPECULAR}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const s=[];t.specularIntensity=void 0!==i.specularFactor?i.specularFactor:1,void 0!==i.specularTexture&&s.push(this.parser.assignTexture(t,"specularIntensityMap",i.specularTexture));const n=i.specularColorFactor||[1,1,1];return t.specularColor=(new r.Color).setRGB(n[0],n[1],n[2],r.LinearSRGBColorSpace),void 0!==i.specularColorTexture&&s.push(this.parser.assignTexture(t,"specularColorMap",i.specularColorTexture,r.SRGBColorSpace)),Promise.all(s)}},mt=class{constructor(e){this.parser=e,this.name=it.EXT_MATERIALS_BUMP}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const r=[];return t.bumpScale=void 0!==i.bumpFactor?i.bumpFactor:1,void 0!==i.bumpTexture&&r.push(this.parser.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(r)}},ft=class{constructor(e){this.parser=e,this.name=it.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return null!==tt(this.parser,e,this.name)?r.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=tt(this.parser,e,this.name);if(null===i)return Promise.resolve();const r=[];return void 0!==i.anisotropyStrength&&(t.anisotropy=i.anisotropyStrength),void 0!==i.anisotropyRotation&&(t.anisotropyRotation=i.anisotropyRotation),void 0!==i.anisotropyTexture&&r.push(this.parser.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(r)}};class gt{constructor(e){this.parser=e,this.name=it.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,i=t.json,r=i.textures[e];if(!r.extensions||!r.extensions[this.name])return null;const s=r.extensions[this.name],n=t.options.ktx2Loader;if(!n){if(i.extensionsRequired&&i.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=it.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;const n=s.extensions[t],a=r.images[n.source];let o=i.textureLoader;if(a.uri){const e=i.options.manager.getHandler(a.uri);null!==e&&(o=e)}return i.loadTextureImage(e,n.source,o)}}class vt{constructor(e){this.parser=e,this.name=it.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;const n=s.extensions[t],a=r.images[n.source];let o=i.textureLoader;if(a.uri){const e=i.options.manager.getHandler(a.uri);null!==e&&(o=e)}return i.loadTextureImage(e,n.source,o)}}class Tt{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const e=i.extensions[this.name],r=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 r.then((function(t){const i=e.byteOffset||0,r=e.byteLength||0,n=e.count,a=e.byteStride,o=new Uint8Array(t,i,r);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=it.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||void 0===i.mesh)return null;const s=t.meshes[i.mesh];for(const r of s.primitives)if(r.mode!==Lt.TRIANGLES&&r.mode!==Lt.TRIANGLE_STRIP&&r.mode!==Lt.TRIANGLE_FAN&&void 0!==r.mode)return null;const n=i.extensions[this.name].attributes,a=[],o={};for(const r in n)a.push(this.parser.getDependency("accessor",n[r]).then((e=>(o[r]=e,o[r]))));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then((e=>{const t=e.pop(),i=t.isGroup?t.children:[t],s=e[0].count,n=[];for(const a of i){const e=new r.Matrix4,t=new r.Vector3,i=new r.Quaternion,l=new r.Vector3(1,1,1),c=new r.InstancedMesh(a.geometry,a.material,s);for(let r=0;r<s;r++)o.TRANSLATION&&t.fromBufferAttribute(o.TRANSLATION,r),o.ROTATION&&i.fromBufferAttribute(o.ROTATION,r),o.SCALE&&l.fromBufferAttribute(o.SCALE,r),c.setMatrixAt(r,e.compose(t,i,l));let h=null;for(const s in o)if("_COLOR_0"===s){const e=o[s];c.instanceColor=new r.InstancedBufferAttribute(e.array,e.itemSize,e.normalized)}else if("TRANSLATION"!==s&&"ROTATION"!==s&&"SCALE"!==s){if(null===h){const e=c.geometry;h=new r.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 r.InstancedBufferAttribute(e.array,e.itemSize,e.normalized))}r.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=it.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12),i=new TextDecoder;if(this.header={magic:i.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 r=this.header.length-12,s=new DataView(e,12);let n=0;for(;n<r;){const t=s.getUint32(n,!0);n+=4;const r=s.getUint32(n,!0);if(n+=4,r===_t){const r=new Uint8Array(e,12+n,t);this.content=i.decode(r)}else if(r===wt){const i=12+n;this.body=e.slice(i,i+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=it.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,s=this.dracoLoader,n=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const r in a){const e=Dt[r]||r.toLowerCase();o[e]=a[r]}for(const r in e.attributes){const t=Dt[r]||r.toLowerCase();if(void 0!==a[r]){const s=i.accessors[e.attributes[r]],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,i){s.decodeDracoFile(e,(function(e){for(const t in e.attributes){const i=e.attributes[t],r=l[t];void 0!==r&&(i.normalized=r)}t(e)}),o,c,r.LinearSRGBColorSpace,i)}))}))}}class At{constructor(){this.name=it.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),i=Math.sin(e.rotation);e.matrix.set(e.repeat.x*t,e.repeat.y*i,e.offset.x,-e.repeat.x*i,e.repeat.y*t,e.offset.y,0,0,1),e.matrixAutoUpdate=!1}return e.needsUpdate=!0,e}}class Ct{constructor(){this.name=it.KHR_MESH_QUANTIZATION}}class Et extends r.Interpolant{constructor(e,t,i,r){super(e,t,i,r)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,r=this.valueSize,s=e*r*3+r;for(let n=0;n!==r;n++)t[n]=i[s+n];return t}interpolate_(e,t,i,r){const s=this.resultBuffer,n=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=r-t,h=(i-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,i=n[p+T+a],r=n[p+T]*c;s[T]=y*e+v*t+f*i+g*r}return s}}const Rt=new r.Quaternion;class Pt extends Et{interpolate_(e,t,i,r){const s=super.interpolate_(e,t,i,r);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:r.NearestFilter,9729:r.LinearFilter,9984:r.NearestMipmapNearestFilter,9985:r.LinearMipmapNearestFilter,9986:r.NearestMipmapLinearFilter,9987:r.LinearMipmapLinearFilter},Ft={33071:r.ClampToEdgeWrapping,33648:r.MirroredRepeatWrapping,10497:r.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:r.InterpolateLinear,STEP:r.InterpolateDiscrete},Nt="OPAQUE",Vt="MASK",zt="BLEND";function Gt(e,t,i){for(const r in i.extensions)void 0===e[r]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=i.extensions[r])}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 i=0,r=t.weights.length;i<r;i++)e.morphTargetInfluences[i]=t.weights[i];if(t.extras&&Array.isArray(t.extras.targetNames)){const i=t.extras.targetNames;if(e.morphTargetInfluences.length===i.length){e.morphTargetDictionary={};for(let t=0,r=i.length;t<r;t++)e.morphTargetDictionary[i[t]]=t}}}function Wt(e){let t;const i=e.extensions&&e.extensions[it.KHR_DRACO_MESH_COMPRESSION];if(t=i?"draco:"+i.bufferView+":"+i.indices+":"+qt(i.attributes):e.indices+":"+qt(e.attributes)+":"+e.mode,void 0!==e.targets)for(let r=0,s=e.targets.length;r<s;r++)t+=":"+qt(e.targets[r]);return t}function qt(e){let t="";const i=Object.keys(e).sort();for(let r=0,s=i.length;r<s;r++)t+=i[r]+":"+e[i[r]]+";";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 r.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 i=!1,s=-1,n=!1,a=-1;if("undefined"!=typeof navigator&&void 0!==navigator.userAgent){const e=navigator.userAgent;i=!0===/^((?!chrome|android).)*safari/i.test(e);const t=e.match(/Version\/(\d+)/);s=i&&t?parseInt(t[1],10):-1,n=e.indexOf("Firefox")>-1,a=n?e.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||i&&s<17||n&&a<98?this.textureLoader=new r.TextureLoader(this.options.manager):this.textureLoader=new r.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new r.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 i=this,r=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([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])})).then((function(t){const n={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:i,userData:{}};return Gt(s,n,r),Ht(n,r),Promise.all(i._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||[],i=this.json.meshes||[];for(let r=0,s=t.length;r<s;r++){const i=t[r].joints;for(let t=0,r=i.length;t<r;t++)e[i[t]].isBone=!0}for(let r=0,s=e.length;r<s;r++){const t=e[r];void 0!==t.mesh&&(this._addNodeRef(this.meshCache,t.mesh),void 0!==t.skin&&(i[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,i){if(e.refs[t]<=1)return i;const r=i.clone(),s=(e,t)=>{const i=this.associations.get(e);null!=i&&this.associations.set(t,i);for(const[r,n]of e.children.entries())s(n,t.children[r])};return s(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const r=e(t[i]);if(r)return r}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let r=0;r<t.length;r++){const s=e(t[r]);s&&i.push(s)}return i}getDependency(e,t){const i=e+":"+t;let r=this.cache.get(i);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne((function(e){return e.loadNode&&e.loadNode(t)}));break;case"mesh":r=this._invokeOne((function(e){return e.loadMesh&&e.loadMesh(t)}));break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne((function(e){return e.loadBufferView&&e.loadBufferView(t)}));break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne((function(e){return e.loadMaterial&&e.loadMaterial(t)}));break;case"texture":r=this._invokeOne((function(e){return e.loadTexture&&e.loadTexture(t)}));break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne((function(e){return e.loadAnimation&&e.loadAnimation(t)}));break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne((function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)})),!r)throw new Error("Unknown type: "+e)}this.cache.add(i,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,r=this.json[e+("mesh"===e?"es":"s")]||[];t=Promise.all(r.map((function(t,r){return i.getDependency(e,r)}))),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=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[it.KHR_BINARY_GLTF].body);const s=this.options;return new Promise((function(e,n){i.load(r.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 i=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+i)}))}loadAccessor(e){const t=this,i=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],i=!0===s.normalized,n=new t(s.count*e);return Promise.resolve(new r.BufferAttribute(n,e,i))}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?i.bufferViews[s.bufferView].byteStride:void 0,d=!0===s.normalized;let p,m;if(u&&u!==c){const e=Math.floor(h/u),i="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+e+":"+s.count;let c=t.cache.get(i);c||(p=new o(n,e*u,s.count*u/l),c=new r.InterleavedBuffer(p,u/l),t.cache.add(i,c)),m=new r.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 r.BufferAttribute(p,a,d);if(void 0!==s.sparse){const t=kt.SCALAR,i=Ut[s.sparse.indices.componentType],l=s.sparse.indices.byteOffset||0,c=s.sparse.values.byteOffset||0,h=new i(e[1],l,s.sparse.count*t),u=new o(e[2],c,s.sparse.count*a);null!==n&&(m=new r.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let e=0,r=h.length;e<r;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,i=this.options,r=t.textures[e].source,s=t.images[r];let n=this.textureLoader;if(s.uri){const e=i.manager.getHandler(s.uri);null!==e&&(n=e)}return this.loadTextureImage(e,r,n)}loadTextureImage(e,t,i){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,i).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 i=(n.samplers||{})[a.sampler]||{};return t.magFilter=It[i.magFilter]||r.LinearFilter,t.minFilter=It[i.minFilter]||r.LinearMipmapLinearFilter,t.wrapS=Ft[i.wrapS]||r.RepeatWrapping,t.wrapT=Ft[i.wrapT]||r.RepeatWrapping,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==r.NearestFilter&&t.minFilter!==r.LinearFilter,s.associations.set(t,{textures:e}),t})).catch((function(){return null}));return this.textureCache[l]=c,c}loadImageSource(e,t){const i=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=i.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(i,s){let a=i;!0===t.isImageBitmapLoader&&(a=function(e){const t=new r.Texture(e);t.needsUpdate=!0,i(t)}),t.load(r.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,i,r){const s=this;return this.getDependency("texture",i.index).then((function(n){if(!n)return null;if(void 0!==i.texCoord&&i.texCoord>0&&((n=n.clone()).channel=i.texCoord),s.extensions[it.KHR_TEXTURE_TRANSFORM]){const e=void 0!==i.extensions?i.extensions[it.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=s.associations.get(n);n=s.extensions[it.KHR_TEXTURE_TRANSFORM].extendTexture(n,e),s.associations.set(n,t)}}return void 0!==r&&(n.colorSpace=r),e[t]=n,n}))}assignFinalMaterial(e){const t=e.geometry;let i=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:"+i.uuid;let t=this.cache.get(e);t||(t=new r.PointsMaterial,r.Material.prototype.copy.call(t,i),t.color.copy(i.color),t.map=i.map,t.sizeAttenuation=!1,this.cache.add(e,t)),i=t}else if(e.isLine){const e="LineBasicMaterial:"+i.uuid;let t=this.cache.get(e);t||(t=new r.LineBasicMaterial,r.Material.prototype.copy.call(t,i),t.color.copy(i.color),t.map=i.map,this.cache.add(e,t)),i=t}if(s||n||a){let e="ClonedMaterial:"+i.uuid+":";s&&(e+="derivative-tangents:"),n&&(e+="vertex-colors:"),a&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=i.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(i))),i=t}e.material=i}getMaterialType(){return r.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,s=this.extensions,n=i.materials[e];let a;const o={},l=[];if((n.extensions||{})[it.KHR_MATERIALS_UNLIT]){const e=s[it.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),l.push(e.extendParams(o,n,t))}else{const i=n.pbrMetallicRoughness||{};if(o.color=new r.Color(1,1,1),o.opacity=1,Array.isArray(i.baseColorFactor)){const e=i.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace),o.opacity=e[3]}void 0!==i.baseColorTexture&&l.push(t.assignTexture(o,"map",i.baseColorTexture,r.SRGBColorSpace)),o.metalness=void 0!==i.metallicFactor?i.metallicFactor:1,o.roughness=void 0!==i.roughnessFactor?i.roughnessFactor:1,void 0!==i.metallicRoughnessTexture&&(l.push(t.assignTexture(o,"metalnessMap",i.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",i.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=r.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!==r.MeshBasicMaterial&&(l.push(t.assignTexture(o,"normalMap",n.normalTexture)),o.normalScale=new r.Vector2(1,1),void 0!==n.normalTexture.scale)){const e=n.normalTexture.scale;o.normalScale.set(e,e)}if(void 0!==n.occlusionTexture&&a!==r.MeshBasicMaterial&&(l.push(t.assignTexture(o,"aoMap",n.occlusionTexture)),void 0!==n.occlusionTexture.strength&&(o.aoMapIntensity=n.occlusionTexture.strength)),void 0!==n.emissiveFactor&&a!==r.MeshBasicMaterial){const e=n.emissiveFactor;o.emissive=(new r.Color).setRGB(e[0],e[1],e[2],r.LinearSRGBColorSpace)}return void 0!==n.emissiveTexture&&a!==r.MeshBasicMaterial&&l.push(t.assignTexture(o,"emissiveMap",n.emissiveTexture,r.SRGBColorSpace)),Promise.all(l).then((function(){const i=new a(o);return n.name&&(i.name=n.name),Ht(i,n),t.associations.set(i,{materials:e}),n.extensions&&Gt(s,i,n),i}))}createUniqueName(e){const t=r.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,s=this.primitiveCache;function n(e){return i[it.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(i){return Qt(i,e,t)}))}const a=[];for(let o=0,l=e.length;o<l;o++){const i=e[o],l=Wt(i),c=s[l];if(c)a.push(c.promise);else{let e;e=i.extensions&&i.extensions[it.KHR_DRACO_MESH_COMPRESSION]?n(i):Qt(new r.BufferGeometry,i,t),i.mode===Lt.TRIANGLE_STRIP?e=e.then((e=>Qe(e,r.TriangleStripDrawMode))):i.mode===Lt.TRIANGLE_FAN&&(e=e.then((e=>Qe(e,r.TriangleFanDrawMode)))),s[l]={primitive:i,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){const t=this,i=this.json,s=this.extensions,n=i.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 r.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:r.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(i){const o=i.slice(0,i.length-1),l=i[i.length-1],c=[];for(let u=0,d=l.length;u<d;u++){const i=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=i.hasAttribute("skinIndex")&&i.hasAttribute("skinWeight");d=e&&t?new r.SkinnedMesh(i,p):new r.Mesh(i,p),!0===d.isSkinnedMesh&&d.normalizeSkinWeights()}else if(h.mode===Lt.LINES)d=new r.LineSegments(i,p);else if(h.mode===Lt.LINE_STRIP)d=new r.Line(i,p);else if(h.mode===Lt.LINE_LOOP)d=new r.LineLoop(i,p);else{if(h.mode!==Lt.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+h.mode);d=new r.Points(i,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 r=0,s=c.length;r<s;r++)t.associations.set(c[r],{meshes:e,primitives:r});if(1===c.length)return n.extensions&&Gt(s,c[0],n),c[0];const h=new r.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 i=this.json.cameras[e],s=i[i.type];if(s)return"perspective"===i.type?t=new r.PerspectiveCamera(r.MathUtils.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):"orthographic"===i.type&&(t=new r.OrthographicCamera(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),Ht(t,i),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],i=[];for(let r=0,s=t.joints.length;r<s;r++)i.push(this._loadNodeShallow(t.joints[r]));return void 0!==t.inverseBindMatrices?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then((function(e){const t=e.pop(),i=e,s=[],n=[];for(let a=0,o=i.length;a<o;a++){const e=i[a];if(e){s.push(e);const i=new r.Matrix4;null!==t&&i.fromArray(t.array,16*a),n.push(i)}}return new r.Skeleton(s,n)}))}loadAnimation(e){const t=this.json,i=this,s=t.animations[e],n=s.name?s.name:"animation_"+e,a=[],o=[],l=[],c=[],h=[];for(let r=0,u=s.channels.length;r<u;r++){const e=s.channels[r],t=s.samplers[e.sampler],i=e.target,n=i.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!==i.node&&(a.push(this.getDependency("node",n)),o.push(this.getDependency("accessor",u)),l.push(this.getDependency("accessor",d)),c.push(t),h.push(i))}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 r=0,s=t.length;r<s;r++){const e=t[r],s=a[r],n=o[r],u=l[r],d=c[r];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const p=i._createAnimationTracks(e,s,n,u,d);if(p)for(let t=0;t<p.length;t++)h.push(p[t])}const u=new r.AnimationClip(n,void 0,h);return Ht(u,s),u}))}createNodeMesh(e){const t=this.json,i=this,r=t.nodes[e];return void 0===r.mesh?null:i.getDependency("mesh",r.mesh).then((function(e){const t=i._getNodeRef(i.meshCache,r.mesh,e);return void 0!==r.weights&&t.traverse((function(e){if(e.isMesh)for(let t=0,i=r.weights.length;t<i;t++)e.morphTargetInfluences[t]=r.weights[t]})),t}))}loadNode(e){const t=this,i=this.json.nodes[e],s=t._loadNodeShallow(e),n=[],a=i.children||[];for(let r=0,l=a.length;r<l;r++)n.push(t.getDependency("node",a[r]));const o=void 0===i.skin?Promise.resolve(null):t.getDependency("skin",i.skin);return Promise.all([s,Promise.all(n),o]).then((function(e){const t=e[0],i=e[1],s=e[2];null!==s&&t.traverse((function(e){e.isSkinnedMesh&&e.bind(s,Kt)}));for(let r=0,n=i.length;r<n;r++)t.add(i[r]);if(void 0!==t.userData.pivot&&i.length>0){const e=t.userData.pivot,s=i[0];t.pivot=(new r.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,i=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 r.Bone:t.length>1?new r.Group:1===t.length?t[0]:new r.Object3D,o!==t[0])for(let e=0,i=t.length;e<i;e++)o.add(t[e]);if(n.name&&(o.userData.name=n.name,o.name=a),Ht(o,n),n.extensions&&Gt(i,o,n),void 0!==n.matrix){const e=new r.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,i=this.json.scenes[e],s=this,n=new r.Group;i.name&&(n.name=s.createUniqueName(i.name)),Ht(n,i),i.extensions&&Gt(t,n,i);const a=i.nodes||[],o=[];for(let r=0,l=a.length;r<l;r++)o.push(s.getDependency("node",a[r]));return Promise.all(o).then((function(e){for(let t=0,i=e.length;t<i;t++){const i=e[t];null!==i.parent?n.add($e(i)):n.add(i)}return s.associations=(e=>{const t=new Map;for(const[i,n]of s.associations)(i instanceof r.Material||i instanceof r.Texture)&&t.set(i,n);return e.traverse((e=>{const i=s.associations.get(e);null!=i&&t.set(e,i)})),t})(n),n}))}_createAnimationTracks(e,t,i,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=r.NumberKeyframeTrack;break;case Ot.rotation:h=r.QuaternionKeyframeTrack;break;case Ot.translation:case Ot.scale:h=r.VectorKeyframeTrack;break;default:if(1===i.itemSize)h=r.NumberKeyframeTrack;else h=r.VectorKeyframeTrack}const u=void 0!==s.interpolation?Bt[s.interpolation]:r.InterpolateLinear,d=this._getArrayFromAccessor(i);for(let r=0,p=l.length;r<p;r++){const e=new h(l[r]+"."+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),i=new Float32Array(t.length);for(let r=0,s=t.length;r<s;r++)i[r]=t[r]*e;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof r.QuaternionKeyframeTrack?Pt:Et)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Qt(e,t,i){const s=t.attributes,n=[];function a(t,r){return i.getDependency("accessor",t).then((function(t){e.setAttribute(r,t)}))}for(const r in s){const t=Dt[r]||r.toLowerCase();t in e.attributes||n.push(a(s[r],t))}if(void 0!==t.indices&&!e.index){const r=i.getDependency("accessor",t.indices).then((function(t){e.setIndex(t)}));n.push(r)}return r.ColorManagement.workingColorSpace,r.LinearSRGBColorSpace,Ht(e,t),function(e,t,i){const s=t.attributes,n=new r.Box3;if(void 0===s.POSITION)return;{const e=i.json.accessors[s.POSITION],t=e.min,a=e.max;if(void 0===t||void 0===a)return;if(n.set(new r.Vector3(t[0],t[1],t[2]),new r.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 r.Vector3,t=new r.Vector3;for(let r=0,s=a.length;r<s;r++){const s=a[r];if(void 0!==s.POSITION){const r=i.json.accessors[s.POSITION],n=r.min,a=r.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]))),r.normalized){const e=Xt(Ut[r.componentType]);t.multiplyScalar(e)}e.max(t)}}}n.expandByVector(e)}e.boundingBox=n;const o=new r.Sphere;n.getCenter(o.center),o.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=o}(e,t,i),Promise.all(n).then((function(){return void 0!==t.targets?function(e,t,i){let r=!1,s=!1,n=!1;for(let c=0,h=t.length;c<h;c++){const e=t[c];if(void 0!==e.POSITION&&(r=!0),void 0!==e.NORMAL&&(s=!0),void 0!==e.COLOR_0&&(n=!0),r&&s&&n)break}if(!r&&!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(r){const t=void 0!==h.POSITION?i.getDependency("accessor",h.POSITION):e.attributes.position;a.push(t)}if(s){const t=void 0!==h.NORMAL?i.getDependency("accessor",h.NORMAL):e.attributes.normal;o.push(t)}if(n){const t=void 0!==h.COLOR_0?i.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 i=t[0],a=t[1],o=t[2];return r&&(e.morphAttributes.position=i),s&&(e.morphAttributes.normal=a),n&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e}))}(e,t.targets,i):e}))}var $t=class extends qe{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4}parse(e){let t=super.parse(e),i=t.glbBytes.slice().buffer;return new Promise(((e,r)=>{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(i,o,(i=>{let{batchTable:r,featureTable:s}=t,{scene:n}=i,a=s.getData("RTC_CENTER",1,"FLOAT","VEC3");a&&(n.position.x+=a[0],n.position.y+=a[1],n.position.z+=a[2]),i.scene.updateMatrix(),i.scene.matrix.multiply(l),i.scene.matrix.decompose(i.scene.position,i.scene.quaternion,i.scene.scale),i.batchTable=r,i.featureTable=s,n.batchTable=r,n.featureTable=s,e(i)}),r)}))}};function Zt(e){let t=e>>11,i=e>>5&63,r=31&e;return[Math.round(t/31*255),Math.round(i/63*255),Math.round(r/31*255)]}var Jt=new r.Vector2;function ei(e,t,i=new r.Vector3){Jt.set(e,t).divideScalar(256).multiplyScalar(2).subScalar(1),i.set(Jt.x,Jt.y,1-Math.abs(Jt.x)-Math.abs(Jt.y));let s=r.MathUtils.clamp(-i.z,0,1);return i.x>=0?i.setX(i.x-s):i.setX(i.x+s),i.y>=0?i.setY(i.y-s):i.setY(i.y+s),i.normalize(),i}var ti={RGB:"color",POSITION:"position"},ii=class extends Ke{constructor(e=r.DefaultLoadingManager){super(),this.manager=e}parse(e){return super.parse(e).then((async e=>{let t,{featureTable:i,batchTable:s}=e,n=new r.PointsMaterial,a=i.header.extensions,o=new r.Vector3;if(a&&a["3DTILES_draco_point_compression"]){let{byteOffset:e,byteLength:r,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 ti&&t in s){l[ti[t]]=s[t]}let c={attributeIDs:l,attributeTypes:{position:"Float32Array",color:"Uint8Array"},useUniqueIDs:!0},h=i.getBuffer(e,r);t=await o.decodeGeometry(h,c),t.attributes.color&&(n.vertexColors=!0)}else{let e=i.getData("POINTS_LENGTH"),s=i.getData("POSITION",e,"FLOAT","VEC3"),a=i.getData("NORMAL",e,"FLOAT","VEC3"),l=i.getData("NORMAL",e,"UNSIGNED_BYTE","VEC2"),c=i.getData("RGB",e,"UNSIGNED_BYTE","VEC3"),h=i.getData("RGBA",e,"UNSIGNED_BYTE","VEC4"),u=i.getData("RGB565",e,"UNSIGNED_SHORT","SCALAR"),d=i.getData("CONSTANT_RGBA",e,"UNSIGNED_BYTE","VEC4"),p=i.getData("POSITION_QUANTIZED",e,"UNSIGNED_SHORT","VEC3"),m=i.getData("QUANTIZED_VOLUME_SCALE",e,"FLOAT","VEC3"),f=i.getData("QUANTIZED_VOLUME_OFFSET",e,"FLOAT","VEC3");if(t=new r.BufferGeometry,p){let i=new Float32Array(3*e);for(let t=0;t<e;t++)for(let e=0;e<3;e++){let r=3*t+e;i[r]=p[r]/65535*m[e]}o.x=f[0],o.y=f[1],o.z=f[2],t.setAttribute("position",new r.BufferAttribute(i,3,!1))}else t.setAttribute("position",new r.BufferAttribute(s,3,!1));if(null!==a)t.setAttribute("normal",new r.BufferAttribute(a,3,!1));else if(null!==l){let i=new Float32Array(3*e),s=new r.Vector3;for(let t=0;t<e;t++){let e=ei(l[2*t],l[2*t+1],s);i[3*t]=e.x,i[3*t+1]=e.y,i[3*t+2]=e.z}t.setAttribute("normal",new r.BufferAttribute(i,3,!1))}if(null!==h)t.setAttribute("color",new r.BufferAttribute(h,4,!0)),n.vertexColors=!0,n.transparent=!0,n.depthWrite=!1;else if(null!==c)t.setAttribute("color",new r.BufferAttribute(c,3,!0)),n.vertexColors=!0;else if(null!==u){let i=new Uint8Array(3*e);for(let t=0;t<e;t++){let e=Zt(u[t]);for(let r=0;r<3;r++){i[3*t+r]=e[r]}}t.setAttribute("color",new r.BufferAttribute(i,3,!0)),n.vertexColors=!0}else if(null!==d){n.color=new r.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 r.Points(t,n);l.position.copy(o),e.scene=l,e.scene.featureTable=i,e.scene.batchTable=s;let c=i.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 ri=new r.Spherical,si=new r.Vector3,ni=new r.Vector3,ai=new r.Vector3,oi=new r.Matrix4,li=new r.Matrix4,ci=new r.Sphere,hi=new r.Euler,ui=new r.Vector3,di=new r.Vector3,pi=new r.Vector3,mi=new r.Vector3,fi=new r.Ray,gi=class{constructor(e=1,t=1,i=1){this.name="",this.radius=new r.Vector3(e,t,i)}intersectRay(e,t){return oi.makeScale(...this.radius).invert(),ci.center.set(0,0,0),ci.radius=1,fi.copy(e).applyMatrix4(oi),fi.intersectSphere(ci,t)?(oi.makeScale(...this.radius),t.applyMatrix4(oi),t):null}getEastNorthUpFrame(e,t,i,r){return i.isMatrix4&&(r=i,i=0),this.getEastNorthUpAxes(e,t,ui,di,pi),this.getCartographicToPosition(e,t,i,mi),r.makeBasis(ui,di,pi).setPosition(mi)}getOrientedEastNorthUpFrame(e,t,i,r,s,n,a){return this.getObjectFrame(e,t,i,r,s,n,a,0)}getObjectFrame(e,t,i,r,s,n,a,o=2){return this.getEastNorthUpFrame(e,t,i,oi),hi.set(s,n,-r,"ZXY"),a.makeRotationFromEuler(hi).premultiply(oi),1===o?(hi.set(Math.PI/2,0,0,"XYZ"),li.makeRotationFromEuler(hi),a.multiply(li)):2===o&&(hi.set(-Math.PI/2,0,Math.PI,"XYZ"),li.makeRotationFromEuler(hi),a.multiply(li)),a}getCartographicFromObjectFrame(e,t,i=2){return 1===i?(hi.set(-Math.PI/2,0,0,"XYZ"),li.makeRotationFromEuler(hi).premultiply(e)):2===i?(hi.set(-Math.PI/2,0,Math.PI,"XYZ"),li.makeRotationFromEuler(hi).premultiply(e)):li.copy(e),mi.setFromMatrixPosition(li),this.getPositionToCartographic(mi,t),this.getEastNorthUpFrame(t.lat,t.lon,0,oi).invert(),li.premultiply(oi),hi.setFromRotationMatrix(li,"ZXY"),t.azimuth=-hi.z,t.elevation=hi.x,t.roll=hi.y,t}getEastNorthUpAxes(e,t,i,r,s,n=mi){this.getCartographicToPosition(e,t,0,n),this.getCartographicToNormal(e,t,s),i.set(-n.y,n.x,0).normalize(),r.crossVectors(s,i).normalize()}getCartographicToPosition(e,t,i,r){this.getCartographicToNormal(e,t,si);let s=this.radius;ni.copy(si),ni.x*=s.x**2,ni.y*=s.y**2,ni.z*=s.z**2;let n=Math.sqrt(si.dot(ni));return ni.divideScalar(n),r.copy(ni).addScaledVector(si,i)}getPositionToCartographic(e,t){this.getPositionToSurfacePoint(e,ni),this.getPositionToNormal(ni,si);let i=ai.subVectors(e,ni);return t.lon=Math.atan2(si.y,si.x),t.lat=Math.asin(si.z),t.height=Math.sign(i.dot(e))*i.length(),t}getCartographicToNormal(e,t,i){return ri.set(1,function(e){return-e+Math.PI/2}(e),t),i.setFromSpherical(ri).normalize(),function(e){let{x:t,y:i,z:r}=e;e.x=r,e.y=t,e.z=i}(i),i}getPositionToNormal(e,t){let i=this.radius;return t.copy(e),t.x/=i.x**2,t.y/=i.y**2,t.z/=i.z**2,t.normalize(),t}getPositionToSurfacePoint(e,t){let i=this.radius,r=1/i.x**2,s=1/i.y**2,n=1/i.z**2,a=e.x*e.x*r,o=e.y*e.y*s,l=e.z*e.z*n,c=a+o+l,h=Math.sqrt(1/c),u=ni.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=ai.set(u.x*r*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*r),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*r+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 i=this.calculateEffectiveRadius(e);return Math.sqrt(2*i*t+t**2)}calculateEffectiveRadius(e){let t=this.radius.x,i=1-this.radius.z**2/t**2,s=e*r.MathUtils.DEG2RAD,n=Math.sin(s)**2;return t/Math.sqrt(1-i*n)}getPositionElevation(e){this.getPositionToSurfacePoint(e,ni);let t=ai.subVectors(e,ni);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(oi.makeScale(...this.radius).invert(),fi.copy(e).applyMatrix4(oi),ni.set(0,0,0),fi.closestPointToPoint(ni,t).normalize(),oi.makeScale(...this.radius),t.applyMatrix4(oi))}copy(e){return this.radius.copy(e.radius),this}clone(){return(new this.constructor).copy(this)}},yi=new gi(he,he,6356752.314245179);yi.name="WGS84 Earth";var vi=new r.Vector3,Ti=new r.Vector3,xi=new r.Vector3,bi=new r.Vector3,_i=new r.Quaternion,wi=new r.Vector3,Mi=new r.Matrix4,Si=new r.Matrix4,Ai=new r.Vector3,Ci=new r.Matrix4,Ei=new r.Quaternion,Ri={};function Pi(e,t,i,r){if(e=e/i*2-1,t=t/i*2-1,r.x=e,r.y=t,r.z=1-Math.abs(e)-Math.abs(t),r.z<0){let e=r.x;r.x=(1-Math.abs(r.y))*(e>=0?1:-1),r.y=(1-Math.abs(e))*(r.y>=0?1:-1)}return r.normalize(),r}var Li=class extends Xe{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4,this.ellipsoid=yi.clone()}resolveExternalURL(e){return this.manager.resolveURL(super.resolveExternalURL(e))}parse(e){return super.parse(e).then((e=>{let{featureTable:t,batchTable:i}=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 r.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:i}=e,n=new r.InstancedMesh(t,i,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++){bi.set(a[3*t+0]-T.x,a[3*t+1]-T.y,a[3*t+2]-T.z),_i.identity(),h&&d?(Ti.set(h[3*t+0],h[3*t+1],h[3*t+2]),xi.set(d[3*t+0],d[3*t+1],d[3*t+2]),vi.crossVectors(xi,Ti).normalize(),Mi.makeBasis(xi,Ti,vi),_i.setFromRotationMatrix(Mi)):p&&m&&(Pi(p[2*t+0],p[2*t+1],65535,Ti),Pi(m[2*t+0],m[2*t+1],65535,xi),vi.crossVectors(xi,Ti).normalize(),Mi.makeBasis(xi,Ti,vi),_i.setFromRotationMatrix(Mi)),wi.set(1,1,1),f&&wi.set(f[3*t+0],f[3*t+1],f[3*t+2]),g&&wi.multiplyScalar(g[t]);for(let e=0,i=x.length;e<i;e++){let i=x[e];Ei.copy(_i),v&&(i.updateMatrixWorld(),Ai.copy(bi).applyMatrix4(i.matrixWorld),this.ellipsoid.getPositionToCartographic(Ai,Ri),this.ellipsoid.getEastNorthUpFrame(Ri.lat,Ri.lon,Ci),Ei.setFromRotationMatrix(Ci)),Mi.compose(bi,Ei,wi).multiply(u);let r=b[e];Si.multiplyMatrices(Mi,r.matrixWorld),i.setMatrixAt(t,Si)}}e.scene.clear(),e.scene.add(...x),e.batchTable=i,e.featureTable=t,e.scene.batchTable=i,e.scene.featureTable=t,n(e)}),a)}))}))}},Ui=class extends Ye{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.adjustmentTransform=new r.Matrix4,this.ellipsoid=yi.clone()}parse(e){let t=super.parse(e),{manager:i,ellipsoid:s,adjustmentTransform:n}=this,a=[];for(let r in t.tiles){let{type:e,buffer:o}=t.tiles[r];switch(e){case"b3dm":{let e=o.slice(),t=new $t(i);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.adjustmentTransform.copy(n);let r=t.parse(e.buffer);a.push(r);break}case"pnts":{let e=o.slice(),t=new ii(i);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions;let r=t.parse(e.buffer);a.push(r);break}case"i3dm":{let e=o.slice(),t=new Li(i);t.workingPath=this.workingPath,t.fetchOptions=this.fetchOptions,t.ellipsoid.copy(s),t.adjustmentTransform.copy(n);let r=t.parse(e.buffer);a.push(r);break}}}return Promise.all(a).then((e=>{let t=new r.Group;return e.forEach((e=>{t.add(e.scene)})),{tiles:e,scene:t}}))}},Ii=new r.Matrix4,Fi=class extends r.Group{constructor(e){super(),this.isTilesGroup=!0,this.name="TilesRenderer.TilesGroup",this.tilesRenderer=e,this.matrixWorldInverse=new r.Matrix4}raycast(e,t){return this.tilesRenderer.raycast(e,t),!1}updateMatrixWorld(e){if(this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldNeedsUpdate||e){null===this.parent?Ii.copy(this.matrix):Ii.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1;let e=Ii.elements,t=this.matrixWorld.elements,i=!1;for(let r=0;r<16;r++){let s=e[r],n=t[r];if(Math.abs(s-n)>2**-52){i=!0;break}}if(i){this.matrixWorld.copy(Ii),this.matrixWorldInverse.copy(Ii).invert();let e=this.children;for(let s=0,n=e.length;s<n;s++)e[s].updateMatrixWorld();let{tilesRenderer:t}=this,{activeTiles:i,visibleTiles:r}=t;i.forEach((e=>{r.has(e)||e.engineData.scene.updateMatrixWorld(!0)}))}}}updateWorldMatrix(e,t){this.parent&&e&&this.parent.updateWorldMatrix(e,!1),this.updateMatrixWorld(!0)}},ki=new r.Ray;function Di(e,t,i,r,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=ki).copy(i.ray).applyMatrix4(n.matrixWorldInverse),!t.traversal.used||!o.intersectsRay(s))return;a.has(t)&&function(e,t,i,r){let{scene:s}=e.engineData;i.invokeOnePlugin((i=>i.raycastTile&&i.raycastTile(e,s,t,r)))||t.intersectObject(s,!0,r)}(t,i,e,r);let l=t.children;for(let c=0,h=l.length;c<h;c++)Di(e,l[c],i,r,s)}var Oi=new r.Vector3,Bi=new r.Vector3,Ni=new r.Vector3,Vi=new r.Ray,zi=class{constructor(e=new r.Box3,t=new r.Matrix4){this.box=e.clone(),this.transform=t.clone(),this.inverseTransform=new r.Matrix4,this.points=Array(8).fill().map((()=>new r.Vector3)),this.planes=[,,,,,,].fill().map((()=>new r.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,Ni).distanceTo(e)}containsPoint(e){return Ni.copy(e).applyMatrix4(this.inverseTransform),this.box.containsPoint(Ni)}intersectsRay(e){return Vi.copy(e).applyMatrix4(this.inverseTransform),Vi.intersectsBox(this.box)}intersectRay(e,t){return Vi.copy(e).applyMatrix4(this.inverseTransform),Vi.intersectBox(this.box,t)?(t.applyMatrix4(this.transform),t):null}update(){let{points:e,inverseTransform:t,transform:i,box:r}=this;t.copy(i).invert();let{min:s,max:n}=r,a=0;for(let o=-1;o<=1;o+=2)for(let t=-1;t<=1;t+=2)for(let r=-1;r<=1;r+=2)e[a].set(o<0?s.x:n.x,t<0?s.y:n.y,r<0?s.z:n.z).applyMatrix4(i),a++;this.updatePlanes()}updatePlanes(){Oi.copy(this.box.min).applyMatrix4(this.transform),Bi.copy(this.box.max).applyMatrix4(this.transform),Ni.set(0,0,1).transformDirection(this.transform),this.planes[0].setFromNormalAndCoplanarPoint(Ni,Oi),this.planes[1].setFromNormalAndCoplanarPoint(Ni,Bi).negate(),Ni.set(0,1,0).transformDirection(this.transform),this.planes[2].setFromNormalAndCoplanarPoint(Ni,Oi),this.planes[3].setFromNormalAndCoplanarPoint(Ni,Bi).negate(),Ni.set(1,0,0).transformDirection(this.transform),this.planes[4].setFromNormalAndCoplanarPoint(Ni,Oi),this.planes[5].setFromNormalAndCoplanarPoint(Ni,Bi).negate()}intersectsSphere(e){return this.clampPoint(e.center,Ni),Ni.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 i=this.points,r=this.planes;for(let s=0;s<6;s++){let t=e[s],r=-1/0;for(let e=0;e<8;e++){let s=i[e],n=t.distanceToPoint(s);r=r<n?n:r}if(r<0)return!1}for(let s=0;s<6;s++){let e=r[s],i=-1/0;for(let r=0;r<8;r++){let s=t[r],n=e.distanceToPoint(s);i=i<n?n:i}if(i<0)return!1}return!0}},Gi=Math.PI,Hi=Gi/2,ji=new r.Vector3,Wi=new r.Vector3,qi=new r.Vector3,Xi=new r.Vector3,Ki=new r.Matrix4,Yi=new r.Box3,Qi=new r.Matrix4;function $i(e,t){t.radius=Math.max(t.radius,e.distanceToSquared(t.center))}function Zi(e){return e.x!==e.y}var Ji=class extends gi{constructor(e=1,t=1,i=1,r=-Hi,s=Hi,n=0,a=2*Gi,o=0,l=0){super(e,t,i),this.latStart=r,this.latEnd=s,this.lonStart=n,this.lonEnd=a,this.heightStart=o,this.heightEnd=l}getBoundingBox(e,t){Zi(this.radius);let i,{latStart:r,latEnd:s,lonStart:n,lonEnd:a,heightStart:o,heightEnd:l}=this,c=.5*(r+s),h=.5*(n+a),u=r>0,d=s<0;i=u?r:d?s:0;let{min:p,max:m}=e;p.setScalar(1/0),m.setScalar(-1/0),a-n<=Gi?(this.getCartographicToNormal(c,h,qi),Wi.set(0,0,1),ji.crossVectors(Wi,qi).normalize(),Wi.crossVectors(qi,ji).normalize(),t.makeBasis(ji,Wi,qi),Ki.copy(t).invert(),this.getCartographicToPosition(i,n,l,Xi).applyMatrix4(Ki),m.x=Math.abs(Xi.x),p.x=-m.x,this.getCartographicToPosition(s,n,l,Xi).applyMatrix4(Ki),m.y=Xi.y,this.getCartographicToPosition(s,h,l,Xi).applyMatrix4(Ki),m.y=Math.max(Xi.y,m.y),this.getCartographicToPosition(r,n,l,Xi).applyMatrix4(Ki),p.y=Xi.y,this.getCartographicToPosition(r,h,l,Xi).applyMatrix4(Ki),p.y=Math.min(Xi.y,p.y),this.getCartographicToPosition(c,h,l,Xi).applyMatrix4(Ki),m.z=Xi.z,this.getCartographicToPosition(r,n,o,Xi).applyMatrix4(Ki),p.z=Xi.z,this.getCartographicToPosition(s,n,o,Xi).applyMatrix4(Ki),p.z=Math.min(Xi.z,p.z)):(this.getCartographicToPosition(i,h,l,qi),qi.z=0,qi.length()<1e-10?qi.set(1,0,0):qi.normalize(),Wi.set(0,0,1),ji.crossVectors(qi,Wi).normalize(),t.makeBasis(ji,Wi,qi),Ki.copy(t).invert(),this.getCartographicToPosition(i,h+Hi,l,Xi).applyMatrix4(Ki),m.x=Math.abs(Xi.x),p.x=-m.x,this.getCartographicToPosition(s,0,d?o:l,Xi).applyMatrix4(Ki),m.y=Xi.y,this.getCartographicToPosition(r,0,u?o:l,Xi).applyMatrix4(Ki),p.y=Xi.y,this.getCartographicToPosition(i,h,l,Xi).applyMatrix4(Ki),m.z=Xi.z,this.getCartographicToPosition(i,a,l,Xi).applyMatrix4(Ki),p.z=Xi.z),e.getCenter(Xi),e.min.sub(Xi).multiplyScalar(1.0000000000001),e.max.sub(Xi).multiplyScalar(1.0000000000001),Xi.applyMatrix4(t),t.setPosition(Xi)}getBoundingSphere(e){Zi(this.radius),this.getBoundingBox(Yi,Qi),e.center.setFromMatrixPosition(Qi),e.radius=0;let t,{latStart:i,latEnd:r,lonStart:s,lonEnd:n,heightStart:a,heightEnd:o}=this,l=.5*(i+r),c=.5*(s+n);t=i>0?i:r<0?r:0,this.getCartographicToPosition(t,s,o,Xi),$i(Xi,e),this.getCartographicToPosition(r,s,o,Xi),$i(Xi,e),this.getCartographicToPosition(r,c,o,Xi),$i(Xi,e),this.getCartographicToPosition(i,s,o,Xi),$i(Xi,e),this.getCartographicToPosition(i,c,o,Xi),$i(Xi,e),this.getCartographicToPosition(l,c,o,Xi),$i(Xi,e),this.getCartographicToPosition(i,s,a,Xi),$i(Xi,e),n-s>Gi&&(this.getCartographicToPosition(t,c+Gi,o,Xi),$i(Xi,e)),e.radius=1.0000000000001*Math.sqrt(e.radius)}},er=new r.Vector3,tr=new r.Vector3,ir=new r.Vector3,rr=new r.Vector3,sr=new r.Vector3,nr=class{constructor(){this.sphere=null,this.obb=null,this.region=null,this.regionObb=null}intersectsRay(e){let t=this.sphere,i=this.obb||this.regionObb;return!(t&&!e.intersectsSphere(t)||i&&!i.intersectsRay(e))}intersectRay(e,t=null){let i=this.sphere,r=this.obb||this.regionObb,s=-1/0,n=-1/0;i&&e.intersectSphere(i,rr)&&(s=i.containsPoint(e.origin)?0:e.origin.distanceToSquared(rr)),r&&r.intersectRay(e,sr)&&(n=r.containsPoint(e.origin)?0:e.origin.distanceToSquared(sr));let a=Math.max(s,n);return a===-1/0?null:(e.at(Math.sqrt(a),t),t)}distanceToPoint(e){let t=this.sphere,i=this.obb||this.regionObb,r=-1/0,s=-1/0;return t&&(r=Math.max(t.distanceToPoint(e),0)),i&&(s=i.distanceToPoint(e)),r>s?r:s}intersectsFrustum(e){let t=this.obb||this.regionObb,i=this.sphere;return!(i&&!e.intersectsSphere(i)||t&&!t.intersectsFrustum(e))&&!(!i&&!t)}intersectsSphere(e){let t=this.obb||this.regionObb,i=this.sphere;return!(i&&!i.intersectsSphere(e)||t&&!t.intersectsSphere(e))&&!(!i&&!t)}intersectsOBB(e){let t=this.obb||this.regionObb,i=this.sphere;return!(i&&!e.intersectsSphere(i)||t&&!t.intersectsOBB(e))&&!(!i&&!t)}getOBB(e,t){let i=this.obb||this.regionObb;i?(e.copy(i.box),t.copy(i.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 i=new zi;er.set(e[3],e[4],e[5]),tr.set(e[6],e[7],e[8]),ir.set(e[9],e[10],e[11]);let r=er.length(),s=tr.length(),n=ir.length();er.normalize(),tr.normalize(),ir.normalize(),0===r&&er.crossVectors(tr,ir),0===s&&tr.crossVectors(er,ir),0===n&&ir.crossVectors(er,tr),i.transform.set(er.x,tr.x,ir.x,e[0],er.y,tr.y,ir.y,e[1],er.z,tr.z,ir.z,e[2],0,0,0,1).premultiply(t),i.box.min.set(-r,-s,-n),i.box.max.set(r,s,n),i.update(),this.obb=i}setSphereData(e,t,i,s,n){let a=new r.Sphere;a.center.set(e,t,i),a.radius=s,a.applyMatrix4(n),this.sphere=a}setRegionData(e,t,i,r,s,n,a){let o=new Ji(...e.radius,i,s,t,r,n,a),l=new zi;o.getBoundingBox(l.box,l.transform),l.update(),this.region=o,this.regionObb=l}},ar=new r.Matrix3;var or=class extends r.Frustum{constructor(){super(),this.points=Array(8).fill().map((()=>new r.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,i)=>{!function(e,t,i,r){let s=ar.set(e.normal.x,e.normal.y,e.normal.z,t.normal.x,t.normal.y,t.normal.z,i.normal.x,i.normal.y,i.normal.z);r.set(-e.constant,-t.constant,-i.constant),r.applyMatrix3(s.invert())}(e[0],e[1],e[2],t[i])}))}};function lr(e,t,i,s){try{return r.TextureUtils.getByteLength(e,t,i,s)}catch{return 0}}function cr(e){var t,i;if(!e)return 0;if(e.isExternalTexture)return(null==(t=e.userData)?void 0:t.byteLength)??0;let{format:r,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==(i=null==t?void 0:t.data)?void 0:i.byteLength)?e+=t.data.byteLength:e+=lr(t.width,t.height,r,s);return e}if(!n)return 0;let o=lr(n.width,n.height,r,s);return o*=e.generateMipmaps?4/3:1,o}var hr=Symbol("INITIAL_FRUSTUM_CULLED"),ur=new r.Matrix4,dr=new r.Vector3,pr=new r.Vector2,mr=new r.Vector3(1,0,0),fr=new r.Vector3(0,1,0),gr=()=>null;function yr(e,t){e.traverse((e=>{e.frustumCulled=e[hr]&&t}))}var vr=class extends De{get autoDisableRendererCulling(){return this._autoDisableRendererCulling}set autoDisableRendererCulling(e){this._autoDisableRendererCulling!==e&&(super._autoDisableRendererCulling=e,this.forEachLoadedModel((t=>{yr(t,!e)})))}constructor(...e){super(...e),this.accelerateRaycast=!0,this.group=new Fi(this),this.ellipsoid=yi.clone(),this.cameras=[],this.cameraMap=new Map,this.cameraInfo=[],this._upRotationMatrix=new r.Matrix4,this._bytesUsed=new WeakMap,this._autoDisableRendererCulling=!0,this.manager=new r.LoadingManager,this._listeners={}}addEventListener(e,t){r.EventDispatcher.prototype.addEventListener.call(this,e,t)}hasEventListener(e,t){return r.EventDispatcher.prototype.hasEventListener.call(this,e,t)}removeEventListener(e,t){r.EventDispatcher.prototype.removeEventListener.call(this,e,t)}dispatchEvent(e){r.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 i=this.root.engineData.boundingVolume;return!!i&&(i.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 i=t.engineData&&t.engineData.scene;i&&e(i,t)}),null,!1)}raycast(e,t){if(this.root)if(this.accelerateRaycast)Di(this,this.root,e,t);else{let i=e.firstHitOnly?[]:t;for(let t of this.activeTiles){let{scene:r}=t.engineData;this.invokeOnePlugin((s=>s.raycastTile&&s.raycastTile(t,r,e,i)))||e.intersectObject(r,!0,i)}e.firstHitOnly&&i.length>0&&(i.sort(((e,t)=>e.distance-t.distance)),t.push(i[0]))}}hasCamera(e){return this.cameraMap.has(e)}setCamera(e){let t=this.cameras,i=this.cameraMap;return!i.has(e)&&(i.set(e,new r.Vector2),t.push(e),this.dispatchEvent({type:"add-camera",camera:e}),!0)}setResolution(e,t,i){let r=this.cameraMap;if(!r.has(e))return!1;let s=t.isVector2?t.x:t,n=t.isVector2?t.y:i,a=r.get(e);return(a.width!==s||a.height!==n)&&(a.set(s,n),this.dispatchEvent({type:"camera-resolution-change"})),!0}getResolution(e,t){let i=this.cameraMap.get(e);return i?t.copy(i):null}setResolutionFromRenderer(e,t){return t.getSize(pr),this.setResolution(e,pr.x,pr.y)}deleteCamera(e){let t=this.cameras,i=this.cameraMap;if(i.has(e)){let r=t.indexOf(e);return t.splice(r,1),i.delete(e),this.dispatchEvent({type:"delete-camera",camera:e}),!0}return!1}loadRootTileset(...e){return super.loadRootTileset(...e).then((e=>{let{asset:t,extensions:i={}}=e;switch((t&&t.gltfUpAxis||"y").toLowerCase()){case"x":this._upRotationMatrix.makeRotationAxis(fr,-Math.PI/2);break;case"y":this._upRotationMatrix.makeRotationAxis(mr,Math.PI/2)}if("3DTILES_ellipsoid"in i){let e=i["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,i=this.cameraMap,s=this.cameraInfo;for(;s.length>t.length;)s.pop();for(;s.length<t.length;)s.push({frustum:new or,isOrthographic:!1,sseDenominator:-1,position:new r.Vector3,invScale:-1,pixelSize:0});dr.setFromMatrixScale(e.matrixWorldInverse),Math.abs(Math.max(dr.x-dr.y,dr.x-dr.z));for(let r=0,n=s.length;r<n;r++){let n=t[r],a=s[r],o=a.frustum,l=a.position,c=i.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;ur.copy(e.matrixWorld),ur.premultiply(n.matrixWorldInverse),ur.premultiply(n.projectionMatrix),o.setFromProjectionMatrix(ur,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,i=null){super.preprocessNode(e,t,i);let s=new r.Matrix4;if(e.transform){let t=e.transform;for(let e=0;e<16;e++)s.elements[e]=t[e]}i&&s.premultiply(i.engineData.transform);let n=(new r.Matrix4).copy(s).invert(),a=new nr;"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=gr}async parseTile(e,t,i,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)||i).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 ii(c);t.workingPath=o,t.fetchOptions=l,h=t.parse(e);break}case"i3dm":{let t=new Li(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 Ui(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 i=t.resourcePath||t.path||o;!/[\\/]$/.test(i)&&i.length&&(i+="/"),h=t.parseAsync(e,i).then((e=>{e.scene=e.scene||new r.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((r=>r.parseToMesh&&r.parseToMesh(e,t,i,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[hr]=e.frustumCulled,e.userData.tile=t})),yr(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 i=t[e];i&&i.isTexture&&T.push(i)}}})),n.aborted)for(let r=0,x=T.length;r<x;r++){let e=T[r];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,i=t.geometry,r=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=i.length;t<n;t++)i[t].dispose();for(let t=0,n=e.length;t<n;t++)e[t].dispose();for(let t=0,n=r.length;t<n;t++){let e=r[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 i=e.engineData.scene;i&&(t?(i.parent=this.group,i.updateMatrixWorld(!0)):i.parent=null)}setTileVisible(e,t){let i=e.engineData.scene,{activeTiles:r,group:s}=this;i&&(t?s.add(i):(s.remove(i),r.has(e)&&(i.parent=s))),super.setTileVisible(e,t)}calculateBytesUsed(e,t){let i=this._bytesUsed;return!i.has(e)&&t&&i.set(e,function(e){let t=new Set,i=0;return e.traverse((e=>{if(e.geometry&&!t.has(e.geometry)&&(i+=function(e){let t=0;for(const r in e.attributes){const i=e.getAttribute(r);t+=i.count*i.itemSize*i.array.BYTES_PER_ELEMENT}const i=e.getIndex();return t+=i?i.count*i.itemSize*i.array.BYTES_PER_ELEMENT:0,t}(e.geometry),t.add(e.geometry)),e.material){let r=e.material;for(let e in r){let s=r[e];s&&s.isTexture&&!t.has(s)&&(i+=cr(s),t.add(s))}}})),i}(t)),i.get(e)??null}calculateTileViewError(e,t){let i=e.engineData,r=this.cameras,s=this.cameraInfo,n=i.boundingVolume,a=!1,o=0,l=1/0,c=0,h=1/0;for(let u=0,d=r.length;u<d;u++){let t,i,r=s[u];if(r.isOrthographic){let s=r.pixelSize;t=e.geometricError/s,i=1/0}else{let s=r.sseDenominator;i=n.distanceToPoint(r.position),t=0===i?1/0:e.geometricError/(i*s)}let d=s[u].frustum;n.intersectsFrustum(d)&&(a=!0,o=Math.max(o,t),l=Math.min(l,i)),c=Math.max(c,t),h=Math.min(h,i)}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 Tr=new r.Matrix4,xr=new r.Matrix4,br=new r.Vector3,_r=new r.Vector3,wr=new r.Vector3,Mr=new r.Vector3,Sr=new r.Vector3,Ar=new r.Vector3,Cr=new r.Quaternion,Er=new r.Vector3,Rr=new r.Vector3,Pr=new r.Ray,Lr=new gi,Ur=new r.Vector2,Ir={};class Fr extends re{get tilesGroup(){return this.ellipsoidFrame}get ellipsoidFrame(){return this.ellipsoidGroup.matrixWorld}get ellipsoidFrameInverse(){const{ellipsoidGroup:e,ellipsoidFrame:t,_ellipsoidFrameInverse:i}=this;return e.matrixWorldInverse?e.matrixWorldInverse:i.copy(t).invert()}constructor(e=null,t=null,i=null,s=null){super(e,t,i),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 r.Quaternion,this.globeInertiaFactor=0,this.ellipsoid=yi.clone(),this.ellipsoidGroup=new r.Group,this._ellipsoidFrameInverse=new r.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||yi.clone(),this.ellipsoidGroup=t||new r.Group}getPivotPoint(e){const{camera:t,ellipsoidFrame:i,ellipsoidFrameInverse:r,ellipsoid:s}=this;return Mr.set(0,0,-1).transformDirection(t.matrixWorld),Pr.origin.copy(t.position),Pr.direction.copy(Mr),Pr.applyMatrix4(r),s.closestPointToRayEstimate(Pr,_r).applyMatrix4(i),(null===super.getPivotPoint(e)||br.subVectors(e,Pr.origin).dot(Pr.direction)>br.subVectors(_r,Pr.origin).dot(Pr.direction))&&e.copy(_r),e}getVectorToCenter(e){const{ellipsoidFrame:t,camera:i}=this;return e.setFromMatrixPosition(t).sub(i.position)}getDistanceToCenter(){return this.getVectorToCenter(_r).length()}getUpDirection(e,t){const{ellipsoidFrame:i,ellipsoidFrameInverse:r,ellipsoid:s}=this;_r.copy(e).applyMatrix4(r),s.getPositionToNormal(_r,t),t.transformDirection(i)}getCameraUpDirection(e){const{ellipsoidFrame:t,ellipsoidFrameInverse:i,ellipsoid:r,camera:s}=this;s.isOrthographicCamera?(this._getVirtualOrthoCameraPosition(_r),_r.applyMatrix4(i),r.getPositionToNormal(_r,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:i}=this;this._isNearControls()?this.scaleZoomOrientationAtEdges=this.zoomDelta<0:(0!==this.state&&1!==this._dragMode&&1!==this._rotationMode&&(i.visible=!1),this.scaleZoomOrientationAtEdges=!1);const r=this.needsUpdate||this._inertiaNeedsUpdate();super.update(e),this.adjustCamera(t),r&&this._isNearControls()&&(this.getCameraUpDirection(Ar),this._alignCameraUp(Ar,1),this.getCameraUpDirection(Ar),this._clampRotation(Ar))}adjustCamera(e){super.adjustCamera(e);const{ellipsoidFrame:t,ellipsoidFrameInverse:i,ellipsoid:s,nearMargin:n,farMargin:a}=this,o=Math.max(...s.radius);if(e.isPerspectiveCamera){const l=_r.setFromMatrixPosition(t).sub(e.position).length(),c=n*o,h=r.MathUtils.clamp((l-o)/c,0,1),u=r.MathUtils.lerp(1,1e3,h);e.near=Math.max(u,l-o-c),br.copy(e.position).applyMatrix4(i),s.getPositionToCartographic(br,Ir);const d=Math.max(s.getPositionElevation(br),2550),p=s.calculateHorizonDistance(Ir.lat,d);e.far=p+.1+o*a,e.updateProjectionMatrix()}else{this._getVirtualOrthoCameraPosition(e.position,e),e.updateMatrixWorld(),Tr.copy(e.matrixWorld).invert(),_r.setFromMatrixPosition(t).applyMatrix4(Tr);const i=-_r.z;e.near=i-o*(1+n),e.far=i+.1+o*a,e.position.addScaledVector(Mr,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:i,dampingFactor:r,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/r),h=Math.max(s.near,n,a,o),u=25e-5;if(wr.setFromMatrixPosition(l),0!==this.globeInertiaFactor){E(Pr,_r.set(0,0,-1),s),Pr.applyMatrix4(s.matrixWorldInverse),Pr.direction.normalize(),Pr.recast(-Pr.direction.dot(Pr.origin)).at(h/Pr.direction.z,_r),_r.applyMatrix4(s.matrixWorld),E(Pr,br.set(u,u,-1),s),Pr.applyMatrix4(s.matrixWorldInverse),Pr.direction.normalize(),Pr.recast(-Pr.direction.dot(Pr.origin)).at(h/Pr.direction.z,br),br.applyMatrix4(s.matrixWorld),_r.sub(wr).normalize(),br.sub(wr).normalize(),this.globeInertiaFactor*=c;const r=_r.angleTo(br)/e;(2*Math.acos(t.w)*this.globeInertiaFactor<r||!i)&&(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)),wr.setFromMatrixPosition(l),Cr.identity().slerp(t,this.globeInertiaFactor*e),A(wr,Cr,xr),s.matrixWorld.premultiply(xr),s.matrixWorld.decompose(s.position,s.quaternion,_r))}_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:i,pivotPoint:r,pointerTracker:s,domElement:n,ellipsoidFrame:a,ellipsoidFrameInverse:o}=this,l=br,c=Sr;s.getCenterPoint(Ur),C(Ur,n,Ur),E(t,Ur,i),t.ray.applyMatrix4(o);const h=_r.copy(r).applyMatrix4(o).length();if(Lr.radius.setScalar(h),!Lr.intersectRay(t.ray,_r))return this.resetState(),void this._updateInertia(e);_r.applyMatrix4(a),wr.setFromMatrixPosition(a),l.subVectors(r,wr).normalize(),c.subVectors(_r,wr).normalize(),Cr.setFromUnitVectors(c,l),A(wr,Cr,xr),i.matrixWorld.premultiply(xr),i.matrixWorld.decompose(i.position,i.quaternion,_r),s.getMoveDistance()/e<2*window.devicePixelRatio?this.inertiaStableFrames++:(this.globeInertia.copy(Cr),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:i,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=r.MathUtils.clamp(r.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())){Mr.set(0,0,-1).transformDirection(n.matrixWorld).normalize(),Rr.copy(this.up).multiplyScalar(-1),this.getUpDirection(s,Er);const e=r.MathUtils.clamp(r.MathUtils.mapLinear(-Er.dot(Rr),1,.95,0,1),0,1),t=1-Mr.dot(Rr),i=n.isOrthographicCamera?.05:1,a=r.MathUtils.clamp(3*l,0,1),o=Math.min(e*t*i*a,.1);Rr.lerpVectors(Mr,Rr,o).normalize(),Cr.setFromUnitVectors(Mr,Rr),A(s,Cr,xr),n.matrixWorld.premultiply(xr),n.matrixWorld.decompose(n.position,n.quaternion,Rr),this.zoomDirection.subVectors(s,n.position).normalize()}super._updateZoom()}else if(n.isPerspectiveCamera){const s=this._getPerspectiveTransitionDistance(),n=this._getMaxPerspectiveDistance(),a=r.MathUtils.mapLinear(this.getDistanceToCenter(),s,n,0,1);this._tiltTowardsCenter(r.MathUtils.lerp(0,.4,a*l)),this._alignCameraUpToNorth(r.MathUtils.lerp(0,.2,a*l));const o=e*(this.getDistanceToCenter()-t.radius.x)*i*.0025,c=Math.max(o,Math.min(this.getDistanceToCenter()-n,0));this.getVectorToCenter(_r).normalize(),this.camera.position.addScaledVector(_r,c),this.camera.updateMatrixWorld(),this.zoomDelta=0}else{const e=this._getOrthographicTransitionZoom(),t=this._getMinOrthographicZoom(),s=r.MathUtils.mapLinear(n.zoom,e,t,0,1);this._tiltTowardsCenter(r.MathUtils.lerp(0,.4,s*l)),this._alignCameraUpToNorth(r.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*i,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;Ar.set(0,0,1).transformDirection(t),this._alignCameraUp(Ar,e)}_tiltTowardsCenter(e){const{camera:t,ellipsoidFrame:i}=this;Mr.set(0,0,-1).transformDirection(t.matrixWorld).normalize(),_r.setFromMatrixPosition(i).sub(t.position).normalize(),_r.lerp(Mr,1-e).normalize(),Cr.setFromUnitVectors(Mr,_r),t.quaternion.premultiply(Cr),t.updateMatrixWorld()}_getPerspectiveTransitionDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const i=Math.max(...t.radius),s=2*Math.atan(Math.tan(r.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),n=i/Math.tan(r.MathUtils.DEG2RAD*e.fov*.5),a=i/Math.tan(.5*s);return Math.max(n,a)}_getMaxPerspectiveDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const i=Math.max(...t.radius),s=2*Math.atan(Math.tan(r.MathUtils.DEG2RAD*e.fov*.5)*e.aspect),n=i/Math.tan(r.MathUtils.DEG2RAD*e.fov*.5),a=i/Math.tan(.5*s);return 2*Math.max(n,a)}_getOrthographicTransitionZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const i=e.top-e.bottom,r=e.right-e.left;return 2*Math.max(i,r)/(2*Math.max(...t.radius))}_getMinOrthographicZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const i=e.top-e.bottom,r=e.right-e.left;return.7*Math.min(i,r)/(2*Math.max(...t.radius))}_getVirtualOrthoCameraPosition(e,t=this.camera){const{ellipsoidFrame:i,ellipsoidFrameInverse:r,ellipsoid:s}=this;if(!t.isOrthographicCamera)throw new Error;Pr.origin.copy(t.position),Pr.direction.set(0,0,-1).transformDirection(t.matrixWorld),Pr.applyMatrix4(r),s.closestPointToRayEstimate(Pr,br).applyMatrix4(i);const n=t.top-t.bottom,a=t.right-t.left,o=Math.max(n,a)/t.zoom;Mr.set(0,0,-1).transformDirection(t.matrixWorld);const l=br.sub(t.position).dot(Mr);e.copy(t.position).addScaledVector(Mr,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:i,ellipsoidFrameInverse:r}=this;Pr.copy(e.ray).applyMatrix4(r);const s=t.intersectRay(Pr,_r);return null!==s?{point:s.clone().applyMatrix4(i)}:null}return t}}const kr=new WeakMap,Dr="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,Or="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,Br="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 Nr extends r.Loader{constructor(e){super(e),this.decoderPaths={js:Or,wasm:Dr,dep_js:Br},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=r.LoaderUtils.resolveURL("draco_wasm_wrapper.js",e),t.wasm=r.LoaderUtils.resolveURL("draco_decoder.wasm",e),t.dep_js=r.LoaderUtils.resolveURL("draco_decoder.js",e)),this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,s){const n=new r.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)}),i,s)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,r.SRGBColorSpace,i).catch(i)}decodeDracoFile(e,t,i,s,n=r.LinearSRGBColorSpace,a=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:n};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const i=JSON.stringify(t);if(kr.has(e)){const t=kr.get(e);if(t.key===i)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 r;const s=this.workerNextTaskID++,n=e.byteLength,a=this._getWorker(s,n).then((i=>(r=i,new Promise(((i,n)=>{r._callbacks[s]={resolve:i,reject:n},r.postMessage({type:"decode",id:s,taskConfig:t,buffer:e},[e])}))))).then((e=>this._createGeometry(e.geometry)));return a.catch((()=>!0)).then((()=>{r&&s&&this._releaseTask(r,s)})),kr.set(e,{key:i,promise:a}),a}_createGeometry(e){const t=new r.BufferGeometry;e.index&&t.setIndex(new r.BufferAttribute(e.index.array,1));for(let i=0;i<e.attributes.length;i++){const{name:s,array:n,itemSize:a,stride:o,vertexColorSpace:l}=e.attributes[i];let c;if(a===o)c=new r.BufferAttribute(n,a);else{const e=new r.InterleavedBuffer(n,o);c=new r.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!==r.SRGBColorSpace)return;const i=new r.Color;for(let s=0,n=e.count;s<n;s++)i.fromBufferAttribute(e,s),r.ColorManagement.colorSpaceToWorking(i,r.SRGBColorSpace),e.setXYZ(s,i.r,i.g,i.b)}_loadLibrary(e,t){const i=new r.FileLoader(this.manager);return i.setResponseType(t),i.setWithCredentials(this.withCredentials),new Promise(((t,r)=>{i.load(e,t,void 0,r)}))}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e="object"!=typeof WebAssembly||"js"===this.decoderConfig.type,t=[],{decoderPaths:i}=this;if(e){if(null===i.dep_js)throw new Error("THREE.DRACOLoader: WebAssembly is required when using a custom decoder paths.");t.push(this._loadLibrary(i.dep_js,"text"))}else t.push(this._loadLibrary(i.js,"text")),t.push(this._loadLibrary(i.wasm,"arraybuffer"));return this.decoderPending=Promise.all(t).then((t=>{const i=t[0];e||(this.decoderConfig.wasmBinary=t[1]);const r=Vr.toString(),s=["/* draco decoder */",i,"","/* worker */",r.substring(r.indexOf("{")+1,r.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 i=t.data;switch(i.type){case"decode":e._callbacks[i.id].resolve(i);break;case"error":e._callbacks[i.id].reject(i)}},this.workerPool.push(e)}else this.workerPool.sort((function(e,t){return e._taskLoad>t._taskLoad?-1:1}));const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i}))}_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 Vr(){let e,t;function i(e,t,i,r,s,n){const a=i.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(i,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,i=f.length;t<i;t++){for(let i=0;i<o;i++)g[e+i]=f[t*o+i];e+=u}}return e._free(m),{name:r,count:a,itemSize:o,array:g,stride:u}}onmessage=function(r){const s=r.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 r=s.buffer,n=s.taskConfig;t.then((e=>{const t=e.draco,a=new t.Decoder;try{const e=function(e,t,r,s){const n=s.attributeIDs,a=s.attributeTypes;let o,l;const c=t.GetEncodedGeometryType(r);if(c===e.TRIANGULAR_MESH)o=new e.Mesh,l=t.DecodeArrayToMesh(r,r.byteLength,o);else{if(c!==e.POINT_CLOUD)throw new Error("THREE.DRACOLoader: Unexpected geometry type.");o=new e.PointCloud,l=t.DecodeArrayToPointCloud(r,r.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 r=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=i(e,t,o,u,r,l);"color"===u&&(d.vertexColorSpace=s.vertexColorSpace),h.attributes.push(d)}c===e.TRIANGULAR_MESH&&(h.index=function(e,t,i){const r=i.num_faces(),s=3*r,n=4*s,a=e._malloc(n);t.GetTrianglesUInt32Array(i,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(r),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)}}))}}}var zr=class{constructor(e={}){let{apiToken:t,autoRefreshToken:i=!1}=e;this.apiToken=t,this.autoRefreshToken=i,this.authURL=null,this._tokenRefreshPromise=null,this._bearerToken=null,this._bearerHostname=null}async fetch(e,t){await this._tokenRefreshPromise;let i={...t},r=null!==this._bearerHostname&&new URL(e).host===this._bearerHostname;r&&(i.headers={...i.headers,Authorization:this._bearerToken});let s=await fetch(e,i);return r&&s.status>=400&&s.status<=499&&this.autoRefreshToken?(await this.refreshToken(t),i.headers.Authorization=this._bearerToken,fetch(e,i)):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}},Gr="https://tile.googleapis.com/v1/createSession",Hr=class{get isMapTilesSession(){return this.authURL===Gr}constructor(e={}){let{apiToken:t,sessionOptions:i=null,autoRefreshToken:r=!1}=e;this.apiToken=t,this.autoRefreshToken=r,this.authURL=Gr,this.sessionToken=null,this.sessionOptions=i,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 i=new URL(e),r=i.host===this._authHostname;r&&(i.searchParams.set("key",this.apiToken),this.sessionToken&&i.searchParams.set("session",this.sessionToken));let s=await fetch(i,t);return r&&s.status>=400&&s.status<=499&&this.autoRefreshToken&&(await this.refreshToken(t),this.sessionToken&&i.searchParams.set("session",this.sessionToken),s=await fetch(i,t)),null!==this.sessionToken||this.isMapTilesSession?s:s.json().then((e=>(this.sessionToken=jr(e),e)))}refreshToken(e){if(null===this._tokenRefreshPromise){let t=new URL(this.authURL);t.searchParams.set("key",this.apiToken);let i={...e};this.isMapTilesSession&&(i.method="POST",i.body=JSON.stringify(this.sessionOptions),i.headers=i.headers||{},i.headers={...i.headers,"Content-Type":"application/json"}),this._tokenRefreshPromise=fetch(t,i).then((e=>{if(!e.ok)throw Error(`GoogleCloudAuth: Failed to load data with error code ${e.status}`);return e.json()})).then((e=>(this.sessionToken=jr(e),this._tokenRefreshPromise=null,e)))}return this._tokenRefreshPromise}};function jr(e){if("session"in e)return e.session;{let t=null;return Ee(e.root,(e=>{if(e.content&&e.content.uri){let[,i]=e.content.uri.split("?");return t=new URLSearchParams(i).get("session"),!0}return!1})),t}}var Wr=class{constructor(){this.creditsCount={}}_adjustAttributions(e,t){let i=this.creditsCount,r=e.split(/;/g);for(let s=0,n=r.length;s<n;s++){let e=r[s];e in i||(i[e]=0),i[e]+=t?1:-1,i[e]<=0&&delete i[e]}}addAttributions(e){this._adjustAttributions(e,!0)}removeAttributions(e){this._adjustAttributions(e,!1)}toString(){return Object.entries(this.creditsCount).sort(((e,t)=>{let i=e[1];return t[1]-i})).map((e=>e[0])).join("; ")}},qr=class{constructor({apiToken:e,sessionOptions:t=null,autoRefreshToken:i=!1,logoUrl:r=null,useRecommendedSettings:s=!0}){this.name="GOOGLE_CLOUD_AUTH_PLUGIN",this.apiToken=e,this.useRecommendedSettings=s,this.logoUrl=r,this.auth=new Hr({apiToken:e,autoRefreshToken:i,sessionOptions:t}),this.tiles=null,this._visibilityChangeCallback=null,this._attributionsManager=new Wr,this._logoAttribution={value:"",type:"image",collapsible:!1},this._attribution={value:"",type:"string",collapsible:!0}}init(e){let{useRecommendedSettings:t,auth:i}=this;e.resetFailedTiles(),e.rootURL??(e.rootURL="https://tile.googleapis.com/v1/3dtiles/root.json"),i.sessionOptions||(i.authURL=e.rootURL),t&&!i.isMapTilesSession&&(e.errorTarget=20),this.tiles=e,this._visibilityChangeCallback=({tile:e,visible:t})=>{var i,r;let s=(null==(r=null==(i=e.engineData.metadata)?void 0:i.asset)?void 0:r.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)}},Xr=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:i=null,autoRefreshToken:r=!1,useRecommendedSettings:s=!0,assetTypeHandler:n=(e,t,i)=>{}}=e;this.name="CESIUM_ION_AUTH_PLUGIN",this.auth=new zr({apiToken:t,autoRefreshToken:r}),this.assetId=i,this.autoRefreshToken=r,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 i=new URL(e.options.url);t.rootURL=e.options.url,t.registerPlugin(new qr({apiToken:i.searchParams.get("key"),autoRefreshToken:this.autoRefreshToken,useRecommendedSettings:this.useRecommendedSettings}))}else{"3DTILES"!==e.type&&this.assetTypeHandler(e.type,t,e),t.rootURL=e.url;let i=new URL(e.url);i.searchParams.has("v")&&-1===this._tileSetVersion&&(this._tileSetVersion=i.searchParams.get("v")),e.attributions&&(this._attributions=e.attributions.map((e=>({value:e.html,type:"html",collapsible:e.collapsible}))))}}};function Kr(e){return"OCTREE"===e.implicitTilingData.root.implicitTiling.subdivisionScheme}function Yr(e){return Kr(e)?8:4}var Qr=class{constructor(e,t){this.parent=e,this.children=[],this.geometricError=0,this.boundingVolume=null;let[i,r,s]=function(e,t){if(!e)return[0,0,0];let i=e.implicitTilingData.x,r=e.implicitTilingData.y,s=e.implicitTilingData.z;return[2*i+t%2,2*r+Math.floor(t/2)%2,Kr(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:i,y:r,z:s}}static clone(e){return{parent:e.parent,children:[],geometricError:e.geometricError,boundingVolume:e.boundingVolume,implicitTilingData:{...e.implicitTilingData}}}},$r=class extends ze{constructor(e){super(),this.tile=e,this.rootTile=e.implicitTilingData.root,this.workingPath=null}parseBuffer(e){let t=new DataView(e),i=0;Oe(t);i+=4;let r=t.getUint32(i,!0);i+=4;let s=t.getUint32(i,!0);i+=8;let n=t.getUint32(i,!0);i+=8;let a=JSON.parse(Ne(new Uint8Array(e,i,s)));return i+=s,{version:r,subtreeJson:a,subtreeByte:e.slice(i,i+n)}}async parse(e){let t=this.parseBuffer(e),i=t.subtreeJson;i.contentAvailabilityHeaders=[].concat(i.contentAvailability);let r=this.preprocessBuffers(i.buffers),s=this.preprocessBufferViews(i.bufferViews,r);this.markActiveBufferViews(i,s);let n=await this.requestActiveBuffers(r,t.subtreeByte),a=this.parseActiveBufferViews(s,n);this.parseAvailability(t,i,a),this.expandSubtree(this.tile,t)}markActiveBufferViews(e,t){let i,r=e.tileAvailability;isNaN(r.bitstream)?isNaN(r.bufferView)||(i=t[r.bufferView]):i=t[r.bitstream],i&&(i.isActive=!0,i.bufferHeader.isActive=!0);let s=e.contentAvailabilityHeaders;for(let a=0;a<s.length;a++)i=void 0,isNaN(s[a].bitstream)?isNaN(s[a].bufferView)||(i=t[s[a].bufferView]):i=t[s[a].bitstream],i&&(i.isActive=!0,i.bufferHeader.isActive=!0);i=void 0;let n=e.childSubtreeAvailability;isNaN(n.bitstream)?isNaN(n.bufferView)||(i=t[n.bufferView]):i=t[n.bitstream],i&&(i.isActive=!0,i.bufferHeader.isActive=!0)}async requestActiveBuffers(e,t){let i=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.isActive)if(r.isExternal){let e=this.parseImplicitURIBuffer(this.tile,this.rootTile.implicitTiling.subtrees.uri,r.uri),t=fetch(e,this.fetchOptions).then((e=>{if(!e.ok)throw Error(`SUBTREELoader: Failed to load external buffer from ${r.uri} with error code ${e.status}.`);return e.arrayBuffer()})).then((e=>new Uint8Array(e)));i.push(t)}else i.push(Promise.resolve(new Uint8Array(t)));else i.push(Promise.resolve())}let r=await Promise.all(i),s={};for(let n=0;n<r.length;n++){let e=r[n];e&&(s[n]=e)}return s}parseActiveBufferViews(e,t){let i={};for(let r=0;r<e.length;r++){let s=e[r];if(!s.isActive)continue;let n=s.byteOffset,a=n+s.byteLength;i[r]=t[s.buffer].slice(n,a)}return i}preprocessBuffers(e=[]){for(let t=0;t<e.length;t++){let i=e[t];i.isActive=!1,i.isExternal=!!i.uri}return e}preprocessBufferViews(e=[],t){for(let i=0;i<e.length;i++){let r=e[i];r.bufferHeader=t[r.buffer],r.isActive=!1,r.isExternal=r.bufferHeader.isExternal}return e}parseAvailability(e,t,i){let r=Yr(this.rootTile),s=this.rootTile.implicitTiling.subtreeLevels,n=(r**+s-1)/(r-1),a=r**+s;e._tileAvailability=this.parseAvailabilityBitstream(t.tileAvailability,i,n),e._contentAvailabilityBitstreams=[];for(let o=0;o<t.contentAvailabilityHeaders.length;o++){let r=this.parseAvailabilityBitstream(t.contentAvailabilityHeaders[o],i,n);e._contentAvailabilityBitstreams.push(r)}e._childSubtreeAvailability=this.parseAvailabilityBitstream(t.childSubtreeAvailability,i,a)}parseAvailabilityBitstream(e,t,i){if(!isNaN(e.constant))return{constant:!!e.constant,lengthBits:i};let r;return isNaN(e.bitstream)?isNaN(e.bufferView)||(r=t[e.bufferView]):r=t[e.bitstream],{bitstream:r,lengthBits:i}}expandSubtree(e,t){let i=Qr.clone(e);for(let n=0;t&&n<t._contentAvailabilityBitstreams.length;n++)if(t&&this.getBit(t._contentAvailabilityBitstreams[n],0)){i.content={uri:this.parseImplicitURI(e,this.rootTile.content.uri)};break}e.children.push(i);let r=this.transcodeSubtreeTiles(i,t),s=this.listChildSubtrees(t,r);for(let n=0;n<s.length;n++){let e=s[n],t=e.tile,i=this.deriveChildTile(null,t,null,e.childMortonIndex);i.content={uri:this.parseImplicitURI(i,this.rootTile.implicitTiling.subtrees.uri)},t.children.push(i)}}transcodeSubtreeTiles(e,t){let i=[e],r=[];for(let s=1;s<this.rootTile.implicitTiling.subtreeLevels;s++){let e=Yr(this.rootTile),n=(e**+s-1)/(e-1),a=e*i.length;for(let s=0;s<a;s++){let a=n+s,o=i[s>>Math.log2(e)];if(!this.getBit(t._tileAvailability,a)){r.push(void 0);continue}let l=this.deriveChildTile(t,o,a,s);o.children.push(l),r.push(l)}i=r,r=[]}return i}deriveChildTile(e,t,i,r){let s=new Qr(t,r);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],i)){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 i=t>>3,r=t%8;return 1==(new Uint8Array(e.bitstream)[i]>>r&1)}getTileBoundingVolume(e){let t={};if(this.rootTile.boundingVolume.region){let i=[...this.rootTile.boundingVolume.region],r=i[0],s=i[2],n=i[1],a=i[3],o=(s-r)/2**e.implicitTilingData.level,l=(a-n)/2**e.implicitTilingData.level;i[0]=r+o*e.implicitTilingData.x,i[2]=r+o*(e.implicitTilingData.x+1),i[1]=n+l*e.implicitTilingData.y,i[3]=n+l*(e.implicitTilingData.y+1);for(let e=0;e<4;e++){let t=i[e];t<-Math.PI?i[e]+=2*Math.PI:t>Math.PI&&(i[e]-=2*Math.PI)}if(Kr(e)){let t=i[4],r=(i[5]-t)/2**e.implicitTilingData.level;i[4]=t+r*e.implicitTilingData.z,i[5]=t+r*(e.implicitTilingData.z+1)}t.region=i}if(this.rootTile.boundingVolume.box){let i=[...this.rootTile.boundingVolume.box],r=2**e.implicitTilingData.level-1,s=2**-e.implicitTilingData.level,n=Kr(e)?3:2;for(let t=0;t<n;t++){i[3+3*t+0]*=s,i[3+3*t+1]*=s,i[3+3*t+2]*=s;let n=i[3+3*t+0],a=i[3+3*t+1],o=i[3+3*t+2],l=0===t?e.implicitTilingData.x:1===t?e.implicitTilingData.y:e.implicitTilingData.z;i[0]+=2*n*(-.5*r+l),i[1]+=2*a*(-.5*r+l),i[2]+=2*o*(-.5*r+l)}t.box=i}return t}getGeometricError(e){return this.rootTile.geometricError/2**e.implicitTilingData.level}listChildSubtrees(e,t){let i=[],r=Yr(this.rootTile);for(let s=0;s<t.length;s++){let n=t[s];if(void 0!==n)for(let t=0;t<r;t++){let a=s*r+t;this.getBit(e._childSubtreeAvailability,a)&&i.push({tile:n,childMortonIndex:a})}}return i}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,i){let r=this.parseImplicitURI(e,t),s=new URL(r,this.workingPath+"/");return s.pathname=s.pathname.substring(0,s.pathname.lastIndexOf("/")),new URL(s.pathname+"/"+i,this.workingPath+"/").toString()}},Zr=class{constructor(){this.name="IMPLICIT_TILING_PLUGIN"}init(e){this.tiles=e}preprocessNode(e,t,i){var r;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==(r=e.content)?void 0:r.uri)&&(e.internal.hasUnrenderableContent=!0,e.internal.hasRenderableContent=!1)}parseTile(e,t,i){if(/^subtree$/i.test(i)){let i=new $r(t);return i.workingPath=t.internal.basePath,i.fetchOptions=this.tiles.fetchOptions,i.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 Jr(e){return e>>1^-(1&e)}var es=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,i=new DataView(e),r=()=>{let e=i.getFloat64(t,!0);return t+=8,e},s=()=>{let e=i.getFloat32(t,!0);return t+=4,e},n=()=>{let e=i.getUint32(t,!0);return t+=4,e},a=()=>{let e=i.getUint8(t);return t+=1,e},o=(i,r)=>{let s=new r(e,t,i);return t+=i*r.BYTES_PER_ELEMENT,s},l={center:[r(),r(),r()],minHeight:s(),maxHeight:s(),sphereCenter:[r(),r(),r()],sphereRadius:r(),horizonOcclusionPoint:[r(),r(),r()]},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+=Jr(h[I]),y+=Jr(u[I]),v+=Jr(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<i.byteLength;){let e=a(),t=n();if(1===e){let t=o(2*c,Uint8Array),i=new Float32Array(3*c);for(let e=0;e<c;e++){let r=t[2*e+0]/255*2-1,s=t[2*e+1]/255*2-1,n=1-(Math.abs(r)+Math.abs(s));if(n<0){let e=r;r=(1-Math.abs(s))*ts(e),s=(1-Math.abs(e))*ts(s)}let a=Math.sqrt(r*r+s*s+n*n);i[3*e+0]=r/a,i[3*e+1]=s/a,i[3*e+2]=n/a}U.octvertexnormals={extensionId:e,normals:i}}else if(2===e){let i=1===t?1:256;U.watermask={extensionId:e,mask:o(i*i,Uint8Array),size:i}}else if(4===e){let t=o(n(),Uint8Array),i=(new TextDecoder).decode(t);U.metadata={extensionId:e,json:JSON.parse(i)}}}return{header:l,indices:_,vertexData:{u:p,v:m,height:f},edgeIndices:L,extensions:U}}};function ts(e){return e<0?-1:1}const is=new r.OrthographicCamera(-1,1,1,-1,0,1);class rs extends r.BufferGeometry{constructor(){super(),this.setAttribute("position",new r.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new r.Float32BufferAttribute([0,2,0,0,2,0],2))}}const ss=new rs;class ns{constructor(e){this._mesh=new r.Mesh(ss,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,is)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}var as=new r.Vector3,os=new r.Vector3;var ls=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=r.MathUtils.mapLinear(e,0,1,-1,1);return 2*Math.atan(Math.exp(t*Math.PI))-Math.PI/2}return r.MathUtils.mapLinear(e,0,1,-Math.PI/2,Math.PI/2)}convertNormalizedToLongitude(e){return"none"===this.scheme?e:r.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):r.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,i=e-t;return i<0&&(i=e+t),this.isMercator?Math.abs(this.convertNormalizedToLatitude(e)-this.convertNormalizedToLatitude(i))/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 i=[e,t];return i[0]=this.convertLongitudeToNormalized(i[0]),i[1]=this.convertLatitudeToNormalized(i[1]),i}toNormalizedRange(e){return[...this.toNormalizedPoint(e[0],e[1]),...this.toNormalizedPoint(e[2],e[3])]}toCartographicPoint(e,t){let i=[e,t];return i[0]=this.convertNormalizedToLongitude(i[0]),i[1]=this.convertNormalizedToLatitude(i[1]),i}toCartographicRange(e){return[...this.toCartographicPoint(e[0],e[1]),...this.toCartographicPoint(e[2],e[3])]}clampToBounds(e,t=!1){let i,s=[...e];i=t?[0,0,1,1]:this.getBounds();let[n,a,o,l]=i;return s[0]=r.MathUtils.clamp(s[0],n,o),s[2]=r.MathUtils.clamp(s[2],n,o),s[1]=r.MathUtils.clamp(s[1],a,l),s[3]=r.MathUtils.clamp(s[3],a,l),s}};function cs(e,t){let[i,r,s,n]=e,[a,o,l,c]=t;return!(i>=l||s<=a||r>=c||n<=o)}var hs=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 ls("none"),this._levels=[]}setLevel(e,t={}){let i=this._levels;for(;i.length<e;)i.push(null);let{tileSplitX:r=2,tileSplitY:s=2}=t,{tilePixelWidth:n=256,tilePixelHeight:a=256,tileCountX:o=r**e,tileCountY:l=s**e,tileBounds:c=null}=t,{pixelWidth:h=n*o,pixelHeight:u=a*l}=t;i[e]={tilePixelWidth:n,tilePixelHeight:a,pixelWidth:h,pixelHeight:u,tileCountX:o,tileCountY:l,tileSplitX:r,tileSplitY:s,tileBounds:c}}generateLevels(e,t,i,r={}){let{minLevel:s=0,tilePixelWidth:n=256,tilePixelHeight:a=256}=r,o=e-1,{pixelWidth:l=n*t*2**o,pixelHeight:c=a*i*2**o}=r;for(let h=s;h<e;h++){let t=e-h-1,i=Math.ceil(l*2**-t),r=Math.ceil(c*2**-t),s=Math.ceil(i/n),o=Math.ceil(r/a);this.setLevel(h,{tilePixelWidth:n,tilePixelHeight:a,pixelWidth:i,pixelHeight:r,tileCountX:s,tileCountY:o})}}getLevel(e){return this._levels[e]}setContentBounds(e,t,i,r){this._contentBounds=[e,t,i,r]}setProjection(e){this.projection=e}getTileAtPoint(e,t,i,s=!1){let{flipY:n}=this,{tileCountY:a,tileBounds:o,pixelHeight:l,pixelWidth:c,tilePixelHeight:h,tilePixelWidth:u}=this.getLevel(i),d=u/c,p=h/l;if(s||([e,t]=this.toNormalizedPoint(e,t)),o){let i=this.toNormalizedRange(o);e=r.MathUtils.mapLinear(e,i[0],i[2],0,1),t=r.MathUtils.mapLinear(t,i[1],i[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,i,s,n,a=!1){let o=[e,t,i,s],l=this.getContentBounds(a),c=this.getLevel(n).tileBounds;if(!cs(o,l)||c&&(a&&(c=this.toNormalizedRange(c)),!cs(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]:[r.MathUtils.clamp(v,0,g-1),r.MathUtils.clamp(T,0,y-1),r.MathUtils.clamp(x,0,g-1),r.MathUtils.clamp(b,0,y-1)]}getTileExists(e,t,i){let[r,s,n,a]=this.contentBounds,[o,l,c,h]=this.getTileBounds(e,t,i);return!(o>=c||l>=h)&&o<=n&&l<=a&&c>=r&&h>=s}getContentBounds(e=!1){let{projection:t}=this,i=[...this.contentBounds];return e&&(i[0]=t.convertLongitudeToNormalized(i[0]),i[1]=t.convertLatitudeToNormalized(i[1]),i[2]=t.convertLongitudeToNormalized(i[2]),i[3]=t.convertLatitudeToNormalized(i[3])),i}getTileContentUVBounds(e,t,i){let[s,n,a,o]=this.getTileBounds(e,t,i,!0,!0),[l,c,h,u]=this.getTileBounds(e,t,i,!0,!1);return[r.MathUtils.mapLinear(s,l,h,0,1),r.MathUtils.mapLinear(n,c,u,0,1),r.MathUtils.mapLinear(a,l,h,0,1),r.MathUtils.mapLinear(o,c,u,0,1)]}getTileBounds(e,t,i,s=!1,n=!0){let{flipY:a,pixelOverlap:o,projection:l}=this,{tilePixelWidth:c,tilePixelHeight:h,pixelWidth:u,pixelHeight:d,tileBounds:p}=this.getLevel(i),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]=r.MathUtils.mapLinear(v[0],0,1,e[0],e[2]),v[2]=r.MathUtils.mapLinear(v[2],0,1,e[0],e[2]),v[1]=r.MathUtils.mapLinear(v[1],0,1,e[1],e[3]),v[3]=r.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 i=[...e],[s,n,a,o]=this.getContentBounds(t);return i[0]=r.MathUtils.clamp(i[0],s,a),i[1]=r.MathUtils.clamp(i[1],n,o),i[2]=r.MathUtils.clamp(i[2],s,a),i[3]=r.MathUtils.clamp(i[3],n,o),i}clampToBounds(e,t=!1){return this.projection.clampToBounds(e,t)}},us=Symbol("TILE_X"),ds=Symbol("TILE_Y"),ps=Symbol("TILE_LEVEL"),ms=Symbol("OVERLAY_RANGE"),fs=Symbol("OVERLAY_LEVEL"),gs=new r.Vector3,ys=new r.Vector3,vs=new r.Sphere,Ts=class{constructor(e={}){let{overlay:t=null,shape:i="ellipsoid",endCaps:r=!0,center:s=!0,useRecommendedSettings:n=!0,applyOverlayTexture:a=!1}=e;this.priority=-10,this.tiles=null,this.overlay=t,this.shape=i,this.endCaps=r,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,i,r,s){if("generated_surface"!==i)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[us],i=t[ds],r=t[ps],o=this._tiling.getTileBounds(e,i,r,!0,!1);if(a.hasContent(o,r)){try{await a.lockTexture(o,r)}catch(l){if("AbortError"!==l.name)throw l;return null}let e=a.getTexture(o,r);if(t[ms]=o,t[fs]=r,s.aborted)return a.releaseTexture(o,r),delete t[ms],delete t[fs],null;n.material.map=e,n.material.needsUpdate=!0}}return n}preprocessNode(e){let t=this._tiling.maxLevel;e[ps]<t&&null!==e.parent&&this.expandChildren(e)}disposeTile(e){let t=e[ms];this.overlay&&t&&(this.overlay.releaseTexture(t,e[fs]),delete e[ms],delete e[fs])}dispose(){this.tiles.forEachLoadedModel(((e,t)=>{this.disposeTile(t)}))}getCartographicFromPosition(e,t={}){let{_tiling:i}=this,{projection:r}=i;if(!r.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/i.aspectRatio+(s?.5:0),a=e.y+(s?.5:0);return t.lat=r.convertNormalizedToLatitude(a),t.lon=r.convertNormalizedToLongitude(n),t}getPositionFromCartographic(e,t,i=new r.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,i);let{center:a}=this,o=n.convertLongitudeToNormalized(t),l=n.convertLatitudeToNormalized(e);return i.x=(o-(a?.5:0))*s.aspectRatio,i.y=l-(a?.5:0),i.z=0,i}_useEllipsoid(){return this._tiling.projection.isCartographic&&"ellipsoid"===this.shape}_createPlanarMesh(e){let t=e[us],i=e[ds],s=e[ps],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 r.PlaneGeometry(2*a,2*o),d=new r.Mesh(u,new r.MeshBasicMaterial);d.position.set(l,c,h);let p=this._tiling.getTileContentUVBounds(t,i,s),{uv:m}=u.attributes;for(let f=0;f<m.count;f++)m.setXY(f,r.MathUtils.mapLinear(m.getX(f),0,1,p[0],p[2]),r.MathUtils.mapLinear(m.getY(f),0,1,p[1],p[3]));return d}_createEllipsoidMesh(e){let{tiles:t,endCaps:i,_tiling:s}=this,{projection:n}=s,a=e[ps],o=e[us],l=e[ds],[c,h,u,d]=e.boundingVolume.region,p=Math.max(15,Math.ceil((d-h)*r.MathUtils.RAD2DEG*.25)),m=Math.max(30,Math.ceil((u-c)*r.MathUtils.RAD2DEG*.25)),f=m+3,g=p+3,y=new r.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(vs);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(r.MathUtils.mapLinear(l,0,1,v,x)),y=n.convertNormalizedToLatitude(r.MathUtils.mapLinear(c,0,1,T,b));if(n.isMercator&&i&&(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,i=r.MathUtils.mapLinear(c-t,0,1,h,d),s=r.MathUtils.mapLinear(c+t,0,1,h,d);y>e&&i<e&&(y=e),y<-e&&s>-e&&(y=-e)}t.ellipsoid.getCartographicToPosition(y,u,0,gs).sub(vs.center),t.ellipsoid.getCartographicToNormal(y,u,ys),o&&gs.addScaledVector(ys,-e.geometricError);let A=r.MathUtils.mapLinear(n.convertLongitudeToNormalized(u),v,x,_[0],_[2]),C=r.MathUtils.mapLinear(n.convertLatitudeToNormalized(y),T,b,_[1],_[3]);w.setXYZ(E,gs.x,gs.y,gs.z),M.setXYZ(E,ys.x,ys.y,ys.z),S.setXY(E,A,C)}let C=new r.Mesh(y,new r.MeshBasicMaterial);return C.position.copy(vs.center),C}getTileset(){let{tiles:e,_tiling:t}=this,i=t.minLevel,{tileCountX:r,tileCountY:s}=t.getLevel(i),n=[];for(let o=0;o<r;o++)for(let e=0;e<s;e++){let t=this.createChild(o,e,i);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,[ps]:-1,[us]:0,[ds]:0}};return e.preprocessTileset(a,""),a}getUrl(){return"tile.generated_surface"}fetchData(e){if(/generated_surface/.test(e))return new ArrayBuffer}createBoundingVolume(e,t,i,r=0){let{_tiling:s}=this,n=-1===i;if(this._useEllipsoid()){let a,o,{endCaps:l}=this;return n?(a=s.getContentBounds(!0),o=s.getContentBounds()):(a=s.getTileBounds(e,t,i,!0,!0),o=s.getTileBounds(e,t,i,!1,!0)),l&&(1===a[3]&&(o[3]=Math.PI/2),0===a[1]&&(o[1]=-Math.PI/2)),{region:[...o,-r,1]}}{let r,{center:a}=this;r=n?s.getContentBounds(!0):s.getTileBounds(e,t,i,!0);let[o,l,c,h]=r,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,i){let{_tiling:r}=this,{projection:s}=r;if(!r.getTileExists(e,t,i))return null;let n,a=this._useEllipsoid();if(a){let[a,o,l,c]=r.getTileBounds(e,t,i,!0),{tilePixelWidth:h,tilePixelHeight:u}=r.getLevel(i),d=(l-a)/h,p=(c-o)/u,[,m,f,g]=r.getTileBounds(e,t,i),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,i){let r=1e-5,s=i+r,n=t+r;Math.abs(n)>Math.PI/2&&(n-=r),e.getCartographicToPosition(t,i,0,as),e.getCartographicToPosition(n,i,0,os);let a=as.distanceTo(os)/r;return e.getCartographicToPosition(t,s,0,os),[as.distanceTo(os)/r,a]}(this.tiles.ellipsoid,y,f);n=Math.max(d*T*b,p*x*_)}else{let{pixelWidth:e,pixelHeight:t}=r.getLevel(i);n=Math.max(r.aspectRatio/e,1/t)}return{refine:"REPLACE",geometricError:n,boundingVolume:this.createBoundingVolume(e,t,i,a?n:0),content:{uri:this.getUrl(e,t,i)},children:[],[us]:e,[ds]:t,[ps]:i}}expandChildren(e){let t=e[ps],i=e[us],r=e[ds],{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*i+a,n*r+o,t+1);l&&e.children.push(l)}}_createDefaultTiling(){let e=new hs;if("ellipsoid"===this.shape){let t=new ls("EPSG:3857");e.setProjection(t),e.generateLevels(20,t.tileCountX,t.tileCountY)}else{let t=new ls("none");e.setProjection(t),e.generateLevels(20,1,1)}return e}},xs=class extends DOMException{constructor(){super("DataCache: Item removed","AbortError")}};function bs(...e){return e.join("_")}var _s=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,i=e.pop(),r=bs(...e);if(r in t)throw Error(`DataCache: "${r}" is already present.`);return this.cache[r]={abortController:new AbortController,result:i,count:1,bytes:this.getMemoryUsage(i)},this.count++,this.cachedBytes+=this.cache[r].bytes,i}lock(...e){let{cache:t}=this,i=bs(...e);if(i in t)t[i].count++;else{let t=new AbortController,r={abortController:t,result:null,count:1,bytes:0,args:e};this.active++,r.result=this.fetchItem(e,t.signal),r.result instanceof Promise?r.result=r.result.then((e=>(t.signal.throwIfAborted(),r.result=e,r.bytes=this.getMemoryUsage(e),this.cachedBytes+=r.bytes,e))).finally((()=>{this.active--})):(this.active--,r.bytes=this.getMemoryUsage(r.result),this.cachedBytes+=r.bytes),this.cache[i]=r,this.count++}return t[i].result}release(...e){let t=bs(...e);this.releaseViaFullKey(t)}get(...e){let{cache:t}=this,i=bs(...e);return i in t&&t[i].count>0?t[i].result:null}has(...e){let{cache:t}=this;return bs(...e)in t}forEachItem(e){let{cache:t}=this;for(let i in t){let r=t[i];r.result instanceof Promise||e(r.result,r.args)}}dispose(){let{cache:e}=this;for(let t in e){let{abortController:i}=e[t];i.abort(new xs),this.releaseViaFullKey(t,!0)}this.cache={}}releaseViaFullKey(e,t=!1){let{cache:i}=this;if(e in i&&i[e].count>0){let r=i[e];if(r.count--,0===r.count||t){let s=()=>{if(i[e]!==r)return;let{result:t,abortController:s}=r;s.abort(new xs),t instanceof Promise?t.then((e=>{this.disposeItem(e,r.args)})).catch((()=>{this.disposeItem(null,r.args)})).finally((()=>{this.count--,this.cachedBytes-=r.bytes})):(this.disposeItem(t,r.args),this.count--,this.cachedBytes-=r.bytes),delete i[e]};t?s():queueMicrotask((()=>{0===r.count&&s()}))}return!0}throw Error("DataCache: Attempting to release key that does not exist")}},ws=class extends _s{constructor(e={}){super();let{fetchOptions:t={}}=e;this.tiling=new hs,this.fetchOptions=t,this.fetchData=(...e)=>fetch(...e)}init(){}async processBufferToTexture(e){let t=new Blob([e]),i=new r.Texture(await createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none",imageOrientation:"flipY"}));return i.generateMipmaps=!1,i.colorSpace=r.SRGBColorSpace,i.needsUpdate=!0,i}getMemoryUsage(e){let{format:t,type:i,image:s,generateMipmaps:n}=e,{width:a,height:o}=s,l=r.TextureUtils.getByteLength(a,o,t,i);return n?4*l/3:l}fetchItem(e,t){let i={...this.fetchOptions,signal:t},r=this.getUrl(...e);return this.fetchData(r,i).then((e=>e.arrayBuffer())).then((e=>this.processBufferToTexture(e)))}disposeItem(e){e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}getUrl(...e){}},Ms=class extends ws{constructor(e={}){let{url:t=null,...i}=e;super(i),this.tileSets=null,this.extension=null,this.url=t}getUrl(e,t,i){let{url:r,extension:s,tileSets:n,tiling:a}=this;return new URL(`${parseInt(n[i-a.minLevel].href)}/${e}/${t}.${s}`,r).toString()}init(){let{url:e}=this;return this.fetchData(new URL("tilemapresource.xml",e),this.fetchOptions).then((e=>e.text())).then((t=>{let{tiling:i}=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"))*r.MathUtils.DEG2RAD,c=parseFloat(n.getAttribute("maxx"))*r.MathUtils.DEG2RAD,h=parseFloat(n.getAttribute("miny"))*r.MathUtils.DEG2RAD,u=parseFloat(n.getAttribute("maxy"))*r.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,i.setProjection(new ls(f)),i.setContentBounds(l,h,c,u),o.forEach((({order:e})=>{i.setLevel(e,{tileCountX:i.projection.tileCountX*2**e,tilePixelWidth:d,tilePixelHeight:p})}))}))}};function Ss(e,t,i,r){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,i.maxLevel),i.minLevel),[c,h,u,d]=i.getTilesInRange(s,n,a,o,l,!0);for(let p=c;p<=u;p++)for(let e=h;e<=d;e++)r(p,e,l)}var As=["a","b","c"],Cs=new r.Vector4,Es=new r.Vector4,Rs=new r.Vector4,Ps=new r.Vector4,Ls=class{constructor(){this.attributeList=null,this.splitOperations=[],this.trianglePool=new Us}forEachSplitPermutation(e){let{splitOperations:t}=this,i=(r=0)=>{r>=t.length?e():(t[r].keepPositive=!0,i(r+1),t[r].keepPositive=!1,i(r+1))};i()}addSplitOperation(e,t=!0){this.splitOperations.push({callback:e,keepPositive:t})}clearSplitOperations(){this.splitOperations.length=0}clipObject(e){let t=e.clone(),i=[];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)&&i.push(e))})),i.forEach((e=>{e.removeFromParent()})),t}clip(e,t=null){let i=this.getClippedData(e,t);return this.constructMesh(i.attributes,i.index,e)}getClippedData(e,t=null,i={}){let{trianglePool:r,splitOperations:s,attributeList:n}=this,a=e.geometry,o=a.attributes.position,l=a.index,c=0,h={};i.index=i.index||[],i.vertexIsClipped=i.vertexIsClipped||[],i.attributes=i.attributes||{};for(let m in a.attributes)null!==n&&(n instanceof Function&&!n(m)||Array.isArray(n)&&!n.includes(m))||(i.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,i=m+1,n=m+2;l&&(t=l.getX(t),i=l.getX(i),n=l.getX(n));let o=r.get();o.initFromIndices(t,i,n);let c=[o];for(let r=0;r<s.length;r++){let{keepPositive:t,callback:i}=s[r],n=[];for(let r=0;r<c.length;r++){let s=c[r],{indices:o,barycoord:l}=s;s.clipValues.a=i(a,o.a,o.b,o.c,l.a,e.matrixWorld),s.clipValues.b=i(a,o.a,o.b,o.c,l.b,e.matrixWorld),s.clipValues.c=i(a,o.a,o.b,o.c,l.c,e.matrixWorld),this.splitTriangle(s,!t,n)}c=n}for(let e=0,r=c.length;e<r;e++){p(c[e],a)}r.reset()}return i;function p(e,t){for(let r=0;r<3;r++){let s=e.getVertexHash(r,t);s in h||(h[s]=c,c++,e.getVertexData(r,t,i.attributes),i.vertexIsClipped.push(0===e.clipValues[As[r]]));let n=h[s];i.index.push(n)}}}constructMesh(e,t,i){let s=i.geometry,n=new r.BufferGeometry,a=e.position.length/3>65535?new Uint32Array(t):new Uint16Array(t);n.setIndex(new r.BufferAttribute(a,1,!1));for(let l in e){let t=s.getAttribute(l),i=new r.BufferAttribute(new t.array.constructor(e[l]),t.itemSize,t.normalized);i.gpuType=t.gpuType,n.setAttribute(l,i)}let o=new r.Mesh(n,i.material.clone());return o.position.copy(i.position),o.quaternion.copy(i.quaternion),o.scale.copy(i.scale),o}splitTriangle(e,t,i){let{trianglePool:s}=this,n=[],a=[],o=[];for(let l=0;l<3;l++){let t=As[l],i=As[(l+1)%3],s=e.clipValues[t],c=e.clipValues[i];(s<0!=c<0||0===s)&&(n.push(l),a.push([t,i]),s===c?o.push(0):o.push(r.MathUtils.mapLinear(0,s,c,0,1)))}if(2!==n.length)Math.min(e.clipValues.a,e.clipValues.b,e.clipValues.c)<0===t&&i.push(e);else if(2===n.length){let r,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),r=Math.min(c.clipValues.a,c.clipValues.b,c.clipValues.c),l=r<0,l===t&&i.push(c),r=Math.min(h.clipValues.a,h.clipValues.b,h.clipValues.c),l=r<0,l===t&&i.push(h),r=Math.min(u.clipValues.a,u.clipValues.b,u.clipValues.c),l=r<0,l===t&&i.push(u)}}},Us=class{constructor(){this.pool=[],this.index=0}get(){if(this.index>=this.pool.length){let e=new Is;this.pool.push(e)}let e=this.pool[this.index];return this.index++,e}reset(){this.index=0}},Is=class{constructor(){this.indices={a:-1,b:-1,c:-1},this.clipValues={a:-1,b:-1,c:-1},this.barycoord=new r.Triangle}getVertexHash(e,t){let{barycoord:i,indices:r}=this,s=i[As[e]];if(1===s.x)return r[As[0]];if(1===s.y)return r[As[1]];if(1===s.z)return r[As[2]];{let{attributes:e}=t,i="";for(let t in e){let n=e[t];switch(Fs(n,r.a,r.b,r.c,s,Cs),("normal"===t||"tangent"===t||"bitangent"===t)&&Cs.normalize(),n.itemSize){case 4:i+=ks(Cs.x,Cs.y,Cs.z,Cs.w);break;case 3:i+=ks(Cs.x,Cs.y,Cs.z);break;case 2:i+=ks(Cs.x,Cs.y);break;case 1:i+=ks(Cs.x)}i+="|"}return i}}getVertexData(e,t,i){let{barycoord:r,indices:s}=this,n=r[As[e]],{attributes:a}=t;for(let o in a){if(!i[o])continue;let e=a[o],t=i[o];switch(Fs(e,s.a,s.b,s.c,n,Cs),("normal"===o||"tangent"===o||"bitangent"===o)&&Cs.normalize(),e.itemSize){case 4:t.push(Cs.x,Cs.y,Cs.z,Cs.w);break;case 3:t.push(Cs.x,Cs.y,Cs.z);break;case 2:t.push(Cs.x,Cs.y);break;case 1:t.push(Cs.x)}}}initFromTriangle(e){return this.initFromIndices(e.indices.a,e.indices.b,e.indices.c)}initFromIndices(e,t,i){return this.indices.a=e,this.indices.b=t,this.indices.c=i,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,i,s,n){this.clipValues[n]=r.MathUtils.lerp(e.clipValues[t],e.clipValues[i],s),this.barycoord[n].lerpVectors(e.barycoord[t],e.barycoord[i],s)}copyVertex(e,t,i){this.clipValues[i]=e.clipValues[t],this.barycoord[i].copy(e.barycoord[t])}};function Fs(e,t,i,r,s,n){switch(Es.fromBufferAttribute(e,t),Rs.fromBufferAttribute(e,i),Ps.fromBufferAttribute(e,r),n.set(0,0,0,0).addScaledVector(Es,s.x).addScaledVector(Rs,s.y).addScaledVector(Ps,s.z),e.itemSize){case 3:Cs.w=0;break;case 2:Cs.w=0,Cs.z=0;break;case 1:Cs.w=0,Cs.z=0,Cs.y=0}return n}function ks(...e){let t="";for(let i=0,r=e.length;i<r;i++)t+=~~(1e5*e[i]+.5),i!==r-1&&(t+="_");return t}var Ds=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:i,range:s,context:n}=this,{width:a,height:o}=i,{image:l}=e,c=Math.round(r.MathUtils.mapLinear(t[0],s[0],s[2],0,a)),h=Math.round(r.MathUtils.mapLinear(t[1],s[1],s[3],0,o)),u=Math.round(r.MathUtils.mapLinear(t[2],s[0],s[2],0,a))-c,d=Math.round(r.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 Os=class extends _s{hasContent(...e){return!0}},Bs=class extends Os{constructor(e){super(),this.tiledImageSource=e,this.tileComposer=new Ds,this.resolution=256}hasContent(e,t,i,r,s){let n=this.tiledImageSource.tiling,a=0;return Ss([e,t,i,r],s,n,(()=>{a++})),0!==a}async fetchItem([e,t,i,s,n],a){let{tiledImageSource:o,tileComposer:l}=this,c=[e,t,i,s],h=o.tiling;await this._markImages(c,n,!1),null==a||a.throwIfAborted();let u=null;if(Ss(c,n,h,((e,t,i)=>{(function(e,t,i=0){if(e.length!==t.length)return!1;for(let r=0,s=e.length;r<s;r++)if(Math.abs(e[r]-t[r])>i)return!1;return!0})(h.getTileBounds(e,t,i,!0,!1),c,1e-10)&&(u=[e,t,i])})),null!==u){let[e,t,i]=u;return o.get(e,t,i).clone()}let d=document.createElement("canvas");d.width=this.resolution,d.height=this.resolution;let p=new r.CanvasTexture(d);return p.colorSpace=r.SRGBColorSpace,p.generateMipmaps=!1,l.setTarget(p,c),l.clear(16777215,0),Ss(c,n,h,((e,t,i)=>{let r=h.getTileBounds(e,t,i,!0,!1),s=o.get(e,t,i);l.draw(s,r)})),p}disposeItem(e,[t,i,r,s,n]){e&&e.dispose(),this._markImages([t,i,r,s],n,!0)}dispose(){super.dispose(),this.tiledImageSource.dispose()}_markImages(e,t,i=!1){let r=this.tiledImageSource,s=r.tiling,n=[];Ss(e,t,s,((e,t,s)=>{i?r.release(e,t,s):n.push(r.lock(e,t,s))}));let a=n.filter((e=>e instanceof Promise));return 0===a.length?null:Promise.all(a)}},Ns=new ce;Ns.maxJobs=10,Ns.priorityCallback=(e,t)=>{let i=e.tile,r=t.tile,s=i.internal.renderer,n=r.internal.renderer,a=s.visibleTiles.has(i);return a===n.visibleTiles.has(r)?Le(i,r):a?1:-1};var Vs=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:i=16777215,frame:s=null,preprocessURL:n=null,alphaMask:a=!1,alphaInvert:o=!1}=e;this.preprocessURL=n,this.opacity=t,this.color=new r.Color(i),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 i={priority:-performance.now()};return this.downloadQueue.add(e,i,(()=>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:i}=this,r=e.join("_"),s=i.get(r);if(s||(s={range:[...e],count:0},i.set(r,s)),s.count+=t?1:-1,s.count<0)throw Error();0===s.count&&i.delete(r)}},zs=class extends Vs{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,...i}=e;super(i),this.imageSource=t,this.regionImageSource=null}_init(){return this._initImageSource().then((()=>{this.imageSource.fetchData=(...e)=>this.fetch(...e),this.regionImageSource=new Bs(this.imageSource)}))}_initImageSource(){return this.imageSource.init()}calculateLevel(e,t=null){let[i,r,s,n]=e,a=s-i,o=n-r;null===t&&(t=this.regionImageSource.resolution);let l=0,c=this.tiling.maxLevel;for(;l<c;l++){let e=t/a,i=t/o,r=this.tiling.getLevel(l);if(null==r)continue;let{pixelWidth:s,pixelHeight:n}=r;if(s>=e||n>=i)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}},Gs=class extends zs{constructor(e={}){super(e),this.imageSource=new Ms(e)}},Hs=new r.Vector3,js=new r.Triangle,Ws=new r.Vector3,qs=new r.Vector3,Xs=class extends es{constructor(e=r.DefaultLoadingManager){super(),this.manager=e,this.ellipsoid=new gi,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:i,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 r.BufferGeometry,y=new r.MeshStandardMaterial,v=new r.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 r=0;r<b;r++)R(r,Ws),P(Ws.x,Ws.y,Ws.z,qs),w.push(Ws.x,Ws.y),_.push(...qs);for(let r=0,U=d.length;r<U;r++)M.push(d[r]);if(x)if(T){let e=f.octvertexnormals.normals;for(let t=0,i=e.length;t<i;t++)S.push(e[t])}else{let e=new r.BufferGeometry,t=d.length>21845?new Uint32Array(d):new Uint16Array(d);e.setIndex(new r.BufferAttribute(t,1,!1)),e.setAttribute("position",new r.BufferAttribute(new Float32Array(_),3,!1)),e.computeVertexNormals();let i=e.getAttribute("normal").array;f.octvertexnormals={normals:i};for(let r=0,s=i.length;r<s;r++)S.push(i[r])}if(g.addGroup(A,d.length,C),A+=d.length,C++,i){let e=_.length/3;for(let t=0;t<b;t++)R(t,Ws),P(Ws.x,Ws.y,Ws.z,qs,-s),w.push(Ws.x,Ws.y),_.push(...qs);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,i=e.length;t<i;t++)S.push(-e[t])}g.addGroup(A,d.length,C),A+=d.length,C++}if(s>0){let e,{westIndices:t,eastIndices:i,southIndices:r,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(i);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(r);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 r=0,U=_.length;r<U;r+=3)_[r+0]-=u.center[0],_[r+1]-=u.center[1],_[r+2]-=u.center[2];let E=_.length/3>65535?new Uint32Array(M):new Uint16Array(M);if(g.setIndex(new r.BufferAttribute(E,1,!1)),g.setAttribute("position",new r.BufferAttribute(new Float32Array(_),3,!1)),g.setAttribute("uv",new r.BufferAttribute(new Float32Array(w),2,!1)),x&&g.setAttribute("normal",new r.BufferAttribute(new Float32Array(S),3,!1)),"watermask"in f){let{mask:e,size:t}=f.watermask,i=new Uint8Array(2*t*t);for(let r=0,n=e.length;r<n;r++){let t=255===e[r]?0:255;i[2*r+0]=t,i[2*r+1]=t}let s=new r.DataTexture(i,t,t,r.RGFormat,r.UnsignedByteType);s.flipY=!0,s.minFilter=r.LinearMipMapLinearFilter,s.magFilter=r.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,i,s,n,a=0){let d=r.MathUtils.lerp(u.minHeight,u.maxHeight,s),p=r.MathUtils.lerp(c,h,e),m=r.MathUtils.lerp(o,l,i);return t.getCartographicToPosition(m,p,d+a,n),n}function L(e){let t=[],i=[],r=[],a=[],o=[];for(let n=0,h=e.length;n<h;n++)R(e[n],Ws),t.push(Ws.x,Ws.y),r.push(Ws.x,Ws.y),P(Ws.x,Ws.y,Ws.z,qs),i.push(...qs),P(Ws.x,Ws.y,Ws.z,qs,-s),a.push(...qs);let l=e.length-1;for(let s=0;s<l;s++){let t=s,i=s+1,r=s+e.length,n=s+e.length+1;o.push(t,r,i),o.push(i,r,n)}let c=null;if(x){let t=(i.length+a.length)/3;if(n){c=Array(3*t);let i=f.octvertexnormals.normals,r=c.length/2;for(let s=0,n=t/2;s<n;s++){let t=e[s],n=3*s,a=i[3*t+0],o=i[3*t+1],l=i[3*t+2];c[n+0]=a,c[n+1]=o,c[n+2]=l,c[r+n+0]=a,c[r+n+1]=o,c[r+n+2]=l}}else{c=[],js.a.fromArray(i,0),js.b.fromArray(a,0),js.c.fromArray(i,3),js.getNormal(Hs);for(let e=0;e<t;e++)c.push(...Hs)}}return{uv:[...t,...r],positions:[...i,...a],indices:o,normals:c}}}},Ks={},Ys=new r.Vector3,Qs=new r.Vector3,$s=new r.Vector3,Zs=new r.Vector3,Js=new r.Vector3,en=new r.Vector3,tn=new r.Vector3,rn=new r.Vector2,sn=new r.Vector2,nn=new r.Vector2,an=class extends Ls{constructor(){super(),this.ellipsoid=new gi,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,i){let{solid:r,skirtLength:s,ellipsoid:n,smoothSkirtNormals:a}=this;this.clearSplitOperations(),this.addSplitOperation(on("x"),!t),this.addSplitOperation(on("y"),!i);let o,l,c=e.geometry.groups[0],h=this.getClippedData(e,c);if(this.adjustVertices(h,e.position,0),r){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,i={},r=(e,r,s)=>{let n=ks(...e,...s,...r);n in i||(i[n]=t,t++,l.attributes.position.push(...e),l.attributes.normal.push(...s),l.attributes.uv.push(...r)),l.index.push(i[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 i=0;i<3;i++){let l=(i+1)%3,h=o[t+i],p=o[t+l];if(rn.fromArray(c,2*h),sn.fromArray(c,2*p),rn.x===sn.x&&(0===rn.x||.5===rn.x||1===rn.x)||rn.y===sn.y&&(0===rn.y||.5===rn.y||1===rn.y)){Qs.fromArray(u,3*h),$s.fromArray(u,3*p);let t=Qs,i=$s,o=Zs.copy(Qs),l=Js.copy($s);en.copy(o).add(e.position),n.getPositionToNormal(en,en),o.addScaledVector(en,-s),en.copy(l).add(e.position),n.getPositionToNormal(en,en),l.addScaledVector(en,-s),a&&d?(en.fromArray(d,3*h),tn.fromArray(d,3*p)):(en.subVectors(t,i),tn.subVectors(t,o).cross(en).normalize(),en.copy(tn)),r(i,sn,tn),r(t,rn,en),r(o,rn,en),r(i,sn,tn),r(o,rn,en),r(l,sn,tn)}}}}let u=h.index.length,d=h;if(o){let{index:e,attributes:t}=o,i=d.attributes.position.length/3;for(let r=0,s=e.length;r<s;r++)d.index.push(e[r]+i);for(let r in h.attributes)d.attributes[r].push(...t[r])}if(l){let{index:e,attributes:t}=l,i=d.attributes.position.length/3;for(let r=0,s=e.length;r<s;r++)d.index.push(e[r]+i);for(let r in h.attributes)d.attributes[r].push(...t[r])}let p=t?0:-.5,m=i?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,i){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=rn.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),rn.toArray(d,2*m));let c=r.MathUtils.lerp(n,a,e.y),p=r.MathUtils.lerp(o,l,e.x),f=Ys.fromArray(u,3*m).add(t);s.getPositionToCartographic(f,Ks),s.getCartographicToPosition(c,p,Ks.height+i,f),f.sub(t),f.toArray(u,3*m)}}};function on(e){return(t,i,r,s,n)=>{let a=t.attributes.uv;return rn.fromBufferAttribute(a,i),sn.fromBufferAttribute(a,r),nn.fromBufferAttribute(a,s),rn[e]*n.x+sn[e]*n.y+nn[e]*n.z-.5}}var ln=Symbol("TILE_X"),cn=Symbol("TILE_Y"),hn=Symbol("TILE_LEVEL"),un=Symbol("TILE_AVAILABLE"),dn=Symbol("TILE_SPLIT_SOURCE_SCENE"),pn=new r.Vector3;function mn(e){let{available:t=null,maxzoom:i=null}=e;return null===i?t.length-1:i}function fn(e,t){let i=e[hn],r=function(e){let{metadataAvailability:t=-1}=e;return t}(t);return i<mn(t)&&-1!==r&&i%r==0}var gn=class{constructor(e={}){let{useRecommendedSettings:t=!0,skirtLength:i=null,smoothSkirtNormals:r=!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=i,this.smoothSkirtNormals=r,this.solid=n,this.generateNormals=s,this.attribution=null,this.tiling=new hs,this.projection=new ls}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:i=[],attribution:r="",available:s=null}=e,{tiling:n,tiles:a,projection:o}=this;r&&(this.attribution={value:r,type:"string",collapsible:!0}),i.length>0&&(a.fetchOptions.headers.Accept+=`;extensions=${i.join("-")}`),o.setScheme(t);let{tileCountX:l,tileCountY:c}=o;n.setProjection(o),n.generateLevels(mn(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,[un]:s,[hn]:-1}},d=a.rootURL;return a.invokeAllPlugins((e=>d=e.preprocessURL?e.preprocessURL(d,null):d)),a.preprocessTileset(u,d),u}))}parseToMesh(e,t,i,r){let s,{skirtLength:n,solid:a,smoothSkirtNormals:o,generateNormals:l,tiles:c}=this,h=c.ellipsoid;if("quantized_tile_split"===i){let e=new URL(r).searchParams,i="true"===e.get("left"),l="true"===e.get("bottom"),c=new an;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[dn];s=c.clipToQuadrant(f,i,l)}else{if("terrain"!==i)return;{let i=new Xs(c.manager);i.ellipsoid.copy(h),i.solid=a,i.smoothSkirtNormals=o,i.generateNormals=l,i.skirtLength=null===n?t.geometricError:n;let[r,u,d,p]=t.boundingVolume.region;i.minLat=u,i.maxLat=p,i.minLon=r,i.maxLon=d,s=i.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),fn(t,this.layer)&&"available"in p&&0===t.children.length&&(t[un]=[...Array(t[hn]+1).fill(null),...p.available])),t[dn]=s,this.expandChildren(t),s}getAttributions(e){this.attribution&&e.push(this.attribution)}createChild(e,t,i,r){let{tiles:s,layer:n,tiling:a,projection:o}=this,l=s.ellipsoid,c=null===r&&0===e||function(e,t,i,r){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(i>=t&&i<=a&&r>=n&&r<=o)return!0}}return!1}(r,e,t,i),h=function(e,t,i,r,s){return s.tiles[0].replace(/{\s*z\s*}/g,i).replace(/{\s*x\s*}/g,e).replace(/{\s*y\s*}/g,t).replace(/{\s*version\s*}/g,r)}(t,i,e,1,n),u=[...a.getTileBounds(t,i,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,pn),pn.z=0;let g=o.tileCountX,y=2*Math.max(...l.radius)*Math.PI*.25/(65*g)/2**e,v={[un]:null,[hn]:e,[ln]:t,[cn]:i,refine:"REPLACE",geometricError:y,boundingVolume:{region:u},content:c?{uri:h}:null,children:[]};return fn(v,n)||(v[un]=r),v}expandChildren(e){let t=e[hn],i=e[ln],r=e[cn],s=e[un];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*i+a,2*r+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:i}=this;if(delete e[dn],fn(e,i)&&(e[un]=null),un in e){let{virtualChildCount:i}=e.internal,r=e.children.length;for(let s=r-i;s<r;s++)t.processNodeQueue.remove(e.children[s]);e.children.length=0,e.internal.virtualChildCount=0}}},yn=class extends Xr{constructor(e={}){super({assetTypeHandler:(e,t,i)=>{if("TERRAIN"===e&&null===t.getPluginByName("QUANTIZED_MESH_PLUGIN"))t.registerPlugin(new gn({useRecommendedSettings:this.useRecommendedSettings}));else if("IMAGERY"===e&&null===t.getPluginByName("GENERATED_SURFACE_PLUGIN")){let e=new Gs({url:t.rootURL});t.registerPlugin(new Ts({shape:"ellipsoid",overlay:e}))}},...e})}},vn=new r.Matrix4,Tn=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 r.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(((i,r)=>{vn.copy(e.group.matrixWorld).premultiply(r.matrixWorldInverse).premultiply(r.projectionMatrixInverse),t||(t=!vn.equals(i)),i.copy(vn)}));let i=this.needsUpdate;return this.needsUpdate=!1,i||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)}},xn=new r.Vector3;function bn(e,t){if(e.isInterleavedBufferAttribute||e.array instanceof t)return e;let i=t===Int8Array||t===Int16Array||t===Int32Array?-1:0,s=new r.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=r.MathUtils.clamp(e.getComponent(o,t),i,1);s.setComponent(o,t,n)}return s}var _n=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:i,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 i=t[e];i&&i.isTexture&&i.generateMipmaps&&(i.generateMipmaps=!1,i.minFilter=r.LinearFilter)}}if(e.geometry){let t=e.geometry,s=t.attributes;if(a){let{uv:e,uv1:t,uv2:i,uv3:r}=s;e&&(s.uv=bn(e,c)),t&&(s.uv1=bn(t,c)),i&&(s.uv2=bn(i,c)),r&&(s.uv3=bn(r,c))}if(i&&!s.normals&&t.computeVertexNormals(),o&&s.normals&&(s.normals=bn(s.normals,h)),l&&function(e,t=Int16Array){let i=e.geometry,s=i.attributes,n=s.position;if(n.isInterleavedBufferAttribute||n.array instanceof t)return n;let a=new r.BufferAttribute(new t(n.count*n.itemSize),n.itemSize,!1),o=n.itemSize,l=n.count;i.computeBoundingBox();let c=i.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",i=h[t],s=u[t],o=r.MathUtils.mapLinear(n.getComponent(m,e),i,s,p,d);a.setComponent(m,e,o)}c.getCenter(xn).multiply(e.scale).applyQuaternion(e.quaternion),e.position.add(xn),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,i=t.index,n=e>65535?Uint32Array:e>255?Uint16Array:Uint8Array;if(!(i.array instanceof n)){let e=new n(t.index.count);e.set(i.array);let s=new r.BufferAttribute(e,1);t.setIndex(s)}}}}))}};function wn(e,t,i){return e&&t in e?e[t]:i}function Mn(e){return"BOOLEAN"!==e&&"STRING"!==e&&"ENUM"!==e}function Sn(e){return/^VEC/.test(e)}function An(e){return/^MAT/.test(e)}function Cn(e,t,i,r=null){return An(i)||Sn(i)?r.fromArray(e,t):e[t]}function En(e){let{type:t,componentType:i}=e;switch(t){case"SCALAR":return"INT64"===i?0n:0;case"VEC2":return new r.Vector2;case"VEC3":return new r.Vector3;case"VEC4":return new r.Vector4;case"MAT2":return new r.Matrix2;case"MAT3":return new r.Matrix3;case"MAT4":return new r.Matrix4;case"BOOLEAN":return!1;case"STRING":return"";case"ENUM":return 0}}function Rn(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 Pn(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 Ln(e,t=null){let i=e.default,r=e.type;if(t||(t=En(e)),null===i){switch(r){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(An(r))t.fromArray(i);else{if(!Sn(r))return i;t.fromArray(i)}}function Un(e,t){if(null===e.noData)return t;let i=e.noData,r=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(An(r)){let t=e.elements;for(let e=0,r=i.length;e<r;e++)if(i[e]!==t[e])return!1;return!0}if(Sn(r)){for(let t=0,r=i.length;t<r;t++)if(i[t]!==e.getComponent(t))return!1;return!0}return i===e}(t)&&(t=Ln(e,t)),t}}function In(e,t){let{type:i,componentType:r,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=An(i)?function(e){let t=e.elements;for(let i=0,r=t.length;i<r;i++)t[i]=l(t[i]);return e}(e):Sn(i)?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}}(r,e)),(a||function(e){return/^FLOAT/.test(e)}(r))&&(e=e*s+n),e}}function Fn(e,t,i=null){if(e.array){Array.isArray(t)||(t=Array(e.count||0)),t.length=null===i?e.count:i;for(let i=0,r=t.length;i<r;i++)Rn(e.type,t[i])||(t[i]=En(e))}else Rn(e.type,t)||(t=En(e));return t}function kn(e,t){for(let i in t)i in e||delete t[i];for(let i in e){let r=e[i];t[i]=Fn(r,t[i])}}var Dn=class{constructor(e,t,i=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=wn(t,"scale",1),this.max=wn(t,"max",1/0),this.min=wn(t,"min",-1/0),this.required=t.required||!1,this.noData=wn(t,"noData",null),this.default=wn(t,"default",null),this.semantic=wn(t,"semantic",null),this.enumSet=null,this.accessorProperty=i,i&&(this.offset=wn(i,"offset",this.offset),this.scale=wn(i,"scale",this.scale),this.max=wn(i,"max",this.max),this.min=wn(i,"min",this.min)),"ENUM"===t.type&&(this.enumSet=e[this.enumType],null===this.componentType&&(this.componentType=wn(this.enumSet,"valueType","UINT16")))}shapeToProperty(e,t=null){return Fn(this,e,t)}resolveDefaultElement(e){return Ln(this,e)}resolveDefault(e){return function(e,t=null){if(e.array){(t=t&&Array.isArray(t)?t:[]).length=e.count;for(let i=0,r=t.length;i<r;i++)t[i]=Ln(e,t[i])}else t=Ln(e,t);return t}(this,e)}resolveNoData(e){return Un(this,e)}resolveEnumsToStrings(e){let t=this.enumSet;if("ENUM"===this.type)if(Array.isArray(e))for(let r=0,s=e.length;r<s;r++)e[r]=i(e[r]);else e=i(e);return e;function i(e){let i=t.values.find((t=>t.value===e));return null===i?"":i.name}}adjustValueScaleOffset(e){return Mn(this.type)?In(this,e):e}},On=class{constructor(e,t={},i={},r=null){this.definition=e,this.class=t[e.class],this.className=e.class,this.enums=i,this.data=r,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=Dn){let t={};for(let i in this.class.properties)t[i]=new e(this.enums,this.class.properties[i],this.definition.properties[i]);this.properties=t}},Bn=class extends Dn{constructor(e,t,i=null){super(e,t,i),this.attribute=(null==i?void 0:i.attribute)??null}},Nn=class extends On{constructor(...e){super(...e),this.isPropertyAttributeAccessor=!0,this._initProperties(Bn)}getData(e,t,i={}){let r=this.properties;kn(r,i);for(let s in r)i[s]=this.getPropertyValue(s,e,t,i[s]);return i}getPropertyValue(e,t,i,r=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(r);r=s.shapeToProperty(r);let a=i.getAttribute(s.attribute.toLowerCase());if(An(n)){let e=r.elements;for(let i=e.length;0<i;)e[0]=a.getComponent(t,0)}else if(Sn(n))r.fromBufferAttribute(a,t);else{if("SCALAR"!==n&&"ENUM"!==n)throw Error("StructuredMetadata.PropertyAttributeAccessor: BOOLEAN and STRING types are not supported by property attributes.");r=a.getX(t)}return r=s.adjustValueScaleOffset(r),r=s.resolveEnumsToStrings(r),r=s.resolveNoData(r)}},Vn=class extends Dn{constructor(e,t,i=null){super(e,t,i),this.values=(null==i?void 0:i.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=wn(i,"arrayOffsets",null),this.stringOffsets=wn(i,"stringOffsets",null),this.arrayOffsetType=wn(i,"arrayOffsetType","UINT32"),this.stringOffsetType=wn(i,"stringOffsetType","UINT32")}getArrayLengthFromId(e,t){let i=this.count;if(null!==this.arrayOffsets){let{arrayOffsets:r,arrayOffsetType:s}=this,n=new(Pn(s))(e[r]);i=n[t+1]-n[t]}return i}getIndexOffsetFromId(e,t){let i=t;if(this.arrayOffsets){let{arrayOffsets:t,arrayOffsetType:r}=this;i=new(Pn(r))(e[t])[i]}else this.array&&(i*=this.count);return i}},zn=class extends On{constructor(...e){super(...e),this.isPropertyTableAccessor=!0,this.count=this.definition.count,this._initProperties(Vn)}getData(e,t={}){let i=this.properties;kn(i,t);for(let r in i)t[r]=this.getPropertyValue(r,e,t[r]);return t}_readValueAtIndex(e,t,i,r=null){let s=this.properties[e],{componentType:n,type:a}=s,o=this.data,l=o[s.values],c=new(Pn(n,a))(l),h=s.getIndexOffsetFromId(o,t);if(Mn(a)||"ENUM"===a)return Cn(c,(h+i)*s.valueLength,a,r);if("STRING"===a){let e=h+i,t=0;if(null!==s.stringOffsets){let{stringOffsets:i,stringOffsetType:r}=s,n=new(Pn(r))(o[i]);t=n[e+1]-n[e],e=n[e]}let n=new Uint8Array(c.buffer,e,t);r=(new TextDecoder).decode(n)}else if("BOOLEAN"===a){let e=h+i,t=e%8;r=1==(c[Math.floor(e/8)]>>t&1)}return r}getPropertyValue(e,t,i=null){if(t>=this.count)throw Error("PropertyTableAccessor: Requested index is outside the range of the table.");let r=this.properties[e];if(!r)throw Error("PropertyTableAccessor: Requested property does not exist.");if(!this.definition.properties[e])return r.resolveDefault(i);let s=r.array,n=this.data,a=r.getArrayLengthFromId(n,t);if(i=r.shapeToProperty(i,a),s)for(let o=0,l=i.length;o<l;o++)i[o]=this._readValueAtIndex(e,t,o,i[o]);else i=this._readValueAtIndex(e,t,0,i);return i=r.adjustValueScaleOffset(i),i=r.resolveEnumsToStrings(i),i=r.resolveNoData(i)}},Gn=new r.Box2,Hn=class{constructor(){this._renderer=new r.WebGLRenderer,this._target=new r.WebGLRenderTarget(1,1),this._texTarget=new r.WebGLRenderTarget,this._quad=new ns(new r.ShaderMaterial({blending:r.CustomBlending,blendDst:r.ZeroFactor,blendSrc:r.OneFactor,uniforms:{map:{value:null},pixel:{value:new r.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:i}=this;return t.readRenderTargetPixelsAsync(i,0,0,e.length/4,1,e)}readData(e){let{_renderer:t,_target:i}=this;t.readRenderTargetPixels(i,0,0,e.length/4,1,e)}renderPixelToTarget(e,t,i){let{_renderer:r,_target:s}=this;Gn.min.copy(t),Gn.max.copy(t),Gn.max.x+=1,Gn.max.y+=1,r.initRenderTarget(s),r.copyTextureToTexture(e,s.texture,Gn,i,0)}},jn=new class{constructor(){let e=null;Object.getOwnPropertyNames(Hn.prototype).forEach((t=>{"constructor"!==t&&(this[t]=(...i)=>(e||(e=new Hn),e[t](...i)))}))}},Wn=new r.Vector2,qn=new r.Vector2,Xn=new r.Vector2;function Kn(e,t,i=[,,,]){let r=3*t,s=3*t+1,n=3*t+2;return e.index&&(r=e.index.getX(r),s=e.index.getX(s),n=e.index.getX(n)),i[0]=r,i[1]=s,i[2]=n,i}function Yn(e,t,i,r,s){let[n,a,o]=r,l=function(e,t){return 0===t?e.getAttribute("uv"):e.getAttribute(`uv${t}`)}(e,t);Wn.fromBufferAttribute(l,n),qn.fromBufferAttribute(l,a),Xn.fromBufferAttribute(l,o),s.set(0,0,0).addScaledVector(Wn,i.x).addScaledVector(qn,i.y).addScaledVector(Xn,i.z)}function Qn(e,t,i,r){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*i%i);return r.set(a,o),r}var $n=new r.Vector2,Zn=new r.Vector2,Jn=new r.Vector2,ea=class extends Dn{constructor(e,t,i=null){super(e,t,i),this.channels=wn(i,"channels",[0]),this.index=wn(i,"index",null),this.texCoord=wn(i,"texCoord",null),this.valueLength=parseInt(this.type.replace(/[^0-9]/g,""))||1}readDataFromBuffer(e,t,i=null){let r=this.type;if("BOOLEAN"===r||"STRING"===r)throw Error("PropertyTextureAccessor: BOOLEAN and STRING types not supported.");return Cn(e,t*this.valueLength,r,i)}},ta=class extends On{constructor(...e){super(...e),this.isPropertyTextureAccessor=!0,this._asyncRead=!1,this._initProperties(ea)}getData(e,t,i,r={}){let s=this.properties;kn(s,r);let n=Object.keys(s),a=n.map((e=>r[e]));return this.getPropertyValuesAtTexel(n,e,t,i,a),n.forEach(((e,t)=>r[e]=a[t])),r}async getDataAsync(e,t,i,r={}){let s=this.properties;kn(s,r);let n=Object.keys(s),a=n.map((e=>r[e]));return await this.getPropertyValuesAtTexelAsync(n,e,t,i,a),n.forEach(((e,t)=>r[e]=a[t])),r}getPropertyValuesAtTexelAsync(...e){this._asyncRead=!0;let t=this.getPropertyValuesAtTexel(...e);return this._asyncRead=!1,t}getPropertyValuesAtTexel(e,t,i,r,s=[]){for(;s.length<e.length;)s.push(null);s.length=e.length,jn.increaseSizeTo(s.length);let n=this.data,a=this.definition.properties,o=this.properties,l=Kn(r,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];Yn(r,s.texCoord,i,l,$n),Qn($n,c.image.width,c.image.height,Zn),Jn.set(u,0),jn.renderPixelToTarget(c,Zn,Jn)}let c=new Uint8Array(4*e.length);return this._asyncRead?jn.readDataAsync(c).then((()=>(h.call(this),s))):(jn.readData(c),h.call(this),s);function h(){for(let t=0,i=e.length;t<i;t++){let i=e[t],r=o[i],n=r.type;if(s[t]=Fn(r,s[t]),!r)throw Error("PropertyTextureAccessor: Requested property does not exist.");if(!a[i]){s[t]=r.resolveDefault(s);continue}let l=r.valueLength*(r.count||1),h=r.channels.map((e=>c[4*t+e])),u=new(Pn(r.componentType,n))(l);if(new Uint8Array(u.buffer).set(h),r.array){let e=s[t];for(let t=0,i=e.length;t<i;t++)e[t]=r.readDataFromBuffer(u,t,e[t])}else s[t]=r.readDataFromBuffer(u,0,s[t]);s[t]=r.adjustValueScaleOffset(s[t]),s[t]=r.resolveEnumsToStrings(s[t]),s[t]=r.resolveNoData(s[t])}}}dispose(){this.data.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},ia=class{constructor(e,t,i,r=null,s=null){let{schema:n,propertyTables:a=[],propertyTextures:o=[],propertyAttributes:l=[]}=e,{enums:c,classes:h}=n,u=a.map((e=>new zn(e,h,c,i))),d=[],p=[];r&&(r.propertyTextures&&(d=r.propertyTextures.map((e=>new ta(o[e],h,c,t)))),r.propertyAttributes&&(p=r.propertyAttributes.map((e=>new Nn(l[e],h,c))))),this.schema=n,this.tableAccessors=u,this.textureAccessors=d,this.attributeAccessors=p,this.object=s,this.textures=t,this.nodeMetadata=r}getPropertyTableData(e,t,i=null){if(Array.isArray(e)){i||(i=[]);let r=Math.min(e.length,t.length);i.length=r;for(let s=0;s<r;s++){let r=this.tableAccessors[e[s]];i[s]=r.getData(t[s],i[s])}}else i||(i={}),i=this.tableAccessors[e].getData(t,i);if(Array.isArray(e)!==Array.isArray(i)||Array.isArray(e)!==Array.isArray(t))throw Error("StructuralMetadata: Scalar and array inputs cannot be mixed.");return i}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,i=[]){let r=this.textureAccessors;i.length=r.length;for(let s=0;s<r.length;s++)i[s]=r[s].getData(e,t,this.object.geometry,i[s]);return i}async getPropertyTextureDataAsync(e,t,i=[]){let r=this.textureAccessors;i.length=r.length;let s=[];for(let n=0;n<r.length;n++){let a=r[n].getDataAsync(e,t,this.object.geometry,i[n]).then((e=>{i[n]=e}));s.push(a)}return await Promise.all(s),i}getPropertyTextureInfo(){return this.textureAccessors}getPropertyAttributeData(e,t=[]){let i=this.attributeAccessors;t.length=i.length;for(let r=0;r<i.length;r++)t[r]=i[r].getData(e,this.object.geometry,t[r]);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()))}},ra="EXT_structural_metadata";function sa(e,t=[]){var i;let r=(null==(i=e.json.textures)?void 0:i.length)||0,s=Array(r).fill(null);return t.forEach((({properties:t})=>{for(let i in t){let{index:r}=t[i];null===s[r]&&(s[r]=e.loadTexture(r))}})),Promise.all(s)}function na(e,t=[]){var i;let r=(null==(i=e.json.bufferViews)?void 0:i.length)||0,s=Array(r).fill(null);return t.forEach((({properties:t})=>{for(let i in t){let{values:r,arrayOffsets:n,stringOffsets:a}=t[i];null===s[r]&&(s[r]=e.getDependency("bufferView",r)),null===s[n]&&(s[n]=e.getDependency("bufferView",n)),null===s[a]&&(s[a]=e.getDependency("bufferView",a))}})),Promise.all(s)}var aa=class{constructor(e){this.parser=e,this.name=ra}async afterRoot({scene:e,parser:t}){let i=t.json.extensionsUsed;if(!i||!i.includes(ra))return;let s=null,n=t.json.extensions[ra];if(n.schemaUri){let{manager:e,path:i,requestHeader:a,crossOrigin:o}=t.options,l=new URL(n.schemaUri,i).toString(),c=new r.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([sa(t,n.propertyTextures),na(t,n.propertyTables),s]),l=new ia(n,a,o);e.userData.structuralMetadata=l,e.traverse((e=>{var i;if(t.associations.has(e)){let{meshes:r,primitives:s}=t.associations.get(e),c=null==(i=t.json.meshes[r])?void 0:i.primitives[s];if(c&&c.extensions&&c.extensions[ra]){let t=c.extensions[ra];e.userData.structuralMetadata=new ia(n,a,o,t,e)}else e.userData.structuralMetadata=l}}))}},oa=new r.Vector2,la=new r.Vector2,ca=new r.Vector2;var ha=class{constructor(e,t,i){this.geometry=e,this.textures=t,this.data=i,this._asyncRead=!1,this.featureIds=i.featureIds.map((e=>{let{texture:t,...i}=e,r={label:null,propertyTable:null,nullFeatureId:null,...i};return t&&(r.texture={texCoord:0,channels:[0],...t}),r}))}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:i,textures:r,featureIds:s}=this,n=Array(s.length).fill(null),a=s.length;jn.increaseSizeTo(a);let o=Kn(i,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=r[e.texture.index];Yn(i,e.texture.texCoord,t,o,oa),Qn(oa,s.image.width,s.image.height,la),ca.set(u,0),jn.renderPixelToTarget(r[e.texture.index],la,ca)}else if("attribute"in e){let t=i.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?jn.readDataAsync(c).then((()=>(h(),n))):(jn.readData(c),h(),n);function h(){let e=new Uint32Array(1);for(let t=0,i=s.length;t<i;t++){let i=s[t],r="nullFeatureId"in i?i.nullFeatureId:null;if("texture"in i){let{channels:s}=i.texture,a=s.map((e=>c[4*t+e]));new Uint8Array(e.buffer).set(a);let o=e[0];o!==r&&(n[t]=o)}}}}dispose(){this.textures.forEach((e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())}))}},ua="EXT_mesh_features";function da(e,t,i){e.traverse((e=>{var r;if(t.associations.has(e)){let{meshes:s,primitives:n}=t.associations.get(e),a=null==(r=t.json.meshes[s])?void 0:r.primitives[n];a&&a.extensions&&a.extensions[ua]&&i(e,a.extensions[ua])}}))}var pa=class{constructor(e){this.parser=e,this.name=ua}async afterRoot({scene:e,parser:t}){var i;let r=t.json.extensionsUsed;if(!r||!r.includes(ua))return;let s=(null==(i=t.json.textures)?void 0:i.length)||0,n=Array(s).fill(null);da(e,t,((e,{featureIds:i})=>{i.forEach((e=>{if(e.texture&&null===n[e.texture.index]){let i=e.texture.index;n[i]=t.loadTexture(i)}}))}));let a=await Promise.all(n);da(e,t,((e,t)=>{e.userData.meshFeatures=new ha(e.geometry,a,t)}))}},ma=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])}}},fa=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 ma)),this.metadata&&(t.register((()=>new aa)),t.register((()=>new pa))),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())}},ga=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:i=0}=e;this.name="UNLOAD_TILES_PLUGIN",this.tiles=null,this.lruCache=new oe,this.deferCallbacks=new ya,this.delay=t,this.bytesTarget=i}init(e){this.tiles=e;let{lruCache:t,deferCallbacks:i}=this,r=t=>{let i=t.engineData.scene;e.visibleTiles.has(t)||e.invokeOnePlugin((e=>e.unloadTileFromGPU&&e.unloadTileFromGPU(i,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,r),t.setMemoryUsage(s,e.calculateBytesUsed(s,n)||1),e.markTileUsed(s),i.cancel(s)):i.run(s)},this._onDisposeModel=({tile:e})=>{t.remove(e),i.cancel(e)},i.callback=e=>{t.markUnused(e),t.scheduleUnload()},e.forEachLoadedModel(((t,i)=>{let r=e.visibleTiles.has(i);this._onVisibilityChangeCallback({tile:i,visible:r})})),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 i=t[e];i&&i.isTexture&&i.dispose()}}e.geometry&&e.geometry.dispose()}))}dispose(){let{lruCache:e,tiles:t,deferCallbacks:i}=this;t.removeEventListener("tile-visibility-change",this._onVisibilityChangeCallback),t.removeEventListener("update-before",this._onUpdateBefore),t.removeEventListener("dispose-model",this._onDisposeModel),i.cancelAll(),e.minBytesSize=0,e.minSize=0,e.maxSize=0,e.markAllUnused(),e.scheduleUnload()}},ya=class{constructor(e=()=>{}){this.map=new Map,this.callback=e,this.delay=0}run(e){let{map:t,delay:i}=this;if(t.has(e))throw Error("DeferCallbackManager: Callback already initialized.");0===i?this.callback(e):t.set(e,setTimeout((()=>{this.callback(e),t.delete(e)}),i))}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:va}=r.MathUtils,Ta=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 i=0===t.get(e).fadeOutTarget;t.delete(e),this.fadeCount--,this.onFadeComplete&&this.onFadeComplete(e,i),0===this.fadeCount&&this.onFadeSetComplete&&this.onFadeSetComplete()}completeAllFades(){this._fadeState.forEach(((e,t)=>{this.completeFade(t)}))}forEachObject(e){this._fadeState.forEach(((t,i)=>{e(i,t)}))}fadeIn(e){let t=this.guaranteeState(e),i=this._fadeState.get(e);i.fadeInTarget=1,i.fadeOutTarget=0,i.fadeOut=0,t&&(this.fadeCount++,1===this.fadeCount&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}fadeOut(e){let t=this.guaranteeState(e),i=this._fadeState.get(e);i.fadeOutTarget=1,t&&(i.fadeInTarget=1,i.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=va((e-this._lastTick)/this.duration,0,1);this._lastTick=e,this._fadeState.forEach(((e,i)=>{let{fadeOutTarget:r,fadeInTarget:s}=e,{fadeOut:n,fadeIn:a}=e,o=Math.sign(s-a);a=va(a+o*t,0,1);let l=Math.sign(r-n);n=va(n+l*t,0,1),e.fadeIn=a,e.fadeOut=n,((1===n||0===n)&&(1===a||0===a)||n>=a)&&this.completeFade(i)}))}},xa=Symbol("FADE_PARAMS");function ba(e,t){if(e[xa])return e[xa];let i={fadeIn:{value:0},fadeOut:{value:0},fadeTexture:{value:null}};return e[xa]=i,e.defines={...e.defines||{},FEATURE_FADE:0},e.onBeforeCompile=e=>{t&&t(e),e.uniforms={...e.uniforms,...i},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`))},i}var _a=class{constructor(){this._fadeParams=new WeakMap,this.fading=0}setFade(e,t,i){if(!e)return;let r=this._fadeParams;e.traverse((e=>{let s=e.material;if(s&&r.has(s)){let e=r.get(s);e.fadeIn.value=t,e.fadeOut.value=i;let n=Number(!(0===t||1===t)||!(0===i||1===i));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 i=e.material;i&&t.delete(i)}))}prepareMaterial(e){let t=this._fadeParams;t.has(e)||t.set(e,ba(e,e.onBeforeCompile))}},wa=class{constructor(e,t=new r.MeshBasicMaterial){this.other=e,this.material=t,this.visible=!0,this.parent=null,this._instanceInfo=[],this._visibilityChanged=!0;let i=new Proxy(this,{get(t,r){if(r in t)return t[r];{let s=e[r];return s instanceof Function?(...e)=>(t.syncInstances(),s.call(i,...e)):e[r]}},set:(t,i,r)=>(i in t?t[i]=r:e[i]=r,!0),deleteProperty:(t,i)=>i in t?delete t[i]:delete e[i]});return i}syncInstances(){let e=this._instanceInfo,t=this.other._instanceInfo;for(;t.length>e.length;){let i=e.length;e.push(new Proxy({visible:!1},{get:(e,r)=>r in e?e[r]:t[i][r],set:(e,r,s)=>(r in e?e[r]=s:t[i][r]=s,!0)}))}}},Ma=class extends wa{constructor(...e){super(...e);let t=this.material,i=ba(t,t.onBeforeCompile);t.defines.FEATURE_FADE=1,t.defines.USE_BATCHING_FRAG=1,t.needsUpdate=!0,this.fadeTexture=null,this._fadeParams=i}setFadeAt(e,t,i){this._initFadeTexture(),this.fadeTexture.setValueAt(e,255*t,255*i)}_initFadeTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=e*e*2,i=this.fadeTexture;if(!i||i.image.data.length!==t){let s=new Sa(new Uint8Array(t),e,e,r.RGFormat,r.UnsignedByteType);if(i){i.dispose();let e=i.image.data,t=this.fadeTexture.image.data,r=Math.min(e.length,t.length);t.set(new e.constructor(e.buffer,0,r))}this.fadeTexture=s,this._fadeParams.fadeTexture.value=s,s.needsUpdate=!0}}dispose(){this.fadeTexture&&this.fadeTexture.dispose()}},Sa=class extends r.DataTexture{setValueAt(e,...t){let{data:i,width:r,height:s}=this.image,n=Math.floor(i.length/(r*s)),a=!1;for(let o=0;o<n;o++){let r=e*n+o,s=i[r],l=t[o]||0;s!==l&&(i[r]=l,a=!0)}a&&(this.needsUpdate=!0)}},Aa=Symbol("HAS_POPPED_IN");var Ca=new r.Vector3,Ea=new r.Vector3,Ra=new r.Quaternion,Pa=new r.Quaternion,La=new r.Vector3;function Ua(){let e=this._fadeManager,t=this._fadeMaterialManager,i=this._fadingBefore,r=this._prevCameraTransforms,{tiles:s,maximumFadeOutTiles:n,batchedMesh:a}=this,{cameras:o}=s;e.update();let l=e.fadeCount;if(0!==i&&0!==l&&(s.dispatchEvent({type:"fade-change"}),s.dispatchEvent({type:"needs-render"})),n<this._fadingOutCount){let t=!0;o.forEach((e=>{if(!r.has(e))return;let i=e.matrixWorld,s=r.get(e);i.decompose(Ea,Pa,La),s.decompose(Ca,Ra,La);let n=Pa.angleTo(Ra),a=Ea.distanceTo(Ca);t&&(t=n>.25||a>.1)})),t&&e.completeAllFades()}if(o.forEach((e=>{r.get(e).copy(e.matrixWorld)})),e.forEachObject(((e,{fadeIn:i,fadeOut:r})=>{let n=e.engineData.scene;s.markTileUsed(e),n&&t.setFade(n,i,r),this.forEachBatchIds(e,((e,t,s)=>{t.setFadeAt(e,i,r),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 Ia=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 Ta,this._fadeMaterialManager=new _a,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 r.Matrix4)},this._onDeleteCamera=({camera:e})=>{this._prevCameraTransforms.delete(e)},this._onTileVisibilityChange=({tile:e})=>{this.forEachBatchIds(e,((e,t,i)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),i.batchedMesh.setVisibleAt(e,!1)}))},this._onUpdateBefore=()=>{this._fadingBefore=this._fadeManager.fadeCount},this._onUpdateAfter=()=>{Ua.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,i)=>{this._fadeMaterialManager.setFade(t.engineData.scene,0,0),this.forEachBatchIds(t,((e,t,r)=>{t.setFadeAt(e,0,0),t.setVisibleAt(e,!1),r.batchedMesh.setVisibleAt(e,i)})),i||(e.invokeOnePlugin((e=>e!==this&&e.setTileVisible&&e.setTileVisible(t,!1))),this._fadingOutCount--)};let i=new Map;e.cameras.forEach((e=>{i.set(e,new r.Matrix4)})),e.forEachLoadedModel(((e,t)=>{this._onLoadModel({scene:e})})),this.tiles=e,this._fadeManager=t,this._prevCameraTransforms=i}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 Ma(t,e),this.tiles.group.add(this.batchedMesh)}}else null!==this.batchedMesh&&(this._onBatchedMeshDispose(),this._onBatchedMeshDispose=null)}setTileVisible(e,t){let i=this._fadeManager,r=i.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 r&&i.completeFade(e),!1;if(i.isFadingOut(e)&&this._fadingOutCount--,t?1===e.internal.depthFromRenderedParent?((e[Aa]||this.fadeRootTiles)&&this._fadeManager.fadeIn(e),e[Aa]=!0):this._fadeManager.fadeIn(e):(this._fadingOutCount++,i.fadeOut(e)),this._quickFadeTiles.has(e)&&(this._fadeManager.completeFade(e),this._quickFadeTiles.delete(e)),r)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 i=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"),r=i.getTileBatchIds(e);r&&r.forEach((e=>{t(e,this.batchedMesh,i)}))}}};new ns(new r.MeshBasicMaterial),new r.DataTexture(new Uint8Array([255,255,255,255]),1,1).needsUpdate=!0;const Fa="#include <opaque_fragment>",ka=`\n float grayscale = dot(outgoingLight, vec3(0.299, 0.587, 0.114));\n outgoingLight = vec3(grayscale);\n ${Fa}\n`;function Da(e){const t=e.onBeforeCompile;e.onBeforeCompile=i=>{t.call(e,i),i.fragmentShader=i.fragmentShader.replace(Fa,ka)},e.needsUpdate=!0}class Oa extends p{constructor(e,t,i,r={}){super(),this.scene=e,this.camera=t,this.renderer=i,this.tiles=null,this.dracoLoader=null,this.apiToken=r.apiToken,this.googleMapsToken=r.googleMapsToken,this.googleMapsToken&&this.initTiles()}initTiles(){this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),this.dracoLoader=new Nr,this.tiles=new vr,this.tiles.errorTarget=40,this.tiles.registerPlugin(new qr({apiToken:this.googleMapsToken,autoRefreshToken:!0})),this.tiles.registerPlugin(new _n),this.tiles.registerPlugin(new Tn),this.tiles.registerPlugin(new ga),this.tiles.registerPlugin(new Ia),this.tiles.registerPlugin(new fa({dracoLoader:this.dracoLoader})),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(Da):e.material&&Da(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(){var e,t;this.tiles&&(this.scene.remove(this.tiles.group),this.tiles.dispose(),this.tiles=null),null==(t=null==(e=this.dracoLoader)?void 0:e.dispose)||t.call(e),this.listeners={}}}var Ba=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-Ba.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*Ba.Bounce.In(2*e):.5*Ba.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}}}}),Na=function(){return performance.now()},Va=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=[],i=0;i<arguments.length;i++)t[i]=arguments[i];for(var r=0,s=t;r<s.length;r++){var n=s[r];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 i=0,r=e;i<r.length;i++){var s=r[i];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=Na()),void 0===t&&(t=!0);var i=Object.keys(this._tweens);if(0!==i.length)for(;i.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<i.length;r++){var s=this._tweens[i[r]],n=!t;s&&!1===s.update(e,n)&&!t&&this.remove(s)}i=Object.keys(this._tweensAddedDuringUpdate)}},e}(),za={Linear:function(e,t){var i=e.length-1,r=i*t,s=Math.floor(r),n=za.Utils.Linear;return t<0?n(e[0],e[1],r):t>1?n(e[i],e[i-1],i-r):n(e[s],e[s+1>i?i:s+1],r-s)},Utils:{Linear:function(e,t,i){return(t-e)*i+e}}},Ga=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),Ha=new Va,ja=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=Ba.Linear.None,this._interpolationFunction=za.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Ga.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=Ha,Ha.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=Na()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var i in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i];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 r={};for(var s in this._valuesEnd)r[s]=this._valuesEnd[s];this._valuesEnd=r}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,i,r,s){for(var n in i){var a=e[n],o=Array.isArray(a),l=o?"array":typeof a,c=!o&&Array.isArray(i[n]);if("undefined"!==l&&"function"!==l){if(c){if(0===(g=i[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&&(i[n]=h)}if("object"!==l&&!o||!a||c)(void 0===t[n]||s)&&(t[n]=a),o||(t[n]*=1),r[n]=c?i[n].slice().reverse():t[n]||0;else{t[n]=o?[]:{};var m=a;for(var f in m)t[n][f]=m[f];r[n]=o?[]:{};var g=i[n];if(!this._isDynamic){var y={};for(var f in g)y[f]=g[f];i[n]=g=y}this._setupProperties(m,t[n],g,r[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=Na()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=Na()),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=Ba.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=za.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,i){var r,s,n=this;if(void 0===t&&(t=Na()),void 0===i&&(i=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!i)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!==(r=this._repeatDelayTime)&&void 0!==r?r: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,i=Math.min(t/n._duration,1);return 0===i&&a===n._duration?1:i}(),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,i,r){for(var s in i)if(void 0!==t[s]){var n=t[s]||0,a=i[s],o=Array.isArray(e[s]),l=Array.isArray(a);!o&&l?e[s]=this._interpolationFunction(a,r):"object"==typeof a&&a?this._updateProperties(e[s],n,a,r):"number"==typeof(a=this._handleRelativeValue(n,a))&&(e[s]=n+(a-n)*r)}},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],i=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof i?this._valuesStartRepeat[e]+parseFloat(i):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();Ga.nextId;var Wa=Ha;Wa.getAll.bind(Wa),Wa.removeAll.bind(Wa),Wa.add.bind(Wa),Wa.remove.bind(Wa),Wa.update.bind(Wa);const qa={CESIUM:void 0,GOOGLEMAPS:void 0},Xa=2e3;({Easing:Ba}).Easing.Quartic.InOut;class Ka extends r.DataTextureLoader{constructor(e){super(e),this.type=r.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||""))}},i=function(e,t,i){t=t||1024;let r=e.pos,s=-1,n=0,a="",o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(s=o.indexOf("\n"))&&n<t&&r<e.byteLength;)a+=o,n+=o.length,r+=128,o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));return-1<s&&(e.pos+=n+s+1,a+o.slice(0,s))},s=function(e,t,i,r){const s=e[t+3],n=Math.pow(2,s-128)/255;i[r+0]=e[t+0]*n,i[r+1]=e[t+1]*n,i[r+2]=e[t+2]*n,i[r+3]=1},n=function(e,t,i,s){const n=e[t+3],a=Math.pow(2,n-128)/255;i[s+0]=r.DataUtils.toHalfFloat(Math.min(e[t+0]*a,65504)),i[s+1]=r.DataUtils.toHalfFloat(Math.min(e[t+1]*a,65504)),i[s+2]=r.DataUtils.toHalfFloat(Math.min(e[t+2]*a,65504)),i[s+3]=r.DataUtils.toHalfFloat(1)},a=new Uint8Array(e);a.pos=0;const o=function(e){const r=/^\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=i(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=i(e),!1!==l;)if(o.string+=l+"\n","#"!==l.charAt(0)){if((c=l.match(r))&&(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,i,r){const s=i;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*i*r);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=r;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 i,r=0;for(;r<l&&o<e.byteLength;){i=e[o++];const s=i>128;if(s&&(i-=128),(0===i||r+i>l)&&t(3,"bad scanline data"),s){const t=e[o++];for(let e=0;e<i;e++)h[r++]=t}else h.set(e.subarray(o,o+i),r),r+=i,o+=i}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 r.FloatType:p=h.length/4;const e=new Float32Array(4*p);for(let i=0;i<p;i++)s(h,4*i,e,4*i);u=e,d=r.FloatType;break;case r.HalfFloatType:p=h.length/4;const t=new Uint16Array(4*p);for(let i=0;i<p;i++)n(h,4*i,t,4*i);u=t,d=r.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:r.LinearSRGBColorSpace,minFilter:r.LinearFilter,magFilter:r.LinearFilter,generateMipmaps:!1,flipY:!0}}setDataType(e){return this.type=e,this}}class Ya extends Ka{constructor(e){super(e)}}function Qa(e,t={}){return new Promise(((i,s)=>{const n=new Ya;n.setDataType(t.floatType||r.HalfFloatType),n.load(e,(e=>{i(e)}),(e=>{}),(e=>{s(e)}))}))}var $a,Za,Ja={exports:{}};$a||($a=1,Ja.exports=((Za=function(){function e(e){return r.appendChild(e.dom),e}function t(e){for(var t=0;t<r.children.length;t++)r.children[t].style.display=t===e?"block":"none";i=e}var i=0,r=document.createElement("div");r.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",r.addEventListener("click",(function(e){e.preventDefault(),t(++i%r.children.length)}),!1);var s=(performance||Date).now(),n=s,a=0,o=e(new Za.Panel("FPS","#0ff","#002")),l=e(new Za.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var c=e(new Za.Panel("MB","#f08","#201"));return t(0),{REVISION:16,dom:r,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:r,setMode:t}}).Panel=function(e,t,i){var r=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=i,g.fillRect(0,0,o,l),g.fillStyle=t,g.fillText(e,c,h),g.fillRect(u,d,p,m),g.fillStyle=i,g.globalAlpha=.9,g.fillRect(u,d,p,m),{dom:f,update:function(l,y){r=Math.min(r,l),s=Math.max(s,l),g.fillStyle=i,g.globalAlpha=1,g.fillRect(0,0,o,d),g.fillStyle=t,g.fillText(n(l)+" "+e+" ("+n(r)+"-"+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=i,g.globalAlpha=.9,g.fillRect(u+p-a,d,a,n((1-l/y)*m))}}},Za));const eo={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 to{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register((function(e){return new ko(e)})),this.register((function(e){return new Do(e)})),this.register((function(e){return new Vo(e)})),this.register((function(e){return new zo(e)})),this.register((function(e){return new Go(e)})),this.register((function(e){return new Ho(e)})),this.register((function(e){return new Oo(e)})),this.register((function(e){return new Bo(e)})),this.register((function(e){return new No(e)})),this.register((function(e){return new jo(e)})),this.register((function(e){return new Wo(e)})),this.register((function(e){return new qo(e)})),this.register((function(e){return new Xo(e)})),this.register((function(e){return new Ko(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,i,r){const s=new Fo,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,r).catch(i)}parseAsync(e,t){const i=this;return new Promise((function(r,s){i.parse(e,r,s,t)}))}}const io=0,ro=1,so=2,no=3,ao=4,oo=5120,lo=5121,co=5122,ho=5123,uo=5124,po=5125,mo=5126,fo=34962,go=34963,yo=9728,vo=9729,To=9984,xo=9985,bo=9986,_o=9987,wo=33071,Mo=33648,So=10497,Ao="KHR_mesh_quantization",Co={};Co[r.NearestFilter]=yo,Co[r.NearestMipmapNearestFilter]=To,Co[r.NearestMipmapLinearFilter]=bo,Co[r.LinearFilter]=vo,Co[r.LinearMipmapNearestFilter]=xo,Co[r.LinearMipmapLinearFilter]=_o,Co[r.ClampToEdgeWrapping]=wo,Co[r.RepeatWrapping]=So,Co[r.MirroredRepeatWrapping]=Mo;const Eo={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},Ro=new r.Color;function Po(e,t){return e.length===t.length&&e.every((function(e,i){return e===t[i]}))}function Lo(e){return 4*Math.ceil(e/4)}function Uo(e,t=0){const i=Lo(e.byteLength);if(i!==e.byteLength){const r=new Uint8Array(i);if(r.set(new Uint8Array(e)),0!==t)for(let s=e.byteLength;s<i;s++)r[s]=t;return r.buffer}return e}function Io(){return"undefined"==typeof document&&"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")}class Fo{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"+r.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,i={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1,copyright:null},i),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);const r=this,s=r.buffers,n=r.json;i=r.options;const a=r.extensionsUsed,o=r.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),i.copyright&&(n.asset.copyright=i.copyright),!0===i.binary){const e=new FileReader;e.readAsArrayBuffer(l),e.onloadend=function(){const i=Uo(e.result),r=new DataView(new ArrayBuffer(8));r.setUint32(0,i.byteLength,!0),r.setUint32(4,5130562,!0);const s=Uo((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+r.byteLength+i.byteLength;c.setUint32(8,h,!0);const u=new Blob([l,o,s,r,i],{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 i=e.result;n.buffers[0].uri=i,t(n)}}else t(n)}serializeUserData(e,t){if(0===Object.keys(e.userData).length)return;const i=this.options,r=this.extensionsUsed;try{const s=JSON.parse(JSON.stringify(e.userData));if(i.includeCustomExtensions&&s.gltfExtensions){void 0===t.extensions&&(t.extensions={});for(const e in s.gltfExtensions)t.extensions[e]=s.gltfExtensions[e],r[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 r.Vector3;for(let i=0,r=e.count;i<r;i++)if(Math.abs(t.fromBufferAttribute(e,i).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 i=e.clone(),s=new r.Vector3;for(let r=0,n=i.count;r<n;r++)s.fromBufferAttribute(i,r),0===s.x&&0===s.y&&0===s.z?s.setX(1):s.normalize(),i.setXYZ(r,s.x,s.y,s.z);return t.attributesNormalized.set(e,i),i}applyTextureTransform(e,t){let i=!1;const r={};0===t.offset.x&&0===t.offset.y||(r.offset=t.offset.toArray(),i=!0),0!==t.rotation&&(r.rotation=t.rotation,i=!0),1===t.repeat.x&&1===t.repeat.y||(r.scale=t.repeat.toArray(),i=!0),i&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=r,this.extensionsUsed.KHR_texture_transform=!0)}async buildMetalRoughTextureAsync(e,t){if(e===t)return e;function i(e){return e.colorSpace===r.SRGBColorSpace?function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}:function(e){return e}}e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e)),t instanceof r.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=Io();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=i(e),r=c.getImageData(0,0,a,o).data;for(let e=2;e<r.length;e+=4)h.data[e]=256*t(r[e]/256)}if(n){c.drawImage(n,0,0,a,o);const e=i(t),r=c.getImageData(0,0,a,o).data;for(let t=1;t<r.length;t+=4)h.data[t]=256*e(r[t]/256)}c.putImageData(h,0,0);const u=(e||t).clone();return u.source=new r.TextureSource(l),u.colorSpace=r.NoColorSpace,u.channel=(e||t).channel,e&&t&&(e.channel,t.channel),u}async buildNormalMapTextureAsync(e,t,i){e instanceof r.CompressedTexture&&(e=await this.decompressTextureAsync(e));const s=e.image,n=Io();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 r=0;r<l.length;r+=4)t&&(l[r+0]=255-l[r+0]),i&&(l[r+1]=255-l[r+1]);a.putImageData(o,0,0);const c=e.clone();return c.source=new r.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,i=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),i.push(e),0}processBufferView(e,t,i,s,n){const a=this.json;let o;switch(a.bufferViews||(a.bufferViews=[]),t){case oo:case lo:o=1;break;case co:case ho:o=2;break;default:o=4}let l=e.itemSize*o;n===fo&&(l=4*Math.ceil(l/4));const c=Lo(s*l),h=new DataView(new ArrayBuffer(c));let u=0;for(let p=i;p<i+s;p++){for(let i=0;i<e.itemSize;i++){let s;e.itemSize>4?s=e.array[p*e.itemSize+i]:(0===i?s=e.getX(p):1===i?s=e.getY(p):2===i?s=e.getZ(p):3===i&&(s=e.getW(p)),!0===e.normalized&&(s=r.MathUtils.normalize(s,e.array))),t===mo?h.setFloat32(u,s,!0):t===uo?h.setInt32(u,s,!0):t===po?h.setUint32(u,s,!0):t===co?h.setInt16(u,s,!0):t===ho?h.setUint16(u,s,!0):t===oo?h.setInt8(u,s):t===lo&&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===fo&&(d.byteStride=l),this.byteOffset+=c,a.bufferViews.push(d);return{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,i=t.json;return i.bufferViews||(i.bufferViews=[]),new Promise((function(r){const s=new FileReader;s.readAsArrayBuffer(e),s.onloadend=function(){const e=Uo(s.result),n={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};t.byteOffset+=e.byteLength,r(i.bufferViews.push(n)-1)}}))}processAccessor(e,t,i,s){const n=this.json;let a;if(e.array.constructor===Float32Array)a=mo;else if(e.array.constructor===Int32Array)a=uo;else if(e.array.constructor===Uint32Array)a=po;else if(e.array.constructor===Int16Array)a=co;else if(e.array.constructor===Uint16Array)a=ho;else if(e.array.constructor===Int8Array)a=oo;else{if(e.array.constructor!==Uint8Array)throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);a=lo}if(void 0===i&&(i=0),void 0!==s&&s!==1/0||(s=e.count),0===s)return null;const o=function(e,t,i){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+i;n++)for(let t=0;t<e.itemSize;t++){let i;e.itemSize>4?i=e.array[n*e.itemSize+t]:(0===t?i=e.getX(n):1===t?i=e.getY(n):2===t?i=e.getZ(n):3===t&&(i=e.getW(n)),!0===e.normalized&&(i=r.MathUtils.normalize(i,e.array))),s.min[t]=Math.min(s.min[t],i),s.max[t]=Math.max(s.max[t],i)}return s}(e,i,s);let l;void 0!==t&&(l=e===t.index?go:fo);const c=this.processBufferView(e,a,i,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,i,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/"+i.toString();if(void 0!==c[h])return c[h];a.images||(a.images=[]);const u={mimeType:s},d=Io();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===i&&(p.translate(0,d.height),p.scale(1,-1)),void 0!==e.data){r.RGBAFormat,e.width>o.maxTextureSize||(e.height,o.maxTextureSize);const t=new Uint8ClampedArray(e.height*e.width*4);for(let i=0;i<t.length;i+=4)t[i+0]=e.data[i+0],t[i+1]=e.data[i+1],t[i+2]=e.data[i+2],t[i+3]=e.data[i+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 i;return"image/jpeg"===t?i=.92:"image/webp"===t&&(i=.8),e.convertToBlob({type:t,quality:i})}return new Promise((i=>e.toBlob(i,t)))}(d,s).then((e=>t.processBufferViewImage(e))).then((e=>{u.bufferView=e}))):u.uri=r.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 i={magFilter:Co[e.magFilter],minFilter:Co[e.minFilter],wrapS:Co[e.wrapS],wrapT:Co[e.wrapT]};return t.samplers.push(i)-1}async processTextureAsync(e){const t=this.options,i=this.cache,s=this.json;if(i.textures.has(e))return i.textures.get(e);s.textures||(s.textures=[]),e instanceof r.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 i.textures.set(e,l),l}async processMaterialAsync(e,t){const i=this.cache,s=this.json,n=void 0!==t&&t.hasAttribute("tangent"),a=e.normalMap?e.uuid+":"+n:e.uuid;if(i.materials.has(a))return i.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(Po(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),i={index:await this.processTextureAsync(t),texCoord:t.channel};this.applyTextureTransform(i,t),o.pbrMetallicRoughness.metallicRoughnessTexture=i}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,r=t.x<0,s=n?t.y<0:t.y>0;let a=e.normalMap;if(r||s){!1===i.normalMaps.has(e.normalMap)&&i.normalMaps.set(e.normalMap,{});const t=i.normalMaps.get(e.normalMap),n=`${r}:${s}`;void 0===t[n]&&(t[n]=await this.buildNormalMapTextureAsync(e.normalMap,r,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===r.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 i.materials.set(a,c),c}async processMeshAsync(e){const t=this.cache,i=this.json,r=[e.geometry.uuid];if(Array.isArray(e.material))for(let T=0,x=e.material.length;T<x;T++)r.push(e.material[T].uuid);else r.push(e.material.uuid);const s=r.join(":");if(t.meshes.has(s))return t.meshes.get(s);const n=e.geometry;let a;a=e.isLineSegments?ro:e.isLineLoop?so:e.isLine?no:e.isPoints?io:e.material.wireframe?ro:ao;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 i=e.array;"JOINTS_0"!==T||i instanceof Uint16Array||i instanceof Uint8Array?(i instanceof Uint32Array||i instanceof Int32Array)&&!T.startsWith("_")&&(p=to.Utils.toTypedBufferAttribute(e,Float32Array)):p=to.Utils.toTypedBufferAttribute(e,Uint16Array);const r=this.processAccessor(p||e,n);null!==r&&(T.startsWith("_")||this.detectMeshQuantization(T,e),l[T]=r,t.attributes.set(this.getUID(e),r))}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 i=[],r=[],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 i=n.morphAttributes[e][a],r=e.toUpperCase(),s=n.attributes[e];if(t.attributes.has(this.getUID(i,!0))){o[r]=t.attributes.get(this.getUID(i,!0));continue}const c=i.clone();if(!n.morphTargetsRelative)for(let e=0,t=i.count;e<t;e++)for(let r=0;r<i.itemSize;r++)0===r&&c.setX(e,i.getX(e)-s.getX(e)),1===r&&c.setY(e,i.getY(e)-s.getY(e)),2===r&&c.setZ(e,i.getZ(e)-s.getZ(e)),3===r&&c.setW(e,i.getW(e)-s.getW(e));o[r]=this.processAccessor(c,n),t.attributes.set(this.getUID(s,!0),o[r])}h.push(o),i.push(e.morphTargetInfluences[a]),void 0!==e.morphTargetDictionary&&r.push(s[a])}o.weights=i,r.length>0&&(o.extras={},o.extras.targetNames=r)}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,i=n.attributes.position.count;t<i;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 i=this.getUID(n.index);void 0===y[T].start&&void 0===y[T].count||(i+=":"+y[T].start+":"+y[T].count),t.attributes.has(i)?e.indices=t.attributes.get(i):(e.indices=this.processAccessor(n.index,n,y[T].start,y[T].count),t.attributes.set(i,e.indices)),null===e.indices&&delete e.indices}const i=await this.processMaterialAsync(g[y[T].materialIndex],n);null!==i&&(e.material=i),c.push(e)}!0===f&&n.setIndex(null),o.primitives=c,i.meshes||(i.meshes=[]),await this._invokeAllAsync((function(t){t.writeMesh&&t.writeMesh(e,o)}));const v=i.meshes.push(o)-1;return t.meshes.set(s,v),v}detectMeshQuantization(e,t){if(this.extensionsUsed[Ao])return;let i;switch(t.array.constructor){case Int8Array:i="byte";break;case Uint8Array:i="unsigned byte";break;case Int16Array:i="short";break;case Uint16Array:i="unsigned short";break;default:return}t.normalized&&(i+=" normalized");const r=e.split("_",1)[0];eo[r]&&eo[r].includes(i)&&(this.extensionsUsed[Ao]=!0,this.extensionsRequired[Ao]=!0)}processCamera(e){const t=this.json;t.cameras||(t.cameras=[]);const i=e.isOrthographicCamera,s={type:i?"orthographic":"perspective"};return i?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:r.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 i=this.json,s=this.nodeMap;i.animations||(i.animations=[]);const n=(e=to.Utils.mergeMorphTargetTracks(e.clone(),t)).tracks,a=[],o=[];for(let c=0;c<n.length;++c){const e=n[c],i=r.PropertyBinding.parseTrackName(e.name);let l=r.PropertyBinding.findNode(t,i.nodeName);const h=Eo[i.propertyName];if("bones"===i.objectName&&(l=!0===l.isSkinnedMesh?l.skeleton.getBoneByName(i.objectIndex):void 0),!l||!h)continue;const u=1;let d,p=e.values.length/e.times.length;h===Eo.morphTargetInfluences&&(p/=l.morphTargetInfluences.length),!0===e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(d="CUBICSPLINE",p/=3):d=e.getInterpolation()===r.InterpolateDiscrete?"STEP":"LINEAR",o.push({input:this.processAccessor(new r.BufferAttribute(e.times,u)),output:this.processAccessor(new r.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_"+i.animations.length,samplers:o,channels:a};return this.serializeUserData(e,l),i.animations.push(l),i.animations.length-1}processSkin(e){const t=this.json,i=this.nodeMap,s=t.nodes[i.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 r.Matrix4;for(let r=0;r<n.bones.length;++r)o.push(i.get(n.bones[r])),c.copy(n.boneInverses[r]),c.multiply(e.bindMatrix).toArray(l,16*r);void 0===t.skins&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new r.BufferAttribute(l,16)),joints:o,skeleton:i.get(a)});return s.skin=t.skins.length-1}async processNodeAsync(e){const t=this.json,i=this.options,r=this.nodeMap;if(t.nodes||(t.nodes=[]),null!==e.pivot)return await this._processNodeWithPivotAsync(e);const s={};if(i.trs){const t=e.quaternion.toArray(),i=e.position.toArray(),r=e.scale.toArray();Po(t,[0,0,0,1])||(s.rotation=t),Po(i,[0,0,0])||(s.translation=i),Po(r,[1,1,1])||(s.scale=r)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===Po(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(r.set(e,n),e.children.length>0){const t=[];for(let r=0,s=e.children.length;r<s;r++){const s=e.children[r];if(s.visible||!1===i.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,i=this.options,r=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();Po(a,[0,0,0,1])||(n.rotation=a),Po(o,[0,0,0])||(n.translation=o),Po(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;r.set(e,c);const h={},u=[-s.x,-s.y,-s.z];if(Po(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 r=0,s=e.children.length;r<s;r++){const s=e.children[r];if(s.visible||!1===i.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,i=this.options;t.scenes||(t.scenes=[],t.scene=0);const r={};""!==e.name&&(r.name=e.name),t.scenes.push(r);const s=[];for(let n=0,a=e.children.length;n<a;n++){const t=e.children[n];if(t.visible||!1===i.onlyVisible){const e=await this.processNodeAsync(t);null!==e&&s.push(e)}}s.length>0&&(r.nodes=s),this.serializeUserData(e,r)}async processObjectsAsync(e){const t=new r.Scene;t.name="AuxScene";for(let i=0;i<e.length;i++)t.children.push(e[i]);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 i=[];for(let s=0;s<e.length;s++)e[s]instanceof r.Scene?await this.processSceneAsync(e[s]):i.push(e[s]);i.length>0&&await this.processObjectsAsync(i);for(let r=0;r<this.skins.length;++r)this.processSkin(this.skins[r]);if(1===e.length)for(let r=0;r<t.animations.length;++r)this.processAnimation(t.animations[r],e[0]);else for(let r=0;r<e.length;r++){const i=t.animations[r]||[];for(let t=0;t<i.length;++t)this.processAnimation(i[t],e[r])}await this._invokeAllAsync((function(t){t.afterParse&&t.afterParse(e)}))}async _invokeAllAsync(e){for(let t=0,i=this.plugins.length;t<i;t++)await e(this.plugins[t])}}class ko{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 i=this.writer,r=i.json,s=i.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]||(r.extensions=r.extensions||{},r.extensions[this.name]={lights:[]},s[this.name]=!0);const a=r.extensions[this.name].lights;a.push(n),t.extensions=t.extensions||{},t.extensions[this.name]={light:a.length-1}}}class Do{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,t){if(!e.isMeshBasicMaterial)return;const i=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},i[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}}class Oo{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.clearcoat)return;const i=this.writer,r=i.extensionsUsed,s={};if(s.clearcoatFactor=e.clearcoat,e.clearcoatMap){const t={index:await i.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};i.applyTextureTransform(t,e.clearcoatMap),s.clearcoatTexture=t}if(s.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){const t={index:await i.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};i.applyTextureTransform(t,e.clearcoatRoughnessMap),s.clearcoatRoughnessTexture=t}if(e.clearcoatNormalMap){const t={index:await i.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};1!==e.clearcoatNormalScale.x&&(t.scale=e.clearcoatNormalScale.x),i.applyTextureTransform(t,e.clearcoatNormalMap),s.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}}class Bo{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.dispersion)return;const i=this.writer.extensionsUsed,r={};r.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=r,i[this.name]=!0}}class No{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.iridescence)return;const i=this.writer,r=i.extensionsUsed,s={};if(s.iridescenceFactor=e.iridescence,e.iridescenceMap){const t={index:await i.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};i.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 i.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};i.applyTextureTransform(t,e.iridescenceThicknessMap),s.iridescenceThicknessTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}}class Vo{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const i=this.writer,r=i.extensionsUsed,s={};if(s.transmissionFactor=e.transmission,e.transmissionMap){const t={index:await i.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};i.applyTextureTransform(t,e.transmissionMap),s.transmissionTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}}class zo{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const i=this.writer,r=i.extensionsUsed,s={};if(s.thicknessFactor=e.thickness,e.thicknessMap){const t={index:await i.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};i.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,r[this.name]=!0}}class Go{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1.5===e.ior)return;const i=this.writer.extensionsUsed,r={};r.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=r,i[this.name]=!0}}class Ho{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(Ro)&&!e.specularIntensityMap&&!e.specularColorMap)return;const i=this.writer,r=i.extensionsUsed,s={};if(e.specularIntensityMap){const t={index:await i.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};i.applyTextureTransform(t,e.specularIntensityMap),s.specularTexture=t}if(e.specularColorMap){const t={index:await i.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};i.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,r[this.name]=!0}}class jo{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.sheen)return;const i=this.writer,r=i.extensionsUsed,s={};if(e.sheenRoughnessMap){const t={index:await i.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};i.applyTextureTransform(t,e.sheenRoughnessMap),s.sheenRoughnessTexture=t}if(e.sheenColorMap){const t={index:await i.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};i.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,r[this.name]=!0}}class Wo{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,t){if(!e.isMeshPhysicalMaterial||0==e.anisotropy)return;const i=this.writer,r=i.extensionsUsed,s={};if(e.anisotropyMap){const t={index:await i.processTextureAsync(e.anisotropyMap)};i.applyTextureTransform(t,e.anisotropyMap),s.anisotropyTexture=t}s.anisotropyStrength=e.anisotropy,s.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}}class qo{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.emissiveIntensity)return;const i=this.writer.extensionsUsed,r={};r.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=r,i[this.name]=!0}}class Xo{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,t){if(!e.isMeshStandardMaterial||1===e.bumpScale&&!e.bumpMap)return;const i=this.writer,r=i.extensionsUsed,s={};if(e.bumpMap){const t={index:await i.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};i.applyTextureTransform(t,e.bumpMap),s.bumpTexture=t}s.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=s,r[this.name]=!0}}class Ko{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;const i=this.writer,s=e,n=new Float32Array(3*s.count),a=new Float32Array(4*s.count),o=new Float32Array(3*s.count),l=new r.Matrix4,c=new r.Vector3,h=new r.Quaternion,u=new r.Vector3;for(let r=0;r<s.count;r++)s.getMatrixAt(r,l),l.decompose(c,h,u),c.toArray(n,3*r),h.toArray(a,4*r),u.toArray(o,3*r);const d={TRANSLATION:i.processAccessor(new r.BufferAttribute(n,3)),ROTATION:i.processAccessor(new r.BufferAttribute(a,4)),SCALE:i.processAccessor(new r.BufferAttribute(o,3))};s.instanceColor&&(d._COLOR_0=i.processAccessor(s.instanceColor)),t.extensions=t.extensions||{},t.extensions[this.name]={attributes:d},i.extensionsUsed[this.name]=!0,i.extensionsRequired[this.name]=!0}}function Yo(e,t,i,s){const{lon:n,lat:a,alt:o}=r.ecefToGeodeticPosition(e,t,i),{east:l,north:c,up:h}=r.getEnuBasis(n,a),u=(new r.Matrix4).makeBasis((new r.Vector3).fromArray(l),(new r.Vector3).fromArray(c),(new r.Vector3).fromArray(h)),d=(new r.Quaternion).setFromRotationMatrix(u).clone().invert().multiply(s),p=(new r.Euler).setFromQuaternion(d,"ZYX");return{lon:n,lat:a,alt:o,pitch:r.MathUtils.radToDeg(p.x)-90,yaw:r.MathUtils.radToDeg(p.z),roll:r.MathUtils.radToDeg(p.y)}}function Qo(e,t){return(new r.Vector3).fromArray(r.getEnuBasis(e,t).up)}function $o(e,t,i,s,n){const a=r.getEnuBasis(e,t);i+=90;const o=(new r.Matrix4).makeBasis((new r.Vector3).fromArray(a.east),(new r.Vector3).fromArray(a.north),(new r.Vector3).fromArray(a.up)),l=new r.Euler(r.MathUtils.degToRad(i),r.MathUtils.degToRad(n),r.MathUtils.degToRad(s),"ZYX"),c=(new r.Quaternion).setFromEuler(l);return(new r.Quaternion).setFromRotationMatrix(o).multiply(c)}function Zo(e,t){const i=(new r.Vector3).subVectors(t,e).normalize(),s=e.clone().normalize();Math.abs(i.dot(s))>.99&&s.set(0,0,1);const n=(new r.Vector3).crossVectors(i,s).normalize();return(new r.Vector3).crossVectors(n,i).normalize()}to.Utils={insertKeyframe:function(e,t){const i=.001,r=e.getValueSize(),s=new e.TimeBufferType(e.times.length+1),n=new e.ValueBufferType(e.values.length+r),a=e.createInterpolant(new e.ValueBufferType(r));let o;if(0===e.times.length){s[0]=t;for(let e=0;e<r;e++)n[e]=0;o=0}else if(t<e.times[0]){if(Math.abs(e.times[0]-t)<i)return 0;s[0]=t,s.set(e.times,1),n.set(a.evaluate(t),0),n.set(e.values,r),o=0}else if(t>e.times[e.times.length-1]){if(Math.abs(e.times[e.times.length-1]-t)<i)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)<i)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)*r),0),n.set(a.evaluate(t),(l+1)*r),n.set(e.values.slice((l+1)*r),(l+2)*r),o=l+1;break}}return e.times=s,e.values=n,o},mergeMorphTargetTracks:function(e,t){const i=[],s={},n=e.tracks;for(let a=0;a<n.length;++a){let e=n[a];const o=r.PropertyBinding.parseTrackName(e.name),l=r.PropertyBinding.findNode(t,o.nodeName);if("morphTargetInfluences"!==o.propertyName||void 0===o.propertyIndex){i.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(r.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,i.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 i=this.insertKeyframe(u,e.times[t]);u.values[i*c+h]=e.values[t]}}return e.tracks=i,e},toTypedBufferAttribute:function(e,t){const i=new r.BufferAttribute(new t(e.count*e.itemSize),e.itemSize,!1);if(!e.normalized&&!e.isInterleavedBufferAttribute)return i.array.set(e.array),i;for(let r=0,s=e.count;r<s;r++)for(let t=0;t<e.itemSize;t++)i.setComponent(r,t,e.getComponent(r,t));return i}};class Jo extends p{constructor(e){super(),this.camera=e,this.lookAt=new r.Vector3,this.cameraTween=null,this.lookAtTween=null,this.activeTransition=null,this.is2D=!1}animateTo(e,t,i=Xa){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(i<=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 r.Vector3(0,0,.25*-h).applyQuaternion(a).add(n),t=new r.Vector3(0,0,.25*-h).applyQuaternion(l).add(o),s=Zo(n,e),u=Zo(o,t);this.camera.up.copy(s),this.lookAt.copy(e),this.lookAtTween=new ja(this.lookAt).to(t,i).easing(Ba.Quartic.InOut).onComplete((()=>{this.lookAt.copy(t),this.lookAtTween=null,this.complete(c)})).start(),this.cameraTween=new ja(this.camera).to({position:o,up:u},i).easing(Ba.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 el extends r.Mesh{constructor(){const e=new r.ShaderMaterial({name:"SkyMaterial",uniforms:{turbidity:{value:5},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.5},sunPosition:{value:new r.Vector3},up:{value:new r.Vector3(0,1,0)},surfaceUp:{value:new r.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:r.BackSide,depthWrite:!1});super(new r.BoxGeometry(1,1,1),e),this.isSky=!0,this.type="Sky",this.material=e}setSurfaceUp(e){this.material.uniforms.surfaceUp.value.copy(e)}}class tl extends r.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,i,r,s,n;null==(i=null==(t=e.geometry)?void 0:t.dispose)||i.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==(r=e.dispose)||r.call(e));null==(s=o.dispose)||s.call(o)}e!==this&&(null==(n=e.dispose)||n.call(e))}))}}let il=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 i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:t,msg:i,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((i=>{const r=this._getIdleWorker();-1!==r?(this._initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=i,this.workers[r].postMessage(e,t)):this.queue.push({resolve:i,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 rl=9,sl=15,nl=16,al=22,ol=37,ll=43,cl=76,hl=83,ul=91,dl=97,pl=100,ml=103,fl=109,gl=122,yl=123,vl=131,Tl=132,xl=133,bl=134,_l=137,wl=138,Ml=139,Sl=140,Al=141,Cl=142,El=145,Rl=146,Pl=148,Ll=152,Ul=153,Il=154,Fl=155,kl=156,Dl=157,Ol=158,Bl=165,Nl=166,Vl=1000054e3,zl=1000054001,Gl=1000054004,Hl=1000054005,jl=1000066e3,Wl=1000066004;class ql{constructor(e,t,i,r){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,i),this._littleEndian=r,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 i=this._offset;let r=0;for(;this._dataView.getUint8(this._offset)!==t&&r<e;)r++,this._offset++;return r<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+i,r)}}const Xl=[171,75,84,88,32,50,48,187,13,10,26,10];function Kl(e){return(new TextDecoder).decode(e)}let Yl,Ql,$l;const Zl={env:{emscripten_notify_memory_growth:function(e){$l=new Uint8Array(Ql.exports.memory.buffer)}}};class Jl{init(){return Yl||(Yl="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,Zl))).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,Zl))).then(this._init),Yl)}_init(e){Ql=e.instance,Zl.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!Ql)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=e.byteLength,r=Ql.exports.malloc(i);$l.set(e,r),t=t||Number(Ql.exports.ZSTD_findDecompressedSize(r,i));const s=Ql.exports.malloc(t),n=Ql.exports.ZSTD_decompress(s,t,r,i),a=$l.slice(s,s+n);return Ql.exports.free(r),Ql.exports.free(s),a}}r.ColorManagement.spaces[r.SRGBColorSpace];const ec="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,tc="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,ic=new WeakMap;let rc;class sc extends r.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new il,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 r.FileLoader(this.manager);e.setWithCredentials(this.withCredentials);const t=new r.FileLoader(this.manager);let i,s;t.setWithCredentials(this.withCredentials),t.setResponseType("arraybuffer"),""===this.transcoderPath?(i=e.loadAsync(tc),s=t.loadAsync(ec)):(e.setPath(this.transcoderPath),i=e.loadAsync("basis_transcoder.js"),t.setPath(this.transcoderPath),s=t.loadAsync("basis_transcoder.wasm")),this.transcoderPending=Promise.all([i,s]).then((([e,t])=>{const i=sc.BasisWorker.toString(),r=["/* constants */","let _EngineFormat = "+JSON.stringify(sc.EngineFormat),"let _EngineType = "+JSON.stringify(sc.EngineType),"let _TranscoderFormat = "+JSON.stringify(sc.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(sc.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([r])),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,i,s){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const n=new r.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)}),i,s)}parse(e,t,i){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(ic.has(e)){return ic.get(e).promise.then(t).catch(i)}this._createTexture(e).then((e=>t?t(e):null)).catch(i)}_createTextureFrom(e,t){const{type:i,error:s,data:{faces:n,width:a,height:o,format:l,type:c,dfdFlags:h}}=e;if("error"===i)return Promise.reject(s);let u;if(6===t.faceCount)u=new r.CompressedCubeTexture(n,l,c);else{const e=n[0].mipmaps;u=t.layerCount>1?new r.CompressedArrayTexture(e,a,o,t.layerCount,l,c):new r.CompressedTexture(e,a,o,l,c)}return u.minFilter=1===n[0].mipmaps.length?r.LinearFilter:r.LinearMipmapLinearFilter,u.magFilter=r.LinearFilter,u.generateMipmaps=!1,u.needsUpdate=!0,u.colorSpace=cc(t),u.premultiplyAlpha=!!(1&h),u}async _createTexture(e,t={}){const i=function(e){const t=new Uint8Array(e.buffer,e.byteOffset,Xl.length);if(t[0]!==Xl[0]||t[1]!==Xl[1]||t[2]!==Xl[2]||t[3]!==Xl[3]||t[4]!==Xl[4]||t[5]!==Xl[5]||t[6]!==Xl[6]||t[7]!==Xl[7]||t[8]!==Xl[8]||t[9]!==Xl[9]||t[10]!==Xl[10]||t[11]!==Xl[11])throw new Error("Missing KTX 2.0 identifier.");const i={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},r=17*Uint32Array.BYTES_PER_ELEMENT,s=new ql(e,Xl.length,r,!0);i.vkFormat=s._nextUint32(),i.typeSize=s._nextUint32(),i.pixelWidth=s._nextUint32(),i.pixelHeight=s._nextUint32(),i.pixelDepth=s._nextUint32(),i.layerCount=s._nextUint32(),i.faceCount=s._nextUint32(),i.levelCount=s._nextUint32(),i.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(i.levelCount,1)*8,d=new ql(e,Xl.length+r,u,!0);for(let O=0,B=Math.max(i.levelCount,1);O<B;O++)i.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const p=new ql(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}i.dataFormatDescriptor.length=0,i.dataFormatDescriptor.push(v);const x=new ql(e,o,l,!0);for(;x._offset<l;){const e=x._nextUint32(),t=x._scan(e),r=Kl(t);if(i.keyValue[r]=x._nextUint8Array(e-t.byteLength-1),r.match(/^ktx/i)){const e=Kl(i.keyValue[r]);i.keyValue[r]=e.substring(0,e.lastIndexOf("\0"))}x._skip(e%4?4-e%4:0)}if(h<=0)return i;const b=new ql(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(i.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 i.globalData={endpointCount:_,selectorCount:w,imageDescs:E,endpointsData:I,selectorsData:F,tablesData:k,extendedData:D},i}(new Uint8Array(e)),s=i.vkFormat===jl&&167===i.dataFormatDescriptor[0].colorModel;if(!(0===i.vkFormat||s&&!this.workerConfig.astcHDRSupported))return async function(e){const{vkFormat:t}=e;if(void 0===oc[t])throw new Error("THREE.KTX2Loader: Unsupported vkFormat: "+t);lc[t];let i;2===e.supercompressionScheme&&(rc||(rc=new Promise((async e=>{const t=new Jl;await t.init(),e(t)}))),i=await rc);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=i.decode(c.levelData,c.uncompressedByteLength)}u=lc[t]===r.FloatType?new Float32Array(h.buffer,h.byteOffset,h.byteLength/Float32Array.BYTES_PER_ELEMENT):lc[t]===r.HalfFloatType||lc[t]===r.UnsignedShortType?new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT):lc[t]===r.UnsignedInt5999Type||lc[t]===r.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(nc.has(oc[t]))a=0===e.pixelDepth?new r.DataTexture(s[0].data,e.pixelWidth,e.pixelHeight):new r.Data3DTexture(s[0].data,e.pixelWidth,e.pixelHeight,e.pixelDepth),a.minFilter=n?r.NearestMipmapNearestFilter:r.NearestFilter,a.magFilter=r.NearestFilter,a.generateMipmaps=0===e.levelCount,a.normalized=ac.has(t);else{if(e.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");a=new r.CompressedTexture(s,e.pixelWidth,e.pixelHeight),a.minFilter=n?r.LinearMipmapLinearFilter:r.LinearFilter,a.magFilter=r.LinearFilter}return a.mipmaps=s,a.type=lc[t],a.format=oc[t],a.colorSpace=cc(e),a.needsUpdate=!0,Promise.resolve(a)}(i);const n=t,a=this.init().then((()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:n},[e]))).then((e=>this._createTextureFrom(e.data,i)));return ic.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL)}}sc.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},sc.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},sc.EngineFormat={RGBAFormat:r.RGBAFormat,RGBA_ASTC_4x4_Format:r.RGBA_ASTC_4x4_Format,RGB_BPTC_UNSIGNED_Format:r.RGB_BPTC_UNSIGNED_Format,RGBA_BPTC_Format:r.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:r.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:r.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:r.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:r.RGB_ETC1_Format,RGB_ETC2_Format:r.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:r.RGB_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:r.RGBA_S3TC_DXT1_Format},sc.EngineType={UnsignedByteType:r.UnsignedByteType,HalfFloatType:r.HalfFloatType,FloatType:r.FloatType},sc.BasisWorker=function(){let e,t,i;const r=_EngineFormat,s=_EngineType,n=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const n=r.data;switch(n.type){case"init":e=n.config,o=n.transcoderBinary,t=new Promise((e=>{i={wasmBinary:o,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),i.KTX2File}));break;case"transcode":t.then((()=>{try{const{faces:t,buffers:r,width:o,height:u,hasAlpha:d,format:p,type:m,dfdFlags:f}=function(t){const r=new i.KTX2File(new Uint8Array(t));function n(){r.close(),r.delete()}if(!r.isValid())throw n(),new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file");let o;if(r.isUASTC())o=a.UASTC;else if(r.isETC1S())o=a.ETC1S;else{if(!r.isHDR())throw new Error("THREE.KTX2Loader: Unknown Basis encoding");o=a.UASTC_HDR}const u=r.getWidth(),d=r.getHeight(),p=r.getLayers()||1,m=r.getLevels(),f=r.getFaces(),g=r.getHasAlpha(),y=r.getDFDFlags(),{transcoderFormat:v,engineFormat:T,engineType:x}=function(t,i,r,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(i)||!c(r)))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(!r.startTranscoding())throw n(),new Error("THREE.KTX2Loader: .startTranscoding failed");const b=[],_=[];for(let e=0;e<f;e++){const t=[];for(let i=0;i<m;i++){const a=[];let o,l;for(let t=0;t<p;t++){const c=r.getImageLevelInfo(i,t,e);0===e&&0===i&&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(r.getImageTranscodedSizeInBytes(i,t,0,v));const u=r.transcodeImage(h,i,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}},r)}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:[r.RGBA_ASTC_4x4_Format,r.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:[r.RGBA_BPTC_Format,r.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:[r.RGBA_S3TC_DXT1_Format,r.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:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],engineType:[s.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.ETC1],engineFormat:[r.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:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],engineType:[s.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[a.UASTC_HDR],transcoderFormat:[n.BC6H],engineFormat:[r.RGB_BPTC_UNSIGNED_Format],engineType:[s.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[n.RGBA32,n.RGBA32],engineFormat:[r.RGBAFormat,r.RGBAFormat],engineType:[s.UnsignedByteType,s.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[a.UASTC_HDR],transcoderFormat:[n.RGBA_HALF],engineFormat:[r.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 i=new Uint8Array(t);let r=0;for(let s=0;s<e.length;s++){const t=e[s];i.set(t,r),r+=t.byteLength}return i}};const nc=new Set([r.RGBAFormat,r.RGBFormat,r.RGFormat,r.RedFormat]),ac=new Set([91]),oc={[fl]:r.RGBAFormat,[ml]:r.RGFormat,[pl]:r.RedFormat,[dl]:r.RGBAFormat,[hl]:r.RGFormat,[cl]:r.RedFormat,[ul]:r.RGBAFormat,[ll]:r.RGBAFormat,[ol]:r.RGBAFormat,[al]:r.RGFormat,[nl]:r.RGFormat,[sl]:r.RedFormat,[rl]:r.RedFormat,[yl]:r.RGBFormat,[gl]:r.RGBFormat,[Ll]:r.RGBA_ETC2_EAC_Format,[Pl]:r.RGB_ETC2_Format,[Ul]:r.R11_EAC_Format,[Il]:r.SIGNED_R11_EAC_Format,[Fl]:r.RG11_EAC_Format,[kl]:r.SIGNED_RG11_EAC_Format,[jl]:r.RGBA_ASTC_4x4_Format,[Ol]:r.RGBA_ASTC_4x4_Format,[Dl]:r.RGBA_ASTC_4x4_Format,[Wl]:r.RGBA_ASTC_6x6_Format,[Nl]:r.RGBA_ASTC_6x6_Format,[Bl]:r.RGBA_ASTC_6x6_Format,[bl]:r.RGBA_S3TC_DXT1_Format,[xl]:r.RGBA_S3TC_DXT1_Format,[Tl]:r.RGB_S3TC_DXT1_Format,[vl]:r.RGB_S3TC_DXT1_Format,[wl]:r.RGBA_S3TC_DXT5_Format,[_l]:r.RGBA_S3TC_DXT5_Format,[Sl]:r.SIGNED_RED_RGTC1_Format,[Ml]:r.RED_RGTC1_Format,[Cl]:r.SIGNED_RED_GREEN_RGTC2_Format,[Al]:r.RED_GREEN_RGTC2_Format,[Rl]:r.RGBA_BPTC_Format,[El]:r.RGBA_BPTC_Format,[Hl]:r.RGBA_PVRTC_4BPPV1_Format,[zl]:r.RGBA_PVRTC_4BPPV1_Format,[Gl]:r.RGBA_PVRTC_2BPPV1_Format,[Vl]:r.RGBA_PVRTC_2BPPV1_Format},lc={[fl]:r.FloatType,[ml]:r.FloatType,[pl]:r.FloatType,[dl]:r.HalfFloatType,[hl]:r.HalfFloatType,[cl]:r.HalfFloatType,[ul]:r.UnsignedShortType,[ll]:r.UnsignedByteType,[ol]:r.UnsignedByteType,[al]:r.UnsignedByteType,[nl]:r.UnsignedByteType,[sl]:r.UnsignedByteType,[rl]:r.UnsignedByteType,[yl]:r.UnsignedInt5999Type,[gl]:r.UnsignedInt101111Type,[Ll]:r.UnsignedByteType,[Pl]:r.UnsignedByteType,[Ul]:r.UnsignedByteType,[Il]:r.UnsignedByteType,[Fl]:r.UnsignedByteType,[kl]:r.UnsignedByteType,[jl]:r.HalfFloatType,[Ol]:r.UnsignedByteType,[Dl]:r.UnsignedByteType,[Wl]:r.HalfFloatType,[Nl]:r.UnsignedByteType,[Bl]:r.UnsignedByteType,[bl]:r.UnsignedByteType,[xl]:r.UnsignedByteType,[Tl]:r.UnsignedByteType,[vl]:r.UnsignedByteType,[wl]:r.UnsignedByteType,[_l]:r.UnsignedByteType,[Sl]:r.UnsignedByteType,[Ml]:r.UnsignedByteType,[Cl]:r.UnsignedByteType,[Al]:r.UnsignedByteType,[Rl]:r.UnsignedByteType,[El]:r.UnsignedByteType,[Hl]:r.UnsignedByteType,[zl]:r.UnsignedByteType,[Gl]:r.UnsignedByteType,[Vl]:r.UnsignedByteType};function cc(e){const t=e.dataFormatDescriptor[0];return 1===t.colorPrimaries?2===t.transferFunction?r.SRGBColorSpace:r.LinearSRGBColorSpace:10===t.colorPrimaries?2===t.transferFunction?"display-p3":"display-p3-linear":(t.colorPrimaries,r.NoColorSpace)}class hc extends tl{constructor(e,t={},i={}){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=r.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.dracoLoader=new Nr,this.ktx2loader=new sc,this.ktx2loader.detectSupport(this.renderer),this.layers.set(s);const h=new vr(e);e.startsWith("http")||h.registerPlugin(new yn({apiToken:qa.CESIUM,assetId:e,autoRefreshToken:!0})),n&&h.registerPlugin(new Zr),h.registerPlugin(new fa({rtc:!0,dracoLoader:this.dracoLoader,ktxLoader:this.ktx2loader})),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(0===e.tile.__depth&&l&&!c)try{const t=e.tile.cached.scene.position,i=r.ecefToGeodeticPosition(...t.toArray()),s=r.geodeticOffsetToEcefDelta(i,o);h.group.position.add((new r.Vector3).fromArray(s)),c=!0}catch(s){null==(t=i.onError)||t.call(i,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 r.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)))}))})),h.addEventListener("load-tile-set",(e=>{})),this.tiles=h,this.add(h.group)}update(){super.update(),this.visible&&this.tiles.update()}dispose(){var e,t,i,r;super.dispose(),this.tiles&&(this.tiles.dispose(),this.remove(this.tiles.group),this.tiles=null),null==(t=null==(e=this.dracoLoader)?void 0:e.dispose)||t.call(e),null==(r=null==(i=this.ktx2loader)?void 0:i.dispose)||r.call(i)}}class uc extends tl{constructor(e,t={},i={}){super(),this.type="MeshLayer",this.isMeshLayer=!0;const s=(null==t?void 0:t.renderOrder)??0,n=r.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 i of t)i.transparent=!0,i.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,i=r.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(r.geodeticOffsetToEcefDelta({lon:i.longitude,lat:i.latitude,alt:i.altitude},n))}catch(l){null==(s=i.onError)||s.call(i,l instanceof Error?l:new Error(String(l)))}}),void 0,(e=>{var t;return null==(t=i.onError)?void 0:t.call(i,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 dc="#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);}",pc="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 mc=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 i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:t,msg:i,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.limit=e}postMessage(e,t){return new Promise((i=>{const r=this.getIdleWorker();-1!==r?(this.initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=i,this.workers[r].postMessage(e,t)):this.queue.push({resolve:i,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 fc(e=new Date(-864e13),t=new Date(864e13),i,r){return i&&r?i<=t&&r>e:i?i<=t:!r||r>e}mc.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 gc extends r.Object3D{constructor(e,t={},i={}){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;mc.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 r.BufferGeometry;e.setAttribute("position",new r.BufferAttribute(c,3));const t=new r.MeshBasicMaterial({color:l,side:r.DoubleSide,depthTest:!1,opacity:.75,transparent:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=dc,e.fragmentShader=pc};const i=new r.Mesh(e,t);i.layers.set(o),this.add(i)}else null==(t=i.onError)||t.call(i,new Error((null==n?void 0:n.message)??String(n)))}))}}class yc extends r.Object3D{constructor(e,t={},i={}){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;mc.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 r.BufferGeometry;e.setAttribute("position",new r.BufferAttribute(h,3)),e.setAttribute("color",new r.BufferAttribute(u,3,!0)),e.setIndex(new r.BufferAttribute(d,1));const t=new r.MeshBasicMaterial({opacity:.2,transparent:!0,side:r.DoubleSide,depthTest:!1,vertexColors:!0,toneMapped:!1});t.onBeforeCompile=e=>{e.vertexShader=dc,e.fragmentShader=pc};const i=new r.Mesh(e,t);i.layers.set(o);const s=new r.BufferGeometry;s.setAttribute("position",new r.BufferAttribute(l,3)),s.setAttribute("color",new r.BufferAttribute(c,3,!0));const n=new r.LineSegments(s,new r.LineBasicMaterial({vertexColors:!0,toneMapped:!1}));n.layers.set(o),n.add(i),this.add(n)}else null==(t=i.onError)||t.call(i,new Error((null==n?void 0:n.message)??String(n)))}))}}class vc extends tl{constructor(e,t={},i={}){var r;super(),this.type="GeojsonLayer",this.isGeojsonLayer=!0;for(let s=0;s<(null==(r=e.features)?void 0:r.length);s++){const r=e.features[s];switch(r.properties.type){case"arrow":const e=new gc(r,t,i);this.add(e);break;case"perimeter":const s=new yc(r,t,i);this.add(s)}}}setTimeFrame(e,t){e&&!e.isDate&&(e=new Date(e)),t&&!t.isDate&&(t=new Date(t));for(let i=0;i<this.children.length;i++){const r=this.children[i],s=r.timeStart,n=r.timeEnd;r.visible=fc(e,t,s,n)}}dispose(){super.dispose(),this.disposeObjectResources(),this.clear()}}const Tc=new Set(["ply","sog","spz","rad"]);function xc(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`${t} must be a non-empty string.`)}function bc(e){var t,i,s,n;if(!e||"object"!=typeof e)throw new Error("Gaussian splat layer definition must be an object.");if(xc(e.id,"id"),xc(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(xc(null==(t=e.data)?void 0:t.url,"data.url"),!Tc.has(null==(i=e.data)?void 0:i.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.");r.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 r.validateTuple(l,"translationENU"),r.validateTuple(c,"rotationDegrees"),r.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 _c(e,t){return{ply:e.SplatFileType.PLY,sog:e.SplatFileType.PCSOGSZIP,spz:e.SplatFileType.SPZ,rad:e.SplatFileType.RAD}[t]}class wc extends tl{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:i,rotationDegrees:s,scale:n}=e,a=r.getEnuBasis(t.longitude,t.latitude),o=(new r.Vector3).fromArray(a.east),l=(new r.Vector3).fromArray(a.north),c=(new r.Vector3).fromArray(a.up),h=(new r.Matrix4).makeBasis(o,l,c);h.setPosition((new r.Vector3).fromArray(r.geodeticToEcefPosition(t.longitude,t.latitude,t.altitude)));const u=(new r.Quaternion).setFromEuler(new r.Euler(s[0]*Math.PI/180,s[1]*Math.PI/180,s[2]*Math.PI/180,"XYZ")),d=(new r.Matrix4).compose((new r.Vector3).fromArray(i),u,new r.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,i,r,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==(r=(i=this.callbacks).ensureRenderer)?void 0:r.call(i)),"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:_c(e,this.definition.data.format)});return new e.SplatMesh({paged:t})}async createDirectMesh(e,t){this.abortController=new AbortController;const i=await fetch(this.definition.data.url,{signal:this.abortController.signal});if(!i.ok)throw new Error(`Failed to load Gaussian splat: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("Failed to load Gaussian splat: response body is unavailable.");const r=i.headers.get("Content-Length"),s=null===r?void 0:Number.parseInt(r,10);return new e.SplatMesh({stream:i.body,streamLength:Number.isFinite(s)&&s>=0?s:void 0,fileType:_c(e,this.definition.data.format),onProgress:e=>{var i,r;"disposed"!==this.loadState&&t===this.loadAttempt&&(null==(r=(i=this.callbacks).onProgress)||r.call(i,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 Mc(e,t,i={}){var s,n,a;const o=i.source??"all";if(!["all","splats","globe","content"].includes(o))throw new TypeError("Unknown surface pick source.");const l=i.layerIds&&new Set(i.layerIds);let c=null;const h=(e,t,i)=>{e&&(!c||e.distance<c.distance)&&(c={...e,source:t,layerId:i})},u=(e,i,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 i=e.matrixWorld.clone().invert(),s=t.ray.origin.clone().applyMatrix4(i),n=t.ray.direction.clone().applyMatrix3((new r.Matrix3).setFromMatrix4(i)),a=new r.Vector3,o=new r.Vector3,l=new r.Quaternion,c=Math.max(0,t.near);let h=t.far,u=-1;return e.forEachSplat(((t,i,r,d,p)=>{if(!Number.isFinite(p)||p<(e.minRaycastOpacity??.2))return;const m=4*Math.max(p,1)-3,f=r.x*m,g=r.y*m,y=r.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(i).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,i,r,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===r||0===s)return;if(T=-a[e]/o[e],((a[t]+T*o[t])/r)**2+((a[i]+T*o[i])/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 i=1-a.lengthSq();if(i<0)return;const r=Math.sqrt(i/e);T=t-r,T<c&&(T=t+r)}Number.isFinite(T)&&T>=c&&T<=h&&(h=T,u=t)})),u<0?null:{distance:h,point:t.ray.at(h,new r.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,i,s);for(const t of e.children)u(t,i,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 Sc=document.createElement("canvas");Sc.width=128,Sc.height=128;const Ac=Sc.getContext("2d"),Cc=Sc.width/2,Ec=Sc.height/2,Rc=Math.min(Sc.width,Sc.height)/2,Pc="0, 0, 0",Lc=Ac.createRadialGradient(Cc,Ec,0,Cc,Ec,Rc);Lc.addColorStop(0,`rgba(${Pc}, 1)`),Lc.addColorStop(.5,`rgba(${Pc}, 0.25)`),Lc.addColorStop(1,`rgba(${Pc}, 0)`),Ac.fillStyle=Lc,Ac.fillRect(0,0,Sc.width,Sc.height);const Uc={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=ns,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,qa.CESIUM=t.cesiumToken||void 0,qa.GOOGLEMAPS=t.googleMapsToken||void 0,this.state=new T({time:{type:"f",value:0},loaded:!1,added:!1,ready:!1}),this.renderer=new r.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=r.AgXToneMapping,this.renderer.outputColorSpace=r.SRGBColorSpace,this.renderer.toneMappingExposure=1,this.renderer.supportedFloatType=this.renderer.getContext().getSupportedExtensions().indexOf("OES_texture_float_linear")>=0?r.FloatType:r.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 r.Clock,this.camera=new r.PerspectiveCamera(90,1,10,1e8),this.camera.up.set(0,0,1),this.camera.position.fromArray(r.geodeticToEcefPosition(-105.18896,39.93,9e3)),this.camera.lookAt((new r.Vector3).fromArray(r.geodeticToEcefPosition(-105.18896,40,0))),this.cameraForward=new r.Vector3,this.cameraRight=new r.Vector3,this.cameraUp=new r.Vector3,this.scene=new r.Scene,this.content=new r.Group,this.scene.add(this.content),this.topLayerIndex=0,this.enabledLayers=[],this.labels=new Map,this.features=new Map,this.globeControls=new Fr(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 Jo(this.camera),this.globeManager=new Oa(this.scene,this.camera,this.renderer,{apiToken:qa.CESIUM,googleMapsToken:qa.GOOGLEMAPS}),this.globeManager.tiles&&(this.globeManager.tiles.group.visible=!this.transparentBackground,this.globeControls.setTilesRenderer(this.globeManager.tiles)),this.camera.updateMatrixWorld(!0),this.cameraCoords=Yo(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.pointerCoords={},this.pointerXYZ=new r.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 el,this.sky.scale.setScalar(2e7),this.sky.visible=!this.transparentBackground,this.scene.add(this.sky);const i=r.MathUtils.degToRad(80),s=r.MathUtils.degToRad(180),n=(new r.Vector3).setFromSphericalCoords(1,i,s);this.sky.material.uniforms.sunPosition.value=n,this.pointerRaycaster=new r.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 i=this.pointerRaycaster.intersectObject(this.globeManager.tiles.group,!0);if(i.length>0){const e=i[0];e?(this.pointerCoords=r.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 i=this.movementKeys[e][t];if(this.keysDown[i]){this.movementState[e]=!0;break}}}}getElevation(e,t,i={}){r.validateGeodeticPosition(e,t,1e4,"Elevation query");const s=(new r.Vector3).fromArray(r.geodeticToEcefPosition(e,t,1e4)),n=Qo(e,t).negate(),a=new r.Raycaster;a.ray.set(s,n);const o=this._raycastSurfaces(a,i);if(!o)throw new Error(`Elevation query found no loaded surface at ${e}, ${t}.`);const l=r.ecefToGeodeticPosition(o.point.x,o.point.y,o.point.z);return r.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[i,r]=e[t];e[t][2]=this.getElevation(i,r).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:Uc.APPENDED})}updateCameraDirections(){const e=new r.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 Qa(e,{floatType:this.renderer.supportedFloatType});t.mapping=r.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,i,r;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)?bc(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 hc(e.data.url,{camera:this.camera,renderer:this.renderer,...e.options},{onError:t=>this.dispatchEvent({type:Uc.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"mesh":{const t=new uc(e.data.url,{...e.options},{onError:t=>this.dispatchEvent({type:Uc.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 vc(e.data,e.options,{onError:t=>this.dispatchEvent({type:Uc.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"gaussian-splat":{const t=new wc(e,{ensureRenderer:()=>this.ensureSparkRenderer(),onStart:e=>this.dispatchEvent({type:Uc.CONTENT_LAYER_LOAD_START,layerId:e.contentLayerId}),onProgress:(e,t)=>this.dispatchEvent({type:Uc.CONTENT_LAYER_LOAD_PROGRESS,layerId:e.contentLayerId,progress:t}),onReady:e=>this.dispatchEvent({type:Uc.CONTENT_LAYER_READY,layerId:e.contentLayerId}),onError:(e,t)=>this.dispatchEvent({type:Uc.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:Uc.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 i=this.content.children[t];let r=!1;for(let t=0;t<e.length;t++){const s=e[t];if(i.labels.has(s)){r=!0;break}}i.setEnabled(r)}}setTimeFrame(e,t){var i;this.timeFrameStart=e?new Date(e):null,this.timeFrameEnd=t?new Date(t):null;for(let r=0;r<this.content.children.length;r++){const e=this.content.children[r];null==(i=e.setTimeFrame)||i.call(e,this.timeFrameStart,this.timeFrameEnd)}}updateLabel(e,t){var i,n;const{longitude:a,latitude:o,altitude:l}=r.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 i=t.element??document.createElement("div");d=new s(i);const n=new r.Mesh(new r.PlaneGeometry(1e3,1e3),new r.MeshBasicMaterial({map:new r.CanvasTexture(Sc),opacity:1,transparent:!0,side:r.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=(i=d.element).remove)||n.call(i),d.element=new s(t.element).element),d.position.fromArray(r.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=Yo(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.sky.setSurfaceUp(Qo(this.cameraCoords.lon,this.cameraCoords.lat)),this.keysEnabled&&function(e,t,i,r,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(i,-l),s.RIGHT&&e.addScaledVector(i,l),s.UP&&e.addScaledVector(r,l),s.DOWN&&e.addScaledVector(r,-l)}(this.camera.position,this.cameraForward,this.cameraRight,this.cameraUp,this.movementState,t,this.movementSpeed,this.boostMultiplier),this.globeManager.update();for(let i=0;i<this.content.children.length;i++){this.content.children[i].update()}for(const[i,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 r.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 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));this.cameraCoords=Yo(this.camera.position.x,this.camera.position.y,this.camera.position.z,this.camera.quaternion),this.dispatchEvent({type:Uc.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:Uc.READY})}),0))}pickCoordinates(e,t,i={}){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 r.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,i);if(!a)return null;const o=r.ecefToGeodeticPosition(a.point.x,a.point.y,a.point.z);return r.validateGeodeticPosition(o.lon,o.lat,o.alt,"Picked coordinates"),{...o,point:a.point.clone(),source:a.source,layerId:a.layerId}}_raycastSurfaces(e,t){return Mc(this,e,t)}getCameraPivot(){let e=null;const t=new r.Raycaster;if(t.setFromCamera({x:0,y:0},this.camera),this.globeManager.tiles){const i=t.intersectObject(this.globeManager.tiles.group,!0);if(i.length>0){const t=i[0];t&&(e=t.point.clone())}}return e||(e=(new r.Vector3).subVectors(this.camera.position,this.cameraForward.clone().multiplyScalar(2e3))),e}async alignCamera(e,t,i,s,n,a,o){const l=r.validateGeodeticPosition(e,t,i,"Camera position"),c=r.validateRotation(s??this.cameraCoords.pitch,n??this.cameraCoords.yaw,a??this.cameraCoords.roll,"Camera rotation"),h=r.requireFiniteNumber(o??Xa,"Camera transition duration"),u=(new r.Vector3).fromArray(r.geodeticToEcefPosition(l.longitude,l.latitude,l.altitude)),d=$o(l.longitude,l.latitude,c.pitch,c.yaw,c.roll);return this.transitionControls.animateTo(u,d,h).then((r=>{r&&this.dispatchEvent({type:Uc.TRANSITIONED,lon:e,lat:t,alt:i,...c})}))}async focusCamera(e,t,i,s,n,a){const o=r.validateGeodeticPosition(e,t,i,"Camera focus"),l=r.requireFiniteNumber(s??2e3,"Camera focus distance"),c=r.validateRotation(n??this.cameraCoords.pitch,0,0,"Camera rotation"),h=r.requireFiniteNumber(a??Xa,"Camera transition duration"),u=(new r.Vector3).fromArray(r.geodeticToEcefPosition(o.longitude,o.latitude,o.altitude)),d=$o(o.longitude,o.latitude,c.pitch,c.yaw,c.roll),p=new r.Vector3(0,0,1).applyQuaternion(d);return u.addScaledVector(p,l),this.transitionControls.animateTo(u,d,h).then((r=>{r&&this.dispatchEvent({type:Uc.TRANSITIONED,lon:e,lat:t,alt:i})}))}async angleCamera(e,t,i){const s=r.validateRotation(e??this.cameraCoords.pitch,t??this.cameraCoords.yaw,0,"Camera rotation"),n=r.requireFiniteNumber(i??Xa,"Camera transition duration"),a=this.getCameraPivot(),{lon:o,lat:l,alt:c}=r.ecefToGeodeticPosition(a.x,a.y,a.z),h=this.camera.position.distanceTo(a),u=(new r.Vector3).fromArray(r.geodeticToEcefPosition(o,l,c)),d=$o(o,l,s.pitch,s.yaw,s.roll),p=new r.Vector3(0,0,1).applyQuaternion(d);return u.addScaledVector(p,h),this.transitionControls.animateTo(u,d,n).then((e=>{e&&this.dispatchEvent({type:Uc.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 to).parse(e,(e=>{const t=new Blob([e],{type:"application/octet-stream"}),i=URL.createObjectURL(t),r=document.createElement("a");r.href=i,r.download="scene.glb",document.body.appendChild(r),r.click(),document.body.removeChild(r)}),(e=>{}),{binary:!0});var e}saveScreenshot(e="screenshot"){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));const t=this.renderer.domElement.toDataURL(),i=document.createElement("a");i.setAttribute("href",t),i.setAttribute("target","_blank"),i.setAttribute("download",`${e}.png`),i.click()}dispose(){var e,t,i,r,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();for(const e of this.labels.values())e.traverse((e=>{var t,i,r,s,n;if(null==(i=null==(t=e.geometry)?void 0:t.dispose)||i.call(t),e.material){const t=Array.isArray(e.material)?e.material:[e.material];for(const e of t)null==(s=null==(r=e.map)?void 0:r.dispose)||s.call(r),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==(r=null==(i=this.sky)?void 0:i.geometry)?void 0:r.dispose)||s.call(r),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=Uc;
|