@terra.gl/core 0.0.1-alpha.6

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.
@@ -0,0 +1,702 @@
1
+ (function(N,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],h):(N=typeof globalThis<"u"?globalThis:N||self,h(N["terra-gl"]={},N.THREE))})(this,function(N,h){"use strict";var $o=Object.defineProperty;var ea=(N,h,Oe)=>h in N?$o(N,h,{enumerable:!0,configurable:!0,writable:!0,value:Oe}):N[h]=Oe;var x=(N,h,Oe)=>ea(N,typeof h!="symbol"?h+"":h,Oe);function Oe(o){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const e in o)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>o[e]})}}return t.default=o,Object.freeze(t)}const se=Oe(h),Zi="0.0.1-alpha.6",$t={name:"criska"};var Be=function(){var o=0,t=document.createElement("div");t.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",t.addEventListener("click",function(d){d.preventDefault(),n(++o%t.children.length)},!1);function e(d){return t.appendChild(d.dom),d}function n(d){for(var c=0;c<t.children.length;c++)t.children[c].style.display=c===d?"block":"none";o=d}var i=(performance||Date).now(),r=i,s=0,a=e(new Be.Panel("FPS","#0ff","#002")),l=e(new Be.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var u=e(new Be.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:t,addPanel:e,showPanel:n,begin:function(){i=(performance||Date).now()},end:function(){s++;var d=(performance||Date).now();if(l.update(d-i,200),d>=r+1e3&&(a.update(s*1e3/(d-r),100),r=d,s=0,u)){var c=performance.memory;u.update(c.usedJSHeapSize/1048576,c.jsHeapSizeLimit/1048576)}return d},update:function(){i=this.end()},domElement:t,setMode:n}};Be.Panel=function(o,t,e){var n=1/0,i=0,r=Math.round,s=r(window.devicePixelRatio||1),a=80*s,l=48*s,u=3*s,d=2*s,c=3*s,p=15*s,f=74*s,m=30*s,v=document.createElement("canvas");v.width=a,v.height=l,v.style.cssText="width:80px;height:48px";var g=v.getContext("2d");return g.font="bold "+9*s+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=e,g.fillRect(0,0,a,l),g.fillStyle=t,g.fillText(o,u,d),g.fillRect(c,p,f,m),g.fillStyle=e,g.globalAlpha=.9,g.fillRect(c,p,f,m),{dom:v,update:function(b,y){n=Math.min(n,b),i=Math.max(i,b),g.fillStyle=e,g.globalAlpha=1,g.fillRect(0,0,a,p),g.fillStyle=t,g.fillText(r(b)+" "+o+" ("+r(n)+"-"+r(i)+")",u,d),g.drawImage(v,c+s,p,f-s,m,c,p,f-s,m),g.fillRect(c+f-s,p,s,m),g.fillStyle=e,g.globalAlpha=.9,g.fillRect(c+f-s,p,s,r((1-b/y)*m))}}};const ot=parseInt(h.REVISION.replace(/\D+/g,"")),Lt=ot>=125?"uv1":"uv2";function en(o,t){if(t===h.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),o;if(t===h.TriangleFanDrawMode||t===h.TriangleStripDrawMode){let e=o.getIndex();if(e===null){const s=[],a=o.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)s.push(l);o.setIndex(s),e=o.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),o}const n=e.count-2,i=[];if(e)if(t===h.TriangleFanDrawMode)for(let s=1;s<=n;s++)i.push(e.getX(0)),i.push(e.getX(s)),i.push(e.getX(s+1));else for(let s=0;s<n;s++)s%2===0?(i.push(e.getX(s)),i.push(e.getX(s+1)),i.push(e.getX(s+2))):(i.push(e.getX(s+2)),i.push(e.getX(s+1)),i.push(e.getX(s)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=o.clone();return r.setIndex(i),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),o}var oe=Uint8Array,Te=Uint16Array,St=Uint32Array,tn=new oe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),nn=new oe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ii=new oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),rn=function(o,t){for(var e=new Te(31),n=0;n<31;++n)e[n]=t+=1<<o[n-1];for(var i=new St(e[30]),n=1;n<30;++n)for(var r=e[n];r<e[n+1];++r)i[r]=r-e[n]<<5|n;return[e,i]},sn=rn(tn,2),on=sn[0],Ti=sn[1];on[28]=258,Ti[258]=28;for(var Pi=rn(nn,0),Ai=Pi[0],Mt=new Te(32768),Q=0;Q<32768;++Q){var Pe=(Q&43690)>>>1|(Q&21845)<<1;Pe=(Pe&52428)>>>2|(Pe&13107)<<2,Pe=(Pe&61680)>>>4|(Pe&3855)<<4,Mt[Q]=((Pe&65280)>>>8|(Pe&255)<<8)>>>1}for(var Ne=function(o,t,e){for(var n=o.length,i=0,r=new Te(t);i<n;++i)++r[o[i]-1];var s=new Te(t);for(i=0;i<t;++i)s[i]=s[i-1]+r[i-1]<<1;var a;if(e){a=new Te(1<<t);var l=15-t;for(i=0;i<n;++i)if(o[i])for(var u=i<<4|o[i],d=t-o[i],c=s[o[i]-1]++<<d,p=c|(1<<d)-1;c<=p;++c)a[Mt[c]>>>l]=u}else for(a=new Te(n),i=0;i<n;++i)o[i]&&(a[i]=Mt[s[o[i]-1]++]>>>15-o[i]);return a},je=new oe(288),Q=0;Q<144;++Q)je[Q]=8;for(var Q=144;Q<256;++Q)je[Q]=9;for(var Q=256;Q<280;++Q)je[Q]=7;for(var Q=280;Q<288;++Q)je[Q]=8;for(var an=new oe(32),Q=0;Q<32;++Q)an[Q]=5;var Wi=Ne(je,9,1),Gi=Ne(an,5,1),_t=function(o){for(var t=o[0],e=1;e<o.length;++e)o[e]>t&&(t=o[e]);return t},ue=function(o,t,e){var n=t/8|0;return(o[n]|o[n+1]<<8)>>(t&7)&e},Zt=function(o,t){var e=t/8|0;return(o[e]|o[e+1]<<8|o[e+2]<<16)>>(t&7)},Vi=function(o){return(o/8|0)+(o&7&&1)},Ci=function(o,t,e){(e==null||e>o.length)&&(e=o.length);var n=new(o instanceof Te?Te:o instanceof St?St:oe)(e-t);return n.set(o.subarray(t,e)),n},ki=function(o,t,e){var n=o.length;if(!n||e&&!e.l&&n<5)return t||new oe(0);var i=!t||e,r=!e||e.i;e||(e={}),t||(t=new oe(n*3));var s=function(Le){var pe=t.length;if(Le>pe){var Se=new oe(Math.max(pe*2,Le));Se.set(t),t=Se}},a=e.f||0,l=e.p||0,u=e.b||0,d=e.l,c=e.d,p=e.m,f=e.n,m=n*8;do{if(!d){e.f=a=ue(o,l,1);var v=ue(o,l+1,3);if(l+=3,v)if(v==1)d=Wi,c=Gi,p=9,f=5;else if(v==2){var w=ue(o,l,31)+257,S=ue(o,l+10,15)+4,P=w+ue(o,l+5,31)+1;l+=14;for(var I=new oe(P),T=new oe(19),M=0;M<S;++M)T[Ii[M]]=ue(o,l+M*3,7);l+=S*3;for(var A=_t(T),L=(1<<A)-1,Z=Ne(T,A,1),M=0;M<P;){var W=Z[ue(o,l,L)];l+=W&15;var g=W>>>4;if(g<16)I[M++]=g;else{var C=0,V=0;for(g==16?(V=3+ue(o,l,3),l+=2,C=I[M-1]):g==17?(V=3+ue(o,l,7),l+=3):g==18&&(V=11+ue(o,l,127),l+=7);V--;)I[M++]=C}}var D=I.subarray(0,w),G=I.subarray(w);p=_t(D),f=_t(G),d=Ne(D,p,1),c=Ne(G,f,1)}else throw"invalid block type";else{var g=Vi(l)+4,b=o[g-4]|o[g-3]<<8,y=g+b;if(y>n){if(r)throw"unexpected EOF";break}i&&s(u+b),t.set(o.subarray(g,y),u),e.b=u+=b,e.p=l=y*8;continue}if(l>m){if(r)throw"unexpected EOF";break}}i&&s(u+131072);for(var X=(1<<p)-1,U=(1<<f)-1,z=l;;z=l){var C=d[Zt(o,l)&X],j=C>>>4;if(l+=C&15,l>m){if(r)throw"unexpected EOF";break}if(!C)throw"invalid length/literal";if(j<256)t[u++]=j;else if(j==256){z=l,d=null;break}else{var H=j-254;if(j>264){var M=j-257,B=tn[M];H=ue(o,l,(1<<B)-1)+on[M],l+=B}var J=c[Zt(o,l)&U],de=J>>>4;if(!J)throw"invalid distance";l+=J&15;var G=Ai[de];if(de>3){var B=nn[de];G+=Zt(o,l)&(1<<B)-1,l+=B}if(l>m){if(r)throw"unexpected EOF";break}i&&s(u+131072);for(var Ke=u+H;u<Ke;u+=4)t[u]=t[u-G],t[u+1]=t[u+1-G],t[u+2]=t[u+2-G],t[u+3]=t[u+3-G];u=Ke}}e.l=d,e.p=z,e.b=u,d&&(a=1,e.m=p,e.d=c,e.n=f)}while(!a);return u==t.length?t:Ci(t,0,u)},Di=new oe(0),Fi=function(o){if((o[0]&15)!=8||o[0]>>>4>7||(o[0]<<8|o[1])%31)throw"invalid zlib data";if(o[1]&32)throw"invalid zlib data: preset dictionaries not supported"};function Oi(o,t){return ki((Fi(o),o.subarray(2,-4)),t)}var zi=typeof TextDecoder<"u"&&new TextDecoder,Xi=0;try{zi.decode(Di,{stream:!0}),Xi=1}catch{}class Ui extends h.Mesh{constructor(t,e={}){super(t),this.isWater=!0;const n=this,i=e.textureWidth!==void 0?e.textureWidth:512,r=e.textureHeight!==void 0?e.textureHeight:512,s=e.clipBias!==void 0?e.clipBias:0,a=e.alpha!==void 0?e.alpha:1,l=e.time!==void 0?e.time:0,u=e.waterNormals!==void 0?e.waterNormals:null,d=e.sunDirection!==void 0?e.sunDirection:new h.Vector3(.70707,.70707,0),c=new h.Color(e.sunColor!==void 0?e.sunColor:16777215),p=new h.Color(e.waterColor!==void 0?e.waterColor:8355711),f=e.eye!==void 0?e.eye:new h.Vector3(0,0,0),m=e.distortionScale!==void 0?e.distortionScale:20,v=e.side!==void 0?e.side:h.FrontSide,g=e.fog!==void 0?e.fog:!1,b=new h.Plane,y=new h.Vector3,w=new h.Vector3,S=new h.Vector3,P=new h.Matrix4,I=new h.Vector3(0,0,-1),T=new h.Vector4,M=new h.Vector3,A=new h.Vector3,L=new h.Vector4,Z=new h.Matrix4,W=new h.PerspectiveCamera,C=new h.WebGLRenderTarget(i,r),V={uniforms:h.UniformsUtils.merge([h.UniformsLib.fog,h.UniformsLib.lights,{normalSampler:{value:null},mirrorSampler:{value:null},alpha:{value:1},time:{value:0},size:{value:1},distortionScale:{value:20},textureMatrix:{value:new h.Matrix4},sunColor:{value:new h.Color(8355711)},sunDirection:{value:new h.Vector3(.70707,.70707,0)},eye:{value:new h.Vector3},waterColor:{value:new h.Color(5592405)}}]),vertexShader:`
2
+ uniform mat4 textureMatrix;
3
+ uniform float time;
4
+
5
+ varying vec4 mirrorCoord;
6
+ varying vec4 worldPosition;
7
+
8
+ #include <common>
9
+ #include <fog_pars_vertex>
10
+ #include <shadowmap_pars_vertex>
11
+ #include <logdepthbuf_pars_vertex>
12
+
13
+ void main() {
14
+ mirrorCoord = modelMatrix * vec4( position, 1.0 );
15
+ worldPosition = mirrorCoord.xyzw;
16
+ mirrorCoord = textureMatrix * mirrorCoord;
17
+ vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
18
+ gl_Position = projectionMatrix * mvPosition;
19
+
20
+ #include <beginnormal_vertex>
21
+ #include <defaultnormal_vertex>
22
+ #include <logdepthbuf_vertex>
23
+ #include <fog_vertex>
24
+ #include <shadowmap_vertex>
25
+ }`,fragmentShader:`
26
+ uniform sampler2D mirrorSampler;
27
+ uniform float alpha;
28
+ uniform float time;
29
+ uniform float size;
30
+ uniform float distortionScale;
31
+ uniform sampler2D normalSampler;
32
+ uniform vec3 sunColor;
33
+ uniform vec3 sunDirection;
34
+ uniform vec3 eye;
35
+ uniform vec3 waterColor;
36
+
37
+ varying vec4 mirrorCoord;
38
+ varying vec4 worldPosition;
39
+
40
+ vec4 getNoise( vec2 uv ) {
41
+ vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);
42
+ vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );
43
+ vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );
44
+ vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );
45
+ vec4 noise = texture2D( normalSampler, uv0 ) +
46
+ texture2D( normalSampler, uv1 ) +
47
+ texture2D( normalSampler, uv2 ) +
48
+ texture2D( normalSampler, uv3 );
49
+ return noise * 0.5 - 1.0;
50
+ }
51
+
52
+ void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) {
53
+ vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );
54
+ float direction = max( 0.0, dot( eyeDirection, reflection ) );
55
+ specularColor += pow( direction, shiny ) * sunColor * spec;
56
+ diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;
57
+ }
58
+
59
+ #include <common>
60
+ #include <packing>
61
+ #include <bsdfs>
62
+ #include <fog_pars_fragment>
63
+ #include <logdepthbuf_pars_fragment>
64
+ #include <lights_pars_begin>
65
+ #include <shadowmap_pars_fragment>
66
+ #include <shadowmask_pars_fragment>
67
+
68
+ void main() {
69
+
70
+ #include <logdepthbuf_fragment>
71
+ vec4 noise = getNoise( worldPosition.xz * size );
72
+ vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );
73
+
74
+ vec3 diffuseLight = vec3(0.0);
75
+ vec3 specularLight = vec3(0.0);
76
+
77
+ vec3 worldToEye = eye-worldPosition.xyz;
78
+ vec3 eyeDirection = normalize( worldToEye );
79
+ sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );
80
+
81
+ float distance = length(worldToEye);
82
+
83
+ vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;
84
+ vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) );
85
+
86
+ float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );
87
+ float rf0 = 0.3;
88
+ float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );
89
+ vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;
90
+ vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance);
91
+ vec3 outgoingLight = albedo;
92
+ gl_FragColor = vec4( outgoingLight, alpha );
93
+
94
+ #include <tonemapping_fragment>
95
+ #include <${ot>=154?"colorspace_fragment":"encodings_fragment"}>
96
+ #include <fog_fragment>
97
+ }`},D=new h.ShaderMaterial({fragmentShader:V.fragmentShader,vertexShader:V.vertexShader,uniforms:h.UniformsUtils.clone(V.uniforms),lights:!0,side:v,fog:g});D.uniforms.mirrorSampler.value=C.texture,D.uniforms.textureMatrix.value=Z,D.uniforms.alpha.value=a,D.uniforms.time.value=l,D.uniforms.normalSampler.value=u,D.uniforms.sunColor.value=c,D.uniforms.waterColor.value=p,D.uniforms.sunDirection.value=d,D.uniforms.distortionScale.value=m,D.uniforms.eye.value=f,n.material=D,n.onBeforeRender=function(G,X,U){if(w.setFromMatrixPosition(n.matrixWorld),S.setFromMatrixPosition(U.matrixWorld),P.extractRotation(n.matrixWorld),y.set(0,0,1),y.applyMatrix4(P),M.subVectors(w,S),M.dot(y)>0)return;M.reflect(y).negate(),M.add(w),P.extractRotation(U.matrixWorld),I.set(0,0,-1),I.applyMatrix4(P),I.add(S),A.subVectors(w,I),A.reflect(y).negate(),A.add(w),W.position.copy(M),W.up.set(0,1,0),W.up.applyMatrix4(P),W.up.reflect(y),W.lookAt(A),W.far=U.far,W.updateMatrixWorld(),W.projectionMatrix.copy(U.projectionMatrix),Z.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),Z.multiply(W.projectionMatrix),Z.multiply(W.matrixWorldInverse),b.setFromNormalAndCoplanarPoint(y,w),b.applyMatrix4(W.matrixWorldInverse),T.set(b.normal.x,b.normal.y,b.normal.z,b.constant);const z=W.projectionMatrix;L.x=(Math.sign(T.x)+z.elements[8])/z.elements[0],L.y=(Math.sign(T.y)+z.elements[9])/z.elements[5],L.z=-1,L.w=(1+z.elements[10])/z.elements[14],T.multiplyScalar(2/T.dot(L)),z.elements[2]=T.x,z.elements[6]=T.y,z.elements[10]=T.z+1-s,z.elements[14]=T.w,f.setFromMatrixPosition(U.matrixWorld);const j=G.getRenderTarget(),H=G.xr.enabled,B=G.shadowMap.autoUpdate;n.visible=!1,G.xr.enabled=!1,G.shadowMap.autoUpdate=!1,G.setRenderTarget(C),G.state.buffers.depth.setMask(!0),G.autoClear===!1&&G.clear(),G.render(X,W),n.visible=!0,G.xr.enabled=H,G.shadowMap.autoUpdate=B,G.setRenderTarget(j);const J=U.viewport;J!==void 0&&G.state.viewport(J)}}}var Yi=Object.defineProperty,Ki=(o,t,e)=>t in o?Yi(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,Bi=(o,t,e)=>(Ki(o,t+"",e),e);class Ni{constructor(){Bi(this,"_listeners")}addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){if(this._listeners===void 0)return!1;const n=this._listeners;return n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){if(this._listeners===void 0)return;const i=this._listeners[t];if(i!==void 0){const r=i.indexOf(e);r!==-1&&i.splice(r,1)}}dispatchEvent(t){if(this._listeners===void 0)return;const n=this._listeners[t.type];if(n!==void 0){t.target=this;const i=n.slice(0);for(let r=0,s=i.length;r<s;r++)i[r].call(this,t);t.target=null}}}var ji=Object.defineProperty,Ri=(o,t,e)=>t in o?ji(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,F=(o,t,e)=>(Ri(o,typeof t!="symbol"?t+"":t,e),e);const at=new h.Ray,ln=new h.Plane,Ji=Math.cos(70*(Math.PI/180)),cn=(o,t)=>(o%t+t)%t;class Qi extends Ni{constructor(t,e){super(),F(this,"object"),F(this,"domElement"),F(this,"enabled",!0),F(this,"target",new h.Vector3),F(this,"minDistance",0),F(this,"maxDistance",1/0),F(this,"minZoom",0),F(this,"maxZoom",1/0),F(this,"minPolarAngle",0),F(this,"maxPolarAngle",Math.PI),F(this,"minAzimuthAngle",-1/0),F(this,"maxAzimuthAngle",1/0),F(this,"enableDamping",!1),F(this,"dampingFactor",.05),F(this,"enableZoom",!0),F(this,"zoomSpeed",1),F(this,"enableRotate",!0),F(this,"rotateSpeed",1),F(this,"enablePan",!0),F(this,"panSpeed",1),F(this,"screenSpacePanning",!0),F(this,"keyPanSpeed",7),F(this,"zoomToCursor",!1),F(this,"autoRotate",!1),F(this,"autoRotateSpeed",2),F(this,"reverseOrbit",!1),F(this,"reverseHorizontalOrbit",!1),F(this,"reverseVerticalOrbit",!1),F(this,"keys",{LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"}),F(this,"mouseButtons",{LEFT:h.MOUSE.ROTATE,MIDDLE:h.MOUSE.DOLLY,RIGHT:h.MOUSE.PAN}),F(this,"touches",{ONE:h.TOUCH.ROTATE,TWO:h.TOUCH.DOLLY_PAN}),F(this,"target0"),F(this,"position0"),F(this,"zoom0"),F(this,"_domElementKeyEvents",null),F(this,"getPolarAngle"),F(this,"getAzimuthalAngle"),F(this,"setPolarAngle"),F(this,"setAzimuthalAngle"),F(this,"getDistance"),F(this,"getZoomScale"),F(this,"listenToKeyEvents"),F(this,"stopListenToKeyEvents"),F(this,"saveState"),F(this,"reset"),F(this,"update"),F(this,"connect"),F(this,"dispose"),F(this,"dollyIn"),F(this,"dollyOut"),F(this,"getScale"),F(this,"setScale"),this.object=t,this.domElement=e,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.getPolarAngle=()=>d.phi,this.getAzimuthalAngle=()=>d.theta,this.setPolarAngle=_=>{let k=cn(_,2*Math.PI),O=d.phi;O<0&&(O+=2*Math.PI),k<0&&(k+=2*Math.PI);let R=Math.abs(k-O);2*Math.PI-R<R&&(k<O?k+=2*Math.PI:O+=2*Math.PI),c.phi=k-O,n.update()},this.setAzimuthalAngle=_=>{let k=cn(_,2*Math.PI),O=d.theta;O<0&&(O+=2*Math.PI),k<0&&(k+=2*Math.PI);let R=Math.abs(k-O);2*Math.PI-R<R&&(k<O?k+=2*Math.PI:O+=2*Math.PI),c.theta=k-O,n.update()},this.getDistance=()=>n.object.position.distanceTo(n.target),this.listenToKeyEvents=_=>{_.addEventListener("keydown",Et),this._domElementKeyEvents=_},this.stopListenToKeyEvents=()=>{this._domElementKeyEvents.removeEventListener("keydown",Et),this._domElementKeyEvents=null},this.saveState=()=>{n.target0.copy(n.target),n.position0.copy(n.object.position),n.zoom0=n.object.zoom},this.reset=()=>{n.target.copy(n.target0),n.object.position.copy(n.position0),n.object.zoom=n.zoom0,n.object.updateProjectionMatrix(),n.dispatchEvent(i),n.update(),l=a.NONE},this.update=(()=>{const _=new h.Vector3,k=new h.Vector3(0,1,0),O=new h.Quaternion().setFromUnitVectors(t.up,k),R=O.clone().invert(),q=new h.Vector3,_e=new h.Quaternion,Ve=2*Math.PI;return function(){const Mi=n.object.position;O.setFromUnitVectors(t.up,k),R.copy(O).invert(),_.copy(Mi).sub(n.target),_.applyQuaternion(O),d.setFromVector3(_),n.autoRotate&&l===a.NONE&&V(W()),n.enableDamping?(d.theta+=c.theta*n.dampingFactor,d.phi+=c.phi*n.dampingFactor):(d.theta+=c.theta,d.phi+=c.phi);let Ze=n.minAzimuthAngle,Ie=n.maxAzimuthAngle;isFinite(Ze)&&isFinite(Ie)&&(Ze<-Math.PI?Ze+=Ve:Ze>Math.PI&&(Ze-=Ve),Ie<-Math.PI?Ie+=Ve:Ie>Math.PI&&(Ie-=Ve),Ze<=Ie?d.theta=Math.max(Ze,Math.min(Ie,d.theta)):d.theta=d.theta>(Ze+Ie)/2?Math.max(Ze,d.theta):Math.min(Ie,d.theta)),d.phi=Math.max(n.minPolarAngle,Math.min(n.maxPolarAngle,d.phi)),d.makeSafe(),n.enableDamping===!0?n.target.addScaledVector(f,n.dampingFactor):n.target.add(f),n.zoomToCursor&&A||n.object.isOrthographicCamera?d.radius=J(d.radius):d.radius=J(d.radius*p),_.setFromSpherical(d),_.applyQuaternion(R),Mi.copy(n.target).add(_),n.object.matrixAutoUpdate||n.object.updateMatrix(),n.object.lookAt(n.target),n.enableDamping===!0?(c.theta*=1-n.dampingFactor,c.phi*=1-n.dampingFactor,f.multiplyScalar(1-n.dampingFactor)):(c.set(0,0,0),f.set(0,0,0));let it=!1;if(n.zoomToCursor&&A){let rt=null;if(n.object instanceof h.PerspectiveCamera&&n.object.isPerspectiveCamera){const st=_.length();rt=J(st*p);const xt=st-rt;n.object.position.addScaledVector(T,xt),n.object.updateMatrixWorld()}else if(n.object.isOrthographicCamera){const st=new h.Vector3(M.x,M.y,0);st.unproject(n.object),n.object.zoom=Math.max(n.minZoom,Math.min(n.maxZoom,n.object.zoom/p)),n.object.updateProjectionMatrix(),it=!0;const xt=new h.Vector3(M.x,M.y,0);xt.unproject(n.object),n.object.position.sub(xt).add(st),n.object.updateMatrixWorld(),rt=_.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),n.zoomToCursor=!1;rt!==null&&(n.screenSpacePanning?n.target.set(0,0,-1).transformDirection(n.object.matrix).multiplyScalar(rt).add(n.object.position):(at.origin.copy(n.object.position),at.direction.set(0,0,-1).transformDirection(n.object.matrix),Math.abs(n.object.up.dot(at.direction))<Ji?t.lookAt(n.target):(ln.setFromNormalAndCoplanarPoint(n.object.up,n.target),at.intersectPlane(ln,n.target))))}else n.object instanceof h.OrthographicCamera&&n.object.isOrthographicCamera&&(it=p!==1,it&&(n.object.zoom=Math.max(n.minZoom,Math.min(n.maxZoom,n.object.zoom/p)),n.object.updateProjectionMatrix()));return p=1,A=!1,it||q.distanceToSquared(n.object.position)>u||8*(1-_e.dot(n.object.quaternion))>u?(n.dispatchEvent(i),q.copy(n.object.position),_e.copy(n.object.quaternion),it=!1,!0):!1}})(),this.connect=_=>{n.domElement=_,n.domElement.style.touchAction="none",n.domElement.addEventListener("contextmenu",Li),n.domElement.addEventListener("pointerdown",wi),n.domElement.addEventListener("pointercancel",nt),n.domElement.addEventListener("wheel",xi)},this.dispose=()=>{var _,k,O,R,q,_e;n.domElement&&(n.domElement.style.touchAction="auto"),(_=n.domElement)==null||_.removeEventListener("contextmenu",Li),(k=n.domElement)==null||k.removeEventListener("pointerdown",wi),(O=n.domElement)==null||O.removeEventListener("pointercancel",nt),(R=n.domElement)==null||R.removeEventListener("wheel",xi),(q=n.domElement)==null||q.ownerDocument.removeEventListener("pointermove",Ht),(_e=n.domElement)==null||_e.ownerDocument.removeEventListener("pointerup",nt),n._domElementKeyEvents!==null&&n._domElementKeyEvents.removeEventListener("keydown",Et)};const n=this,i={type:"change"},r={type:"start"},s={type:"end"},a={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let l=a.NONE;const u=1e-6,d=new h.Spherical,c=new h.Spherical;let p=1;const f=new h.Vector3,m=new h.Vector2,v=new h.Vector2,g=new h.Vector2,b=new h.Vector2,y=new h.Vector2,w=new h.Vector2,S=new h.Vector2,P=new h.Vector2,I=new h.Vector2,T=new h.Vector3,M=new h.Vector2;let A=!1;const L=[],Z={};function W(){return 2*Math.PI/60/60*n.autoRotateSpeed}function C(){return Math.pow(.95,n.zoomSpeed)}function V(_){n.reverseOrbit||n.reverseHorizontalOrbit?c.theta+=_:c.theta-=_}function D(_){n.reverseOrbit||n.reverseVerticalOrbit?c.phi+=_:c.phi-=_}const G=(()=>{const _=new h.Vector3;return function(O,R){_.setFromMatrixColumn(R,0),_.multiplyScalar(-O),f.add(_)}})(),X=(()=>{const _=new h.Vector3;return function(O,R){n.screenSpacePanning===!0?_.setFromMatrixColumn(R,1):(_.setFromMatrixColumn(R,0),_.crossVectors(n.object.up,_)),_.multiplyScalar(O),f.add(_)}})(),U=(()=>{const _=new h.Vector3;return function(O,R){const q=n.domElement;if(q&&n.object instanceof h.PerspectiveCamera&&n.object.isPerspectiveCamera){const _e=n.object.position;_.copy(_e).sub(n.target);let Ve=_.length();Ve*=Math.tan(n.object.fov/2*Math.PI/180),G(2*O*Ve/q.clientHeight,n.object.matrix),X(2*R*Ve/q.clientHeight,n.object.matrix)}else q&&n.object instanceof h.OrthographicCamera&&n.object.isOrthographicCamera?(G(O*(n.object.right-n.object.left)/n.object.zoom/q.clientWidth,n.object.matrix),X(R*(n.object.top-n.object.bottom)/n.object.zoom/q.clientHeight,n.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),n.enablePan=!1)}})();function z(_){n.object instanceof h.PerspectiveCamera&&n.object.isPerspectiveCamera||n.object instanceof h.OrthographicCamera&&n.object.isOrthographicCamera?p=_:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),n.enableZoom=!1)}function j(_){z(p/_)}function H(_){z(p*_)}function B(_){if(!n.zoomToCursor||!n.domElement)return;A=!0;const k=n.domElement.getBoundingClientRect(),O=_.clientX-k.left,R=_.clientY-k.top,q=k.width,_e=k.height;M.x=O/q*2-1,M.y=-(R/_e)*2+1,T.set(M.x,M.y,1).unproject(n.object).sub(n.object.position).normalize()}function J(_){return Math.max(n.minDistance,Math.min(n.maxDistance,_))}function de(_){m.set(_.clientX,_.clientY)}function Ke(_){B(_),S.set(_.clientX,_.clientY)}function Le(_){b.set(_.clientX,_.clientY)}function pe(_){v.set(_.clientX,_.clientY),g.subVectors(v,m).multiplyScalar(n.rotateSpeed);const k=n.domElement;k&&(V(2*Math.PI*g.x/k.clientHeight),D(2*Math.PI*g.y/k.clientHeight)),m.copy(v),n.update()}function Se(_){P.set(_.clientX,_.clientY),I.subVectors(P,S),I.y>0?j(C()):I.y<0&&H(C()),S.copy(P),n.update()}function Me(_){y.set(_.clientX,_.clientY),w.subVectors(y,b).multiplyScalar(n.panSpeed),U(w.x,w.y),b.copy(y),n.update()}function ce(_){B(_),_.deltaY<0?H(C()):_.deltaY>0&&j(C()),n.update()}function re(_){let k=!1;switch(_.code){case n.keys.UP:U(0,n.keyPanSpeed),k=!0;break;case n.keys.BOTTOM:U(0,-n.keyPanSpeed),k=!0;break;case n.keys.LEFT:U(n.keyPanSpeed,0),k=!0;break;case n.keys.RIGHT:U(-n.keyPanSpeed,0),k=!0;break}k&&(_.preventDefault(),n.update())}function wt(){if(L.length==1)m.set(L[0].pageX,L[0].pageY);else{const _=.5*(L[0].pageX+L[1].pageX),k=.5*(L[0].pageY+L[1].pageY);m.set(_,k)}}function et(){if(L.length==1)b.set(L[0].pageX,L[0].pageY);else{const _=.5*(L[0].pageX+L[1].pageX),k=.5*(L[0].pageY+L[1].pageY);b.set(_,k)}}function fe(){const _=L[0].pageX-L[1].pageX,k=L[0].pageY-L[1].pageY,O=Math.sqrt(_*_+k*k);S.set(0,O)}function tt(){n.enableZoom&&fe(),n.enablePan&&et()}function ve(){n.enableZoom&&fe(),n.enableRotate&&wt()}function gi(_){if(L.length==1)v.set(_.pageX,_.pageY);else{const O=qt(_),R=.5*(_.pageX+O.x),q=.5*(_.pageY+O.y);v.set(R,q)}g.subVectors(v,m).multiplyScalar(n.rotateSpeed);const k=n.domElement;k&&(V(2*Math.PI*g.x/k.clientHeight),D(2*Math.PI*g.y/k.clientHeight)),m.copy(v)}function bi(_){if(L.length==1)y.set(_.pageX,_.pageY);else{const k=qt(_),O=.5*(_.pageX+k.x),R=.5*(_.pageY+k.y);y.set(O,R)}w.subVectors(y,b).multiplyScalar(n.panSpeed),U(w.x,w.y),b.copy(y)}function vi(_){const k=qt(_),O=_.pageX-k.x,R=_.pageY-k.y,q=Math.sqrt(O*O+R*R);P.set(0,q),I.set(0,Math.pow(P.y/S.y,n.zoomSpeed)),j(I.y),S.copy(P)}function No(_){n.enableZoom&&vi(_),n.enablePan&&bi(_)}function jo(_){n.enableZoom&&vi(_),n.enableRotate&&gi(_)}function wi(_){var k,O;n.enabled!==!1&&(L.length===0&&((k=n.domElement)==null||k.ownerDocument.addEventListener("pointermove",Ht),(O=n.domElement)==null||O.ownerDocument.addEventListener("pointerup",nt)),Eo(_),_.pointerType==="touch"?Qo(_):Ro(_))}function Ht(_){n.enabled!==!1&&(_.pointerType==="touch"?Ho(_):Jo(_))}function nt(_){var k,O,R;qo(_),L.length===0&&((k=n.domElement)==null||k.releasePointerCapture(_.pointerId),(O=n.domElement)==null||O.ownerDocument.removeEventListener("pointermove",Ht),(R=n.domElement)==null||R.ownerDocument.removeEventListener("pointerup",nt)),n.dispatchEvent(s),l=a.NONE}function Ro(_){let k;switch(_.button){case 0:k=n.mouseButtons.LEFT;break;case 1:k=n.mouseButtons.MIDDLE;break;case 2:k=n.mouseButtons.RIGHT;break;default:k=-1}switch(k){case h.MOUSE.DOLLY:if(n.enableZoom===!1)return;Ke(_),l=a.DOLLY;break;case h.MOUSE.ROTATE:if(_.ctrlKey||_.metaKey||_.shiftKey){if(n.enablePan===!1)return;Le(_),l=a.PAN}else{if(n.enableRotate===!1)return;de(_),l=a.ROTATE}break;case h.MOUSE.PAN:if(_.ctrlKey||_.metaKey||_.shiftKey){if(n.enableRotate===!1)return;de(_),l=a.ROTATE}else{if(n.enablePan===!1)return;Le(_),l=a.PAN}break;default:l=a.NONE}l!==a.NONE&&n.dispatchEvent(r)}function Jo(_){if(n.enabled!==!1)switch(l){case a.ROTATE:if(n.enableRotate===!1)return;pe(_);break;case a.DOLLY:if(n.enableZoom===!1)return;Se(_);break;case a.PAN:if(n.enablePan===!1)return;Me(_);break}}function xi(_){n.enabled===!1||n.enableZoom===!1||l!==a.NONE&&l!==a.ROTATE||(_.preventDefault(),n.dispatchEvent(r),ce(_),n.dispatchEvent(s))}function Et(_){n.enabled===!1||n.enablePan===!1||re(_)}function Qo(_){switch(Si(_),L.length){case 1:switch(n.touches.ONE){case h.TOUCH.ROTATE:if(n.enableRotate===!1)return;wt(),l=a.TOUCH_ROTATE;break;case h.TOUCH.PAN:if(n.enablePan===!1)return;et(),l=a.TOUCH_PAN;break;default:l=a.NONE}break;case 2:switch(n.touches.TWO){case h.TOUCH.DOLLY_PAN:if(n.enableZoom===!1&&n.enablePan===!1)return;tt(),l=a.TOUCH_DOLLY_PAN;break;case h.TOUCH.DOLLY_ROTATE:if(n.enableZoom===!1&&n.enableRotate===!1)return;ve(),l=a.TOUCH_DOLLY_ROTATE;break;default:l=a.NONE}break;default:l=a.NONE}l!==a.NONE&&n.dispatchEvent(r)}function Ho(_){switch(Si(_),l){case a.TOUCH_ROTATE:if(n.enableRotate===!1)return;gi(_),n.update();break;case a.TOUCH_PAN:if(n.enablePan===!1)return;bi(_),n.update();break;case a.TOUCH_DOLLY_PAN:if(n.enableZoom===!1&&n.enablePan===!1)return;No(_),n.update();break;case a.TOUCH_DOLLY_ROTATE:if(n.enableZoom===!1&&n.enableRotate===!1)return;jo(_),n.update();break;default:l=a.NONE}}function Li(_){n.enabled!==!1&&_.preventDefault()}function Eo(_){L.push(_)}function qo(_){delete Z[_.pointerId];for(let k=0;k<L.length;k++)if(L[k].pointerId==_.pointerId){L.splice(k,1);return}}function Si(_){let k=Z[_.pointerId];k===void 0&&(k=new h.Vector2,Z[_.pointerId]=k),k.set(_.pageX,_.pageY)}function qt(_){const k=_.pointerId===L[0].pointerId?L[1]:L[0];return Z[k.pointerId]}this.dollyIn=(_=C())=>{H(_),n.update()},this.dollyOut=(_=C())=>{j(_),n.update()},this.getScale=()=>p,this.setScale=_=>{z(_),n.update()},this.getZoomScale=()=>C(),e!==void 0&&this.connect(e),this.update()}}class Hi extends Qi{constructor(t,e){super(t,e),this.screenSpacePanning=!1,this.mouseButtons.LEFT=h.MOUSE.PAN,this.mouseButtons.RIGHT=h.MOUSE.ROTATE,this.touches.ONE=h.TOUCH.PAN,this.touches.TWO=h.TOUCH.DOLLY_ROTATE}}function ze(o){if(typeof TextDecoder<"u")return new TextDecoder().decode(o);let t="";for(let e=0,n=o.length;e<n;e++)t+=String.fromCharCode(o[e]);try{return decodeURIComponent(escape(t))}catch{return t}}const Ce="srgb",we="srgb-linear",un=3001,Ei=3e3;class qi extends h.Loader{constructor(t){super(t),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new ir(e)}),this.register(function(e){return new rr(e)}),this.register(function(e){return new pr(e)}),this.register(function(e){return new fr(e)}),this.register(function(e){return new mr(e)}),this.register(function(e){return new or(e)}),this.register(function(e){return new ar(e)}),this.register(function(e){return new lr(e)}),this.register(function(e){return new cr(e)}),this.register(function(e){return new nr(e)}),this.register(function(e){return new ur(e)}),this.register(function(e){return new sr(e)}),this.register(function(e){return new dr(e)}),this.register(function(e){return new hr(e)}),this.register(function(e){return new er(e)}),this.register(function(e){return new yr(e)}),this.register(function(e){return new gr(e)})}load(t,e,n,i){const r=this;let s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){const u=h.LoaderUtils.extractUrlBase(t);s=h.LoaderUtils.resolveURL(u,this.path)}else s=h.LoaderUtils.extractUrlBase(t);this.manager.itemStart(t);const a=function(u){i?i(u):console.error(u),r.manager.itemError(t),r.manager.itemEnd(t)},l=new h.FileLoader(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(t,function(u){try{r.parse(u,s,function(d){e(d),r.manager.itemEnd(t)},a)}catch(d){a(d)}},n,a)}setDRACOLoader(t){return this.dracoLoader=t,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(t){return this.ktx2Loader=t,this}setMeshoptDecoder(t){return this.meshoptDecoder=t,this}register(t){return this.pluginCallbacks.indexOf(t)===-1&&this.pluginCallbacks.push(t),this}unregister(t){return this.pluginCallbacks.indexOf(t)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(t),1),this}parse(t,e,n,i){let r;const s={},a={};if(typeof t=="string")r=JSON.parse(t);else if(t instanceof ArrayBuffer)if(ze(new Uint8Array(t.slice(0,4)))===hn){try{s[Y.KHR_BINARY_GLTF]=new br(t)}catch(d){i&&i(d);return}r=JSON.parse(s[Y.KHR_BINARY_GLTF].content)}else r=JSON.parse(ze(new Uint8Array(t)));else r=t;if(r.asset===void 0||r.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new Wr(r,{path:e||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const d=this.pluginCallbacks[u](l);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[d.name]=d,s[d.name]=!0}if(r.extensionsUsed)for(let u=0;u<r.extensionsUsed.length;++u){const d=r.extensionsUsed[u],c=r.extensionsRequired||[];switch(d){case Y.KHR_MATERIALS_UNLIT:s[d]=new tr;break;case Y.KHR_DRACO_MESH_COMPRESSION:s[d]=new vr(r,this.dracoLoader);break;case Y.KHR_TEXTURE_TRANSFORM:s[d]=new wr;break;case Y.KHR_MESH_QUANTIZATION:s[d]=new xr;break;default:c.indexOf(d)>=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}l.setExtensions(s),l.setPlugins(a),l.parse(n,i)}parseAsync(t,e){const n=this;return new Promise(function(i,r){n.parse(t,e,i,r)})}}function $i(){let o={};return{get:function(t){return o[t]},add:function(t,e){o[t]=e},remove:function(t){delete o[t]},removeAll:function(){o={}}}}const Y={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class er{constructor(t){this.parser=t,this.name=Y.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const t=this.parser,e=this.parser.json.nodes||[];for(let n=0,i=e.length;n<i;n++){const r=e[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&t._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(t){const e=this.parser,n="light:"+t;let i=e.cache.get(n);if(i)return i;const r=e.json,l=((r.extensions&&r.extensions[this.name]||{}).lights||[])[t];let u;const d=new h.Color(16777215);l.color!==void 0&&d.setRGB(l.color[0],l.color[1],l.color[2],we);const c=l.range!==void 0?l.range:0;switch(l.type){case"directional":u=new h.DirectionalLight(d),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new h.PointLight(d),u.distance=c;break;case"spot":u=new h.SpotLight(d),u.distance=c,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,u.angle=l.spot.outerConeAngle,u.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return u.position.set(0,0,0),u.decay=2,xe(u,l),l.intensity!==void 0&&(u.intensity=l.intensity),u.name=e.createUniqueName(l.name||"light_"+t),i=Promise.resolve(u),e.cache.add(n,i),i}getDependency(t,e){if(t==="light")return this._loadLight(e)}createNodeAttachment(t){const e=this,n=this.parser,r=n.json.nodes[t],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return n._getNodeRef(e.cache,a,l)})}}class tr{constructor(){this.name=Y.KHR_MATERIALS_UNLIT}getMaterialType(){return h.MeshBasicMaterial}extendParams(t,e,n){const i=[];t.color=new h.Color(1,1,1),t.opacity=1;const r=e.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const s=r.baseColorFactor;t.color.setRGB(s[0],s[1],s[2],we),t.opacity=s[3]}r.baseColorTexture!==void 0&&i.push(n.assignTexture(t,"map",r.baseColorTexture,Ce))}return Promise.all(i)}}class nr{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(t,e){const i=this.parser.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=i.extensions[this.name].emissiveStrength;return r!==void 0&&(e.emissiveIntensity=r),Promise.resolve()}}class ir{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_CLEARCOAT}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];if(s.clearcoatFactor!==void 0&&(e.clearcoat=s.clearcoatFactor),s.clearcoatTexture!==void 0&&r.push(n.assignTexture(e,"clearcoatMap",s.clearcoatTexture)),s.clearcoatRoughnessFactor!==void 0&&(e.clearcoatRoughness=s.clearcoatRoughnessFactor),s.clearcoatRoughnessTexture!==void 0&&r.push(n.assignTexture(e,"clearcoatRoughnessMap",s.clearcoatRoughnessTexture)),s.clearcoatNormalTexture!==void 0&&(r.push(n.assignTexture(e,"clearcoatNormalMap",s.clearcoatNormalTexture)),s.clearcoatNormalTexture.scale!==void 0)){const a=s.clearcoatNormalTexture.scale;e.clearcoatNormalScale=new h.Vector2(a,a)}return Promise.all(r)}}class rr{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_DISPERSION}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const i=this.parser.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=i.extensions[this.name];return e.dispersion=r.dispersion!==void 0?r.dispersion:0,Promise.resolve()}}class sr{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_IRIDESCENCE}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return s.iridescenceFactor!==void 0&&(e.iridescence=s.iridescenceFactor),s.iridescenceTexture!==void 0&&r.push(n.assignTexture(e,"iridescenceMap",s.iridescenceTexture)),s.iridescenceIor!==void 0&&(e.iridescenceIOR=s.iridescenceIor),e.iridescenceThicknessRange===void 0&&(e.iridescenceThicknessRange=[100,400]),s.iridescenceThicknessMinimum!==void 0&&(e.iridescenceThicknessRange[0]=s.iridescenceThicknessMinimum),s.iridescenceThicknessMaximum!==void 0&&(e.iridescenceThicknessRange[1]=s.iridescenceThicknessMaximum),s.iridescenceThicknessTexture!==void 0&&r.push(n.assignTexture(e,"iridescenceThicknessMap",s.iridescenceThicknessTexture)),Promise.all(r)}}class or{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_SHEEN}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[];e.sheenColor=new h.Color(0,0,0),e.sheenRoughness=0,e.sheen=1;const s=i.extensions[this.name];if(s.sheenColorFactor!==void 0){const a=s.sheenColorFactor;e.sheenColor.setRGB(a[0],a[1],a[2],we)}return s.sheenRoughnessFactor!==void 0&&(e.sheenRoughness=s.sheenRoughnessFactor),s.sheenColorTexture!==void 0&&r.push(n.assignTexture(e,"sheenColorMap",s.sheenColorTexture,Ce)),s.sheenRoughnessTexture!==void 0&&r.push(n.assignTexture(e,"sheenRoughnessMap",s.sheenRoughnessTexture)),Promise.all(r)}}class ar{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_TRANSMISSION}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return s.transmissionFactor!==void 0&&(e.transmission=s.transmissionFactor),s.transmissionTexture!==void 0&&r.push(n.assignTexture(e,"transmissionMap",s.transmissionTexture)),Promise.all(r)}}class lr{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_VOLUME}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];e.thickness=s.thicknessFactor!==void 0?s.thicknessFactor:0,s.thicknessTexture!==void 0&&r.push(n.assignTexture(e,"thicknessMap",s.thicknessTexture)),e.attenuationDistance=s.attenuationDistance||1/0;const a=s.attenuationColor||[1,1,1];return e.attenuationColor=new h.Color().setRGB(a[0],a[1],a[2],we),Promise.all(r)}}class cr{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_IOR}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const i=this.parser.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=i.extensions[this.name];return e.ior=r.ior!==void 0?r.ior:1.5,Promise.resolve()}}class ur{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_SPECULAR}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];e.specularIntensity=s.specularFactor!==void 0?s.specularFactor:1,s.specularTexture!==void 0&&r.push(n.assignTexture(e,"specularIntensityMap",s.specularTexture));const a=s.specularColorFactor||[1,1,1];return e.specularColor=new h.Color().setRGB(a[0],a[1],a[2],we),s.specularColorTexture!==void 0&&r.push(n.assignTexture(e,"specularColorMap",s.specularColorTexture,Ce)),Promise.all(r)}}class hr{constructor(t){this.parser=t,this.name=Y.EXT_MATERIALS_BUMP}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return e.bumpScale=s.bumpFactor!==void 0?s.bumpFactor:1,s.bumpTexture!==void 0&&r.push(n.assignTexture(e,"bumpMap",s.bumpTexture)),Promise.all(r)}}class dr{constructor(t){this.parser=t,this.name=Y.KHR_MATERIALS_ANISOTROPY}getMaterialType(t){const n=this.parser.json.materials[t];return!n.extensions||!n.extensions[this.name]?null:h.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser,i=n.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const r=[],s=i.extensions[this.name];return s.anisotropyStrength!==void 0&&(e.anisotropy=s.anisotropyStrength),s.anisotropyRotation!==void 0&&(e.anisotropyRotation=s.anisotropyRotation),s.anisotropyTexture!==void 0&&r.push(n.assignTexture(e,"anisotropyMap",s.anisotropyTexture)),Promise.all(r)}}class pr{constructor(t){this.parser=t,this.name=Y.KHR_TEXTURE_BASISU}loadTexture(t){const e=this.parser,n=e.json,i=n.textures[t];if(!i.extensions||!i.extensions[this.name])return null;const r=i.extensions[this.name],s=e.options.ktx2Loader;if(!s){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return e.loadTextureImage(t,r.source,s)}}class fr{constructor(t){this.parser=t,this.name=Y.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(t){const e=this.name,n=this.parser,i=n.json,r=i.textures[t];if(!r.extensions||!r.extensions[e])return null;const s=r.extensions[e],a=i.images[s.source];let l=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(l=u)}return this.detectSupport().then(function(u){if(u)return n.loadTextureImage(t,s.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(e)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(t)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(t){const e=new Image;e.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",e.onload=e.onerror=function(){t(e.height===1)}})),this.isSupported}}class mr{constructor(t){this.parser=t,this.name=Y.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(t){const e=this.name,n=this.parser,i=n.json,r=i.textures[t];if(!r.extensions||!r.extensions[e])return null;const s=r.extensions[e],a=i.images[s.source];let l=n.textureLoader;if(a.uri){const u=n.options.manager.getHandler(a.uri);u!==null&&(l=u)}return this.detectSupport().then(function(u){if(u)return n.loadTextureImage(t,s.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(e)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(t)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(t){const e=new Image;e.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",e.onload=e.onerror=function(){t(e.height===1)}})),this.isSupported}}class yr{constructor(t){this.name=Y.EXT_MESHOPT_COMPRESSION,this.parser=t}loadBufferView(t){const e=this.parser.json,n=e.bufferViews[t];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){const l=i.byteOffset||0,u=i.byteLength||0,d=i.count,c=i.byteStride,p=new Uint8Array(a,l,u);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(d,c,p,i.mode,i.filter).then(function(f){return f.buffer}):s.ready.then(function(){const f=new ArrayBuffer(d*c);return s.decodeGltfBuffer(new Uint8Array(f),d,c,p,i.mode,i.filter),f})})}else return null}}class gr{constructor(t){this.name=Y.EXT_MESH_GPU_INSTANCING,this.parser=t}createNodeMesh(t){const e=this.parser.json,n=e.nodes[t];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=e.meshes[n.mesh];for(const u of i.primitives)if(u.mode!==ae.TRIANGLES&&u.mode!==ae.TRIANGLE_STRIP&&u.mode!==ae.TRIANGLE_FAN&&u.mode!==void 0)return null;const s=n.extensions[this.name].attributes,a=[],l={};for(const u in s)a.push(this.parser.getDependency("accessor",s[u]).then(d=>(l[u]=d,l[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(t)),Promise.all(a).then(u=>{const d=u.pop(),c=d.isGroup?d.children:[d],p=u[0].count,f=[];for(const m of c){const v=new h.Matrix4,g=new h.Vector3,b=new h.Quaternion,y=new h.Vector3(1,1,1),w=new h.InstancedMesh(m.geometry,m.material,p);for(let S=0;S<p;S++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,S),l.ROTATION&&b.fromBufferAttribute(l.ROTATION,S),l.SCALE&&y.fromBufferAttribute(l.SCALE,S),w.setMatrixAt(S,v.compose(g,b,y));for(const S in l)if(S==="_COLOR_0"){const P=l[S];w.instanceColor=new h.InstancedBufferAttribute(P.array,P.itemSize,P.normalized)}else S!=="TRANSLATION"&&S!=="ROTATION"&&S!=="SCALE"&&m.geometry.setAttribute(S,l[S]);h.Object3D.prototype.copy.call(w,m),this.parser.assignFinalMaterial(w),f.push(w)}return d.isGroup?(d.clear(),d.add(...f),d):f[0]}))}}const hn="glTF",Re=12,dn={JSON:1313821514,BIN:5130562};class br{constructor(t){this.name=Y.KHR_BINARY_GLTF,this.content=null,this.body=null;const e=new DataView(t,0,Re);if(this.header={magic:ze(new Uint8Array(t.slice(0,4))),version:e.getUint32(4,!0),length:e.getUint32(8,!0)},this.header.magic!==hn)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-Re,i=new DataView(t,Re);let r=0;for(;r<n;){const s=i.getUint32(r,!0);r+=4;const a=i.getUint32(r,!0);if(r+=4,a===dn.JSON){const l=new Uint8Array(t,Re+r,s);this.content=ze(l)}else if(a===dn.BIN){const l=Re+r;this.body=t.slice(l,l+s)}r+=s}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class vr{constructor(t,e){if(!e)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Y.KHR_DRACO_MESH_COMPRESSION,this.json=t,this.dracoLoader=e,this.dracoLoader.preload()}decodePrimitive(t,e){const n=this.json,i=this.dracoLoader,r=t.extensions[this.name].bufferView,s=t.extensions[this.name].attributes,a={},l={},u={};for(const d in s){const c=Tt[d]||d.toLowerCase();a[c]=s[d]}for(const d in t.attributes){const c=Tt[d]||d.toLowerCase();if(s[d]!==void 0){const p=n.accessors[t.attributes[d]],f=Xe[p.componentType];u[c]=f.name,l[c]=p.normalized===!0}}return e.getDependency("bufferView",r).then(function(d){return new Promise(function(c,p){i.decodeDracoFile(d,function(f){for(const m in f.attributes){const v=f.attributes[m],g=l[m];g!==void 0&&(v.normalized=g)}c(f)},a,u,we,p)})})}}class wr{constructor(){this.name=Y.KHR_TEXTURE_TRANSFORM}extendTexture(t,e){return(e.texCoord===void 0||e.texCoord===t.channel)&&e.offset===void 0&&e.rotation===void 0&&e.scale===void 0||(t=t.clone(),e.texCoord!==void 0&&(t.channel=e.texCoord),e.offset!==void 0&&t.offset.fromArray(e.offset),e.rotation!==void 0&&(t.rotation=e.rotation),e.scale!==void 0&&t.repeat.fromArray(e.scale),t.needsUpdate=!0),t}}class xr{constructor(){this.name=Y.KHR_MESH_QUANTIZATION}}class pn extends h.Interpolant{constructor(t,e,n,i){super(t,e,n,i)}copySampleValue_(t){const e=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=t*i*3+i;for(let s=0;s!==i;s++)e[s]=n[r+s];return e}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,l=a*2,u=a*3,d=i-e,c=(n-e)/d,p=c*c,f=p*c,m=t*u,v=m-u,g=-2*f+3*p,b=f-p,y=1-g,w=b-p+c;for(let S=0;S!==a;S++){const P=s[v+S+a],I=s[v+S+l]*d,T=s[m+S+a],M=s[m+S]*d;r[S]=y*P+w*I+g*T+b*M}return r}}const Lr=new h.Quaternion;class Sr extends pn{interpolate_(t,e,n,i){const r=super.interpolate_(t,e,n,i);return Lr.fromArray(r).normalize().toArray(r),r}}const ae={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Xe={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},fn={9728:h.NearestFilter,9729:h.LinearFilter,9984:h.NearestMipmapNearestFilter,9985:h.LinearMipmapNearestFilter,9986:h.NearestMipmapLinearFilter,9987:h.LinearMipmapLinearFilter},mn={33071:h.ClampToEdgeWrapping,33648:h.MirroredRepeatWrapping,10497:h.RepeatWrapping},It={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Tt={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",...ot>=152?{TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3"}:{TEXCOORD_0:"uv",TEXCOORD_1:"uv2"},COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Ae={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Mr={CUBICSPLINE:void 0,LINEAR:h.InterpolateLinear,STEP:h.InterpolateDiscrete},Pt={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function _r(o){return o.DefaultMaterial===void 0&&(o.DefaultMaterial=new h.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:h.FrontSide})),o.DefaultMaterial}function ke(o,t,e){for(const n in e.extensions)o[n]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[n]=e.extensions[n])}function xe(o,t){t.extras!==void 0&&(typeof t.extras=="object"?Object.assign(o.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function Zr(o,t,e){let n=!1,i=!1,r=!1;for(let u=0,d=t.length;u<d;u++){const c=t[u];if(c.POSITION!==void 0&&(n=!0),c.NORMAL!==void 0&&(i=!0),c.COLOR_0!==void 0&&(r=!0),n&&i&&r)break}if(!n&&!i&&!r)return Promise.resolve(o);const s=[],a=[],l=[];for(let u=0,d=t.length;u<d;u++){const c=t[u];if(n){const p=c.POSITION!==void 0?e.getDependency("accessor",c.POSITION):o.attributes.position;s.push(p)}if(i){const p=c.NORMAL!==void 0?e.getDependency("accessor",c.NORMAL):o.attributes.normal;a.push(p)}if(r){const p=c.COLOR_0!==void 0?e.getDependency("accessor",c.COLOR_0):o.attributes.color;l.push(p)}}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(l)]).then(function(u){const d=u[0],c=u[1],p=u[2];return n&&(o.morphAttributes.position=d),i&&(o.morphAttributes.normal=c),r&&(o.morphAttributes.color=p),o.morphTargetsRelative=!0,o})}function Ir(o,t){if(o.updateMorphTargets(),t.weights!==void 0)for(let e=0,n=t.weights.length;e<n;e++)o.morphTargetInfluences[e]=t.weights[e];if(t.extras&&Array.isArray(t.extras.targetNames)){const e=t.extras.targetNames;if(o.morphTargetInfluences.length===e.length){o.morphTargetDictionary={};for(let n=0,i=e.length;n<i;n++)o.morphTargetDictionary[e[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Tr(o){let t;const e=o.extensions&&o.extensions[Y.KHR_DRACO_MESH_COMPRESSION];if(e?t="draco:"+e.bufferView+":"+e.indices+":"+At(e.attributes):t=o.indices+":"+At(o.attributes)+":"+o.mode,o.targets!==void 0)for(let n=0,i=o.targets.length;n<i;n++)t+=":"+At(o.targets[n]);return t}function At(o){let t="";const e=Object.keys(o).sort();for(let n=0,i=e.length;n<i;n++)t+=e[n]+":"+o[e[n]]+";";return t}function Wt(o){switch(o){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Pr(o){return o.search(/\.jpe?g($|\?)/i)>0||o.search(/^data\:image\/jpeg/)===0?"image/jpeg":o.search(/\.webp($|\?)/i)>0||o.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const Ar=new h.Matrix4;class Wr{constructor(t={},e={}){this.json=t,this.extensions={},this.plugins={},this.options=e,this.cache=new $i,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=!1,r=-1;typeof navigator<"u"&&typeof navigator.userAgent<"u"&&(n=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,i=navigator.userAgent.indexOf("Firefox")>-1,r=i?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||n||i&&r<98?this.textureLoader=new h.TextureLoader(this.options.manager):this.textureLoader=new h.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new h.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(t){this.extensions=t}setPlugins(t){this.plugins=t}parse(t,e){const n=this,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(s){const a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:n,userData:{}};return ke(r,a,i),xe(a,i),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();t(a)})}).catch(e)}_markDefs(){const t=this.json.nodes||[],e=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=e.length;i<r;i++){const s=e[i].joints;for(let a=0,l=s.length;a<l;a++)t[s[a]].isBone=!0}for(let i=0,r=t.length;i<r;i++){const s=t[i];s.mesh!==void 0&&(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0&&(n[s.mesh].isSkinnedMesh=!0)),s.camera!==void 0&&this._addNodeRef(this.cameraCache,s.camera)}}_addNodeRef(t,e){e!==void 0&&(t.refs[e]===void 0&&(t.refs[e]=t.uses[e]=0),t.refs[e]++)}_getNodeRef(t,e,n){if(t.refs[e]<=1)return n;const i=n.clone(),r=(s,a)=>{const l=this.associations.get(s);l!=null&&this.associations.set(a,l);for(const[u,d]of s.children.entries())r(d,a.children[u])};return r(n,i),i.name+="_instance_"+t.uses[e]++,i}_invokeOne(t){const e=Object.values(this.plugins);e.push(this);for(let n=0;n<e.length;n++){const i=t(e[n]);if(i)return i}return null}_invokeAll(t){const e=Object.values(this.plugins);e.unshift(this);const n=[];for(let i=0;i<e.length;i++){const r=t(e[i]);r&&n.push(r)}return n}getDependency(t,e){const n=t+":"+e;let i=this.cache.get(n);if(!i){switch(t){case"scene":i=this.loadScene(e);break;case"node":i=this._invokeOne(function(r){return r.loadNode&&r.loadNode(e)});break;case"mesh":i=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(e)});break;case"accessor":i=this.loadAccessor(e);break;case"bufferView":i=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(e)});break;case"buffer":i=this.loadBuffer(e);break;case"material":i=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(e)});break;case"texture":i=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(e)});break;case"skin":i=this.loadSkin(e);break;case"animation":i=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(e)});break;case"camera":i=this.loadCamera(e);break;default:if(i=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(t,e)}),!i)throw new Error("Unknown type: "+t);break}this.cache.add(n,i)}return i}getDependencies(t){let e=this.cache.get(t);if(!e){const n=this,i=this.json[t+(t==="mesh"?"es":"s")]||[];e=Promise.all(i.map(function(r,s){return n.getDependency(t,s)})),this.cache.add(t,e)}return e}loadBuffer(t){const e=this.json.buffers[t],n=this.fileLoader;if(e.type&&e.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+e.type+" buffer type is not supported.");if(e.uri===void 0&&t===0)return Promise.resolve(this.extensions[Y.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(r,s){n.load(h.LoaderUtils.resolveURL(e.uri,i.path),r,void 0,function(){s(new Error('THREE.GLTFLoader: Failed to load buffer "'+e.uri+'".'))})})}loadBufferView(t){const e=this.json.bufferViews[t];return this.getDependency("buffer",e.buffer).then(function(n){const i=e.byteLength||0,r=e.byteOffset||0;return n.slice(r,r+i)})}loadAccessor(t){const e=this,n=this.json,i=this.json.accessors[t];if(i.bufferView===void 0&&i.sparse===void 0){const s=It[i.type],a=Xe[i.componentType],l=i.normalized===!0,u=new a(i.count*s);return Promise.resolve(new h.BufferAttribute(u,s,l))}const r=[];return i.bufferView!==void 0?r.push(this.getDependency("bufferView",i.bufferView)):r.push(null),i.sparse!==void 0&&(r.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(r).then(function(s){const a=s[0],l=It[i.type],u=Xe[i.componentType],d=u.BYTES_PER_ELEMENT,c=d*l,p=i.byteOffset||0,f=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,m=i.normalized===!0;let v,g;if(f&&f!==c){const b=Math.floor(p/f),y="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+b+":"+i.count;let w=e.cache.get(y);w||(v=new u(a,b*f,i.count*f/d),w=new h.InterleavedBuffer(v,f/d),e.cache.add(y,w)),g=new h.InterleavedBufferAttribute(w,l,p%f/d,m)}else a===null?v=new u(i.count*l):v=new u(a,p,i.count*l),g=new h.BufferAttribute(v,l,m);if(i.sparse!==void 0){const b=It.SCALAR,y=Xe[i.sparse.indices.componentType],w=i.sparse.indices.byteOffset||0,S=i.sparse.values.byteOffset||0,P=new y(s[1],w,i.sparse.count*b),I=new u(s[2],S,i.sparse.count*l);a!==null&&(g=new h.BufferAttribute(g.array.slice(),g.itemSize,g.normalized));for(let T=0,M=P.length;T<M;T++){const A=P[T];if(g.setX(A,I[T*l]),l>=2&&g.setY(A,I[T*l+1]),l>=3&&g.setZ(A,I[T*l+2]),l>=4&&g.setW(A,I[T*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return g})}loadTexture(t){const e=this.json,n=this.options,r=e.textures[t].source,s=e.images[r];let a=this.textureLoader;if(s.uri){const l=n.manager.getHandler(s.uri);l!==null&&(a=l)}return this.loadTextureImage(t,r,a)}loadTextureImage(t,e,n){const i=this,r=this.json,s=r.textures[t],a=r.images[e],l=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[l])return this.textureCache[l];const u=this.loadImageSource(e,n).then(function(d){d.flipY=!1,d.name=s.name||a.name||"",d.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(d.name=a.uri);const p=(r.samplers||{})[s.sampler]||{};return d.magFilter=fn[p.magFilter]||h.LinearFilter,d.minFilter=fn[p.minFilter]||h.LinearMipmapLinearFilter,d.wrapS=mn[p.wrapS]||h.RepeatWrapping,d.wrapT=mn[p.wrapT]||h.RepeatWrapping,i.associations.set(d,{textures:t}),d}).catch(function(){return null});return this.textureCache[l]=u,u}loadImageSource(t,e){const n=this,i=this.json,r=this.options;if(this.sourceCache[t]!==void 0)return this.sourceCache[t].then(c=>c.clone());const s=i.images[t],a=self.URL||self.webkitURL;let l=s.uri||"",u=!1;if(s.bufferView!==void 0)l=n.getDependency("bufferView",s.bufferView).then(function(c){u=!0;const p=new Blob([c],{type:s.mimeType});return l=a.createObjectURL(p),l});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+t+" is missing URI and bufferView");const d=Promise.resolve(l).then(function(c){return new Promise(function(p,f){let m=p;e.isImageBitmapLoader===!0&&(m=function(v){const g=new h.Texture(v);g.needsUpdate=!0,p(g)}),e.load(h.LoaderUtils.resolveURL(c,r.path),m,void 0,f)})}).then(function(c){return u===!0&&a.revokeObjectURL(l),xe(c,s),c.userData.mimeType=s.mimeType||Pr(s.uri),c}).catch(function(c){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),c});return this.sourceCache[t]=d,d}assignTexture(t,e,n,i){const r=this;return this.getDependency("texture",n.index).then(function(s){if(!s)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(s=s.clone(),s.channel=n.texCoord),r.extensions[Y.KHR_TEXTURE_TRANSFORM]){const a=n.extensions!==void 0?n.extensions[Y.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=r.associations.get(s);s=r.extensions[Y.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),r.associations.set(s,l)}}return i!==void 0&&(typeof i=="number"&&(i=i===un?Ce:we),"colorSpace"in s?s.colorSpace=i:s.encoding=i===Ce?un:Ei),t[e]=s,s})}assignFinalMaterial(t){const e=t.geometry;let n=t.material;const i=e.attributes.tangent===void 0,r=e.attributes.color!==void 0,s=e.attributes.normal===void 0;if(t.isPoints){const a="PointsMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new h.PointsMaterial,h.Material.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(a,l)),n=l}else if(t.isLine){const a="LineBasicMaterial:"+n.uuid;let l=this.cache.get(a);l||(l=new h.LineBasicMaterial,h.Material.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(a,l)),n=l}if(i||r||s){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),s&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=n.clone(),r&&(l.vertexColors=!0),s&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(n))),n=l}t.material=n}getMaterialType(){return h.MeshStandardMaterial}loadMaterial(t){const e=this,n=this.json,i=this.extensions,r=n.materials[t];let s;const a={},l=r.extensions||{},u=[];if(l[Y.KHR_MATERIALS_UNLIT]){const c=i[Y.KHR_MATERIALS_UNLIT];s=c.getMaterialType(),u.push(c.extendParams(a,r,e))}else{const c=r.pbrMetallicRoughness||{};if(a.color=new h.Color(1,1,1),a.opacity=1,Array.isArray(c.baseColorFactor)){const p=c.baseColorFactor;a.color.setRGB(p[0],p[1],p[2],we),a.opacity=p[3]}c.baseColorTexture!==void 0&&u.push(e.assignTexture(a,"map",c.baseColorTexture,Ce)),a.metalness=c.metallicFactor!==void 0?c.metallicFactor:1,a.roughness=c.roughnessFactor!==void 0?c.roughnessFactor:1,c.metallicRoughnessTexture!==void 0&&(u.push(e.assignTexture(a,"metalnessMap",c.metallicRoughnessTexture)),u.push(e.assignTexture(a,"roughnessMap",c.metallicRoughnessTexture))),s=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(t)}),u.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(t,a)})))}r.doubleSided===!0&&(a.side=h.DoubleSide);const d=r.alphaMode||Pt.OPAQUE;if(d===Pt.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,d===Pt.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&s!==h.MeshBasicMaterial&&(u.push(e.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new h.Vector2(1,1),r.normalTexture.scale!==void 0)){const c=r.normalTexture.scale;a.normalScale.set(c,c)}if(r.occlusionTexture!==void 0&&s!==h.MeshBasicMaterial&&(u.push(e.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&s!==h.MeshBasicMaterial){const c=r.emissiveFactor;a.emissive=new h.Color().setRGB(c[0],c[1],c[2],we)}return r.emissiveTexture!==void 0&&s!==h.MeshBasicMaterial&&u.push(e.assignTexture(a,"emissiveMap",r.emissiveTexture,Ce)),Promise.all(u).then(function(){const c=new s(a);return r.name&&(c.name=r.name),xe(c,r),e.associations.set(c,{materials:t}),r.extensions&&ke(i,c,r),c})}createUniqueName(t){const e=h.PropertyBinding.sanitizeNodeName(t||"");return e in this.nodeNamesUsed?e+"_"+ ++this.nodeNamesUsed[e]:(this.nodeNamesUsed[e]=0,e)}loadGeometries(t){const e=this,n=this.extensions,i=this.primitiveCache;function r(a){return n[Y.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,e).then(function(l){return yn(l,a,e)})}const s=[];for(let a=0,l=t.length;a<l;a++){const u=t[a],d=Tr(u),c=i[d];if(c)s.push(c.promise);else{let p;u.extensions&&u.extensions[Y.KHR_DRACO_MESH_COMPRESSION]?p=r(u):p=yn(new h.BufferGeometry,u,e),i[d]={primitive:u,promise:p},s.push(p)}}return Promise.all(s)}loadMesh(t){const e=this,n=this.json,i=this.extensions,r=n.meshes[t],s=r.primitives,a=[];for(let l=0,u=s.length;l<u;l++){const d=s[l].material===void 0?_r(this.cache):this.getDependency("material",s[l].material);a.push(d)}return a.push(e.loadGeometries(s)),Promise.all(a).then(function(l){const u=l.slice(0,l.length-1),d=l[l.length-1],c=[];for(let f=0,m=d.length;f<m;f++){const v=d[f],g=s[f];let b;const y=u[f];if(g.mode===ae.TRIANGLES||g.mode===ae.TRIANGLE_STRIP||g.mode===ae.TRIANGLE_FAN||g.mode===void 0)b=r.isSkinnedMesh===!0?new h.SkinnedMesh(v,y):new h.Mesh(v,y),b.isSkinnedMesh===!0&&b.normalizeSkinWeights(),g.mode===ae.TRIANGLE_STRIP?b.geometry=en(b.geometry,h.TriangleStripDrawMode):g.mode===ae.TRIANGLE_FAN&&(b.geometry=en(b.geometry,h.TriangleFanDrawMode));else if(g.mode===ae.LINES)b=new h.LineSegments(v,y);else if(g.mode===ae.LINE_STRIP)b=new h.Line(v,y);else if(g.mode===ae.LINE_LOOP)b=new h.LineLoop(v,y);else if(g.mode===ae.POINTS)b=new h.Points(v,y);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(b.geometry.morphAttributes).length>0&&Ir(b,r),b.name=e.createUniqueName(r.name||"mesh_"+t),xe(b,r),g.extensions&&ke(i,b,g),e.assignFinalMaterial(b),c.push(b)}for(let f=0,m=c.length;f<m;f++)e.associations.set(c[f],{meshes:t,primitives:f});if(c.length===1)return r.extensions&&ke(i,c[0],r),c[0];const p=new h.Group;r.extensions&&ke(i,p,r),e.associations.set(p,{meshes:t});for(let f=0,m=c.length;f<m;f++)p.add(c[f]);return p})}loadCamera(t){let e;const n=this.json.cameras[t],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?e=new h.PerspectiveCamera(h.MathUtils.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(e=new h.OrthographicCamera(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(e.name=this.createUniqueName(n.name)),xe(e,n),Promise.resolve(e)}loadSkin(t){const e=this.json.skins[t],n=[];for(let i=0,r=e.joints.length;i<r;i++)n.push(this._loadNodeShallow(e.joints[i]));return e.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",e.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const r=i.pop(),s=i,a=[],l=[];for(let u=0,d=s.length;u<d;u++){const c=s[u];if(c){a.push(c);const p=new h.Matrix4;r!==null&&p.fromArray(r.array,u*16),l.push(p)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',e.joints[u])}return new h.Skeleton(a,l)})}loadAnimation(t){const e=this.json,n=this,i=e.animations[t],r=i.name?i.name:"animation_"+t,s=[],a=[],l=[],u=[],d=[];for(let c=0,p=i.channels.length;c<p;c++){const f=i.channels[c],m=i.samplers[f.sampler],v=f.target,g=v.node,b=i.parameters!==void 0?i.parameters[m.input]:m.input,y=i.parameters!==void 0?i.parameters[m.output]:m.output;v.node!==void 0&&(s.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",b)),l.push(this.getDependency("accessor",y)),u.push(m),d.push(v))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(l),Promise.all(u),Promise.all(d)]).then(function(c){const p=c[0],f=c[1],m=c[2],v=c[3],g=c[4],b=[];for(let y=0,w=p.length;y<w;y++){const S=p[y],P=f[y],I=m[y],T=v[y],M=g[y];if(S===void 0)continue;S.updateMatrix&&S.updateMatrix();const A=n._createAnimationTracks(S,P,I,T,M);if(A)for(let L=0;L<A.length;L++)b.push(A[L])}return new h.AnimationClip(r,void 0,b)})}createNodeMesh(t){const e=this.json,n=this,i=e.nodes[t];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(r){const s=n._getNodeRef(n.meshCache,i.mesh,r);return i.weights!==void 0&&s.traverse(function(a){if(a.isMesh)for(let l=0,u=i.weights.length;l<u;l++)a.morphTargetInfluences[l]=i.weights[l]}),s})}loadNode(t){const e=this.json,n=this,i=e.nodes[t],r=n._loadNodeShallow(t),s=[],a=i.children||[];for(let u=0,d=a.length;u<d;u++)s.push(n.getDependency("node",a[u]));const l=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([r,Promise.all(s),l]).then(function(u){const d=u[0],c=u[1],p=u[2];p!==null&&d.traverse(function(f){f.isSkinnedMesh&&f.bind(p,Ar)});for(let f=0,m=c.length;f<m;f++)d.add(c[f]);return d})}_loadNodeShallow(t){const e=this.json,n=this.extensions,i=this;if(this.nodeCache[t]!==void 0)return this.nodeCache[t];const r=e.nodes[t],s=r.name?i.createUniqueName(r.name):"",a=[],l=i._invokeOne(function(u){return u.createNodeMesh&&u.createNodeMesh(t)});return l&&a.push(l),r.camera!==void 0&&a.push(i.getDependency("camera",r.camera).then(function(u){return i._getNodeRef(i.cameraCache,r.camera,u)})),i._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(t)}).forEach(function(u){a.push(u)}),this.nodeCache[t]=Promise.all(a).then(function(u){let d;if(r.isBone===!0?d=new h.Bone:u.length>1?d=new h.Group:u.length===1?d=u[0]:d=new h.Object3D,d!==u[0])for(let c=0,p=u.length;c<p;c++)d.add(u[c]);if(r.name&&(d.userData.name=r.name,d.name=s),xe(d,r),r.extensions&&ke(n,d,r),r.matrix!==void 0){const c=new h.Matrix4;c.fromArray(r.matrix),d.applyMatrix4(c)}else r.translation!==void 0&&d.position.fromArray(r.translation),r.rotation!==void 0&&d.quaternion.fromArray(r.rotation),r.scale!==void 0&&d.scale.fromArray(r.scale);return i.associations.has(d)||i.associations.set(d,{}),i.associations.get(d).nodes=t,d}),this.nodeCache[t]}loadScene(t){const e=this.extensions,n=this.json.scenes[t],i=this,r=new h.Group;n.name&&(r.name=i.createUniqueName(n.name)),xe(r,n),n.extensions&&ke(e,r,n);const s=n.nodes||[],a=[];for(let l=0,u=s.length;l<u;l++)a.push(i.getDependency("node",s[l]));return Promise.all(a).then(function(l){for(let d=0,c=l.length;d<c;d++)r.add(l[d]);const u=d=>{const c=new Map;for(const[p,f]of i.associations)(p instanceof h.Material||p instanceof h.Texture)&&c.set(p,f);return d.traverse(p=>{const f=i.associations.get(p);f!=null&&c.set(p,f)}),c};return i.associations=u(r),r})}_createAnimationTracks(t,e,n,i,r){const s=[],a=t.name?t.name:t.uuid,l=[];Ae[r.path]===Ae.weights?t.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(a);let u;switch(Ae[r.path]){case Ae.weights:u=h.NumberKeyframeTrack;break;case Ae.rotation:u=h.QuaternionKeyframeTrack;break;case Ae.position:case Ae.scale:u=h.VectorKeyframeTrack;break;default:switch(n.itemSize){case 1:u=h.NumberKeyframeTrack;break;case 2:case 3:default:u=h.VectorKeyframeTrack;break}break}const d=i.interpolation!==void 0?Mr[i.interpolation]:h.InterpolateLinear,c=this._getArrayFromAccessor(n);for(let p=0,f=l.length;p<f;p++){const m=new u(l[p]+"."+Ae[r.path],e.array,c,d);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(m),s.push(m)}return s}_getArrayFromAccessor(t){let e=t.array;if(t.normalized){const n=Wt(e.constructor),i=new Float32Array(e.length);for(let r=0,s=e.length;r<s;r++)i[r]=e[r]*n;e=i}return e}_createCubicSplineTrackInterpolant(t){t.createInterpolant=function(n){const i=this instanceof h.QuaternionKeyframeTrack?Sr:pn;return new i(this.times,this.values,this.getValueSize()/3,n)},t.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Gr(o,t,e){const n=t.attributes,i=new h.Box3;if(n.POSITION!==void 0){const a=e.json.accessors[n.POSITION],l=a.min,u=a.max;if(l!==void 0&&u!==void 0){if(i.set(new h.Vector3(l[0],l[1],l[2]),new h.Vector3(u[0],u[1],u[2])),a.normalized){const d=Wt(Xe[a.componentType]);i.min.multiplyScalar(d),i.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=t.targets;if(r!==void 0){const a=new h.Vector3,l=new h.Vector3;for(let u=0,d=r.length;u<d;u++){const c=r[u];if(c.POSITION!==void 0){const p=e.json.accessors[c.POSITION],f=p.min,m=p.max;if(f!==void 0&&m!==void 0){if(l.setX(Math.max(Math.abs(f[0]),Math.abs(m[0]))),l.setY(Math.max(Math.abs(f[1]),Math.abs(m[1]))),l.setZ(Math.max(Math.abs(f[2]),Math.abs(m[2]))),p.normalized){const v=Wt(Xe[p.componentType]);l.multiplyScalar(v)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}o.boundingBox=i;const s=new h.Sphere;i.getCenter(s.center),s.radius=i.min.distanceTo(i.max)/2,o.boundingSphere=s}function yn(o,t,e){const n=t.attributes,i=[];function r(s,a){return e.getDependency("accessor",s).then(function(l){o.setAttribute(a,l)})}for(const s in n){const a=Tt[s]||s.toLowerCase();a in o.attributes||i.push(r(n[s],a))}if(t.indices!==void 0&&!o.index){const s=e.getDependency("accessor",t.indices).then(function(a){o.setIndex(a)});i.push(s)}return xe(o,t),Gr(o,t,e),Promise.all(i).then(function(){return t.targets!==void 0?Zr(o,t.targets,e):o})}function gn(o,t,e){const n=e.length-o-1;if(t>=e[n])return n-1;if(t<=e[o])return o;let i=o,r=n,s=Math.floor((i+r)/2);for(;t<e[s]||t>=e[s+1];)t<e[s]?r=s:i=s,s=Math.floor((i+r)/2);return s}function Vr(o,t,e,n){const i=[],r=[],s=[];i[0]=1;for(let a=1;a<=e;++a){r[a]=t-n[o+1-a],s[a]=n[o+a]-t;let l=0;for(let u=0;u<a;++u){const d=s[u+1],c=r[a-u],p=i[u]/(d+c);i[u]=l+d*p,l=c*p}i[a]=l}return i}function Cr(o,t,e,n){const i=gn(o,n,t),r=Vr(i,n,o,t),s=new h.Vector4(0,0,0,0);for(let a=0;a<=o;++a){const l=e[i-o+a],u=r[a],d=l.w*u;s.x+=l.x*d,s.y+=l.y*d,s.z+=l.z*d,s.w+=l.w*u}return s}function kr(o,t,e,n,i){const r=[];for(let c=0;c<=e;++c)r[c]=0;const s=[];for(let c=0;c<=n;++c)s[c]=r.slice(0);const a=[];for(let c=0;c<=e;++c)a[c]=r.slice(0);a[0][0]=1;const l=r.slice(0),u=r.slice(0);for(let c=1;c<=e;++c){l[c]=t-i[o+1-c],u[c]=i[o+c]-t;let p=0;for(let f=0;f<c;++f){const m=u[f+1],v=l[c-f];a[c][f]=m+v;const g=a[f][c-1]/a[c][f];a[f][c]=p+m*g,p=v*g}a[c][c]=p}for(let c=0;c<=e;++c)s[0][c]=a[c][e];for(let c=0;c<=e;++c){let p=0,f=1;const m=[];for(let v=0;v<=e;++v)m[v]=r.slice(0);m[0][0]=1;for(let v=1;v<=n;++v){let g=0;const b=c-v,y=e-v;c>=v&&(m[f][0]=m[p][0]/a[y+1][b],g=m[f][0]*a[b][y]);const w=b>=-1?1:-b,S=c-1<=y?v-1:e-c;for(let I=w;I<=S;++I)m[f][I]=(m[p][I]-m[p][I-1])/a[y+1][b+I],g+=m[f][I]*a[b+I][y];c<=y&&(m[f][v]=-m[p][v-1]/a[y+1][c],g+=m[f][v]*a[c][y]),s[v][c]=g;const P=p;p=f,f=P}}let d=e;for(let c=1;c<=n;++c){for(let p=0;p<=e;++p)s[c][p]*=d;d*=e-c}return s}function Dr(o,t,e,n,i){const r=i<o?i:o,s=[],a=gn(o,n,t),l=kr(a,n,o,r,t),u=[];for(let d=0;d<e.length;++d){const c=e[d].clone(),p=c.w;c.x*=p,c.y*=p,c.z*=p,u[d]=c}for(let d=0;d<=r;++d){const c=u[a-o].clone().multiplyScalar(l[d][0]);for(let p=1;p<=o;++p)c.add(u[a-o+p].clone().multiplyScalar(l[d][p]));s[d]=c}for(let d=r+1;d<=i+1;++d)s[d]=new h.Vector4(0,0,0);return s}function Fr(o,t){let e=1;for(let i=2;i<=o;++i)e*=i;let n=1;for(let i=2;i<=t;++i)n*=i;for(let i=2;i<=o-t;++i)n*=i;return e/n}function Or(o){const t=o.length,e=[],n=[];for(let r=0;r<t;++r){const s=o[r];e[r]=new h.Vector3(s.x,s.y,s.z),n[r]=s.w}const i=[];for(let r=0;r<t;++r){const s=e[r].clone();for(let a=1;a<=r;++a)s.sub(i[r-a].clone().multiplyScalar(Fr(r,a)*n[a]));i[r]=s.divideScalar(n[0])}return i}function zr(o,t,e,n,i){const r=Dr(o,t,e,n,i);return Or(r)}class bn extends h.Curve{constructor(t,e,n,i,r){super(),this.degree=t,this.knots=e,this.controlPoints=[],this.startKnot=i||0,this.endKnot=r||this.knots.length-1;for(let s=0;s<n.length;++s){const a=n[s];this.controlPoints[s]=new h.Vector4(a.x,a.y,a.z,a.w)}}getPoint(t,e){const n=e||new h.Vector3,i=this.knots[this.startKnot]+t*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=Cr(this.degree,this.knots,this.controlPoints,i);return r.w!=1&&r.divideScalar(r.w),n.set(r.x,r.y,r.z)}getTangent(t,e){const n=e||new h.Vector3,i=this.knots[0]+t*(this.knots[this.knots.length-1]-this.knots[0]),r=zr(this.degree,this.knots,this.controlPoints,i,1);return n.copy(r[1]).normalize(),n}}let K,E,ne;class Xr extends h.Loader{constructor(t){super(t)}load(t,e,n,i){const r=this,s=r.path===""?h.LoaderUtils.extractUrlBase(t):r.path,a=new h.FileLoader(this.manager);a.setPath(r.path),a.setResponseType("arraybuffer"),a.setRequestHeader(r.requestHeader),a.setWithCredentials(r.withCredentials),a.load(t,function(l){try{e(r.parse(l,s))}catch(u){i?i(u):console.error(u),r.manager.itemError(t)}},n,i)}parse(t,e){if(jr(t))K=new Nr().parse(t);else{const i=Mn(t);if(!Rr(i))throw new Error("THREE.FBXLoader: Unknown format.");if(xn(i)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+xn(i));K=new Br().parse(i)}const n=new h.TextureLoader(this.manager).setPath(this.resourcePath||e).setCrossOrigin(this.crossOrigin);return new Ur(n,this.manager).parse(K)}}class Ur{constructor(t,e){this.textureLoader=t,this.manager=e}parse(){E=this.parseConnections();const t=this.parseImages(),e=this.parseTextures(t),n=this.parseMaterials(e),i=this.parseDeformers(),r=new Yr().parse(i);return this.parseScene(i,r,n),ne}parseConnections(){const t=new Map;return"Connections"in K&&K.Connections.connections.forEach(function(n){const i=n[0],r=n[1],s=n[2];t.has(i)||t.set(i,{parents:[],children:[]});const a={ID:r,relationship:s};t.get(i).parents.push(a),t.has(r)||t.set(r,{parents:[],children:[]});const l={ID:i,relationship:s};t.get(r).children.push(l)}),t}parseImages(){const t={},e={};if("Video"in K.Objects){const n=K.Objects.Video;for(const i in n){const r=n[i],s=parseInt(i);if(t[s]=r.RelativeFilename||r.Filename,"Content"in r){const a=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,l=typeof r.Content=="string"&&r.Content!=="";if(a||l){const u=this.parseImage(n[i]);e[r.RelativeFilename||r.Filename]=u}}}}for(const n in t){const i=t[n];e[i]!==void 0?t[n]=e[i]:t[n]=t[n].split("\\").pop()}return t}parseImage(t){const e=t.Content,n=t.RelativeFilename||t.Filename,i=n.slice(n.lastIndexOf(".")+1).toLowerCase();let r;switch(i){case"bmp":r="image/bmp";break;case"jpg":case"jpeg":r="image/jpeg";break;case"png":r="image/png";break;case"tif":r="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",n),r="image/tga";break;default:console.warn('FBXLoader: Image type "'+i+'" is not supported.');return}if(typeof e=="string")return"data:"+r+";base64,"+e;{const s=new Uint8Array(e);return window.URL.createObjectURL(new Blob([s],{type:r}))}}parseTextures(t){const e=new Map;if("Texture"in K.Objects){const n=K.Objects.Texture;for(const i in n){const r=this.parseTexture(n[i],t);e.set(parseInt(i),r)}}return e}parseTexture(t,e){const n=this.loadTexture(t,e);n.ID=t.id,n.name=t.attrName;const i=t.WrapModeU,r=t.WrapModeV,s=i!==void 0?i.value:0,a=r!==void 0?r.value:0;if(n.wrapS=s===0?h.RepeatWrapping:h.ClampToEdgeWrapping,n.wrapT=a===0?h.RepeatWrapping:h.ClampToEdgeWrapping,"Scaling"in t){const l=t.Scaling.value;n.repeat.x=l[0],n.repeat.y=l[1]}return n}loadTexture(t,e){let n;const i=this.textureLoader.path,r=E.get(t.id).children;r!==void 0&&r.length>0&&e[r[0].ID]!==void 0&&(n=e[r[0].ID],(n.indexOf("blob:")===0||n.indexOf("data:")===0)&&this.textureLoader.setPath(void 0));let s;const a=t.FileName.slice(-3).toLowerCase();if(a==="tga"){const l=this.manager.getHandler(".tga");l===null?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",t.RelativeFilename),s=new h.Texture):(l.setPath(this.textureLoader.path),s=l.load(n))}else a==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",t.RelativeFilename),s=new h.Texture):s=this.textureLoader.load(n);return this.textureLoader.setPath(i),s}parseMaterials(t){const e=new Map;if("Material"in K.Objects){const n=K.Objects.Material;for(const i in n){const r=this.parseMaterial(n[i],t);r!==null&&e.set(parseInt(i),r)}}return e}parseMaterial(t,e){const n=t.id,i=t.attrName;let r=t.ShadingModel;if(typeof r=="object"&&(r=r.value),!E.has(n))return null;const s=this.parseParameters(t,e,n);let a;switch(r.toLowerCase()){case"phong":a=new h.MeshPhongMaterial;break;case"lambert":a=new h.MeshLambertMaterial;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),a=new h.MeshPhongMaterial;break}return a.setValues(s),a.name=i,a}parseParameters(t,e,n){const i={};t.BumpFactor&&(i.bumpScale=t.BumpFactor.value),t.Diffuse?i.color=new h.Color().fromArray(t.Diffuse.value):t.DiffuseColor&&(t.DiffuseColor.type==="Color"||t.DiffuseColor.type==="ColorRGB")&&(i.color=new h.Color().fromArray(t.DiffuseColor.value)),t.DisplacementFactor&&(i.displacementScale=t.DisplacementFactor.value),t.Emissive?i.emissive=new h.Color().fromArray(t.Emissive.value):t.EmissiveColor&&(t.EmissiveColor.type==="Color"||t.EmissiveColor.type==="ColorRGB")&&(i.emissive=new h.Color().fromArray(t.EmissiveColor.value)),t.EmissiveFactor&&(i.emissiveIntensity=parseFloat(t.EmissiveFactor.value)),t.Opacity&&(i.opacity=parseFloat(t.Opacity.value)),i.opacity<1&&(i.transparent=!0),t.ReflectionFactor&&(i.reflectivity=t.ReflectionFactor.value),t.Shininess&&(i.shininess=t.Shininess.value),t.Specular?i.specular=new h.Color().fromArray(t.Specular.value):t.SpecularColor&&t.SpecularColor.type==="Color"&&(i.specular=new h.Color().fromArray(t.SpecularColor.value));const r=this;return E.get(n).children.forEach(function(s){const a=s.relationship;switch(a){case"Bump":i.bumpMap=r.getTexture(e,s.ID);break;case"Maya|TEX_ao_map":i.aoMap=r.getTexture(e,s.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":i.map=r.getTexture(e,s.ID),i.map!==void 0&&("colorSpace"in i.map?i.map.colorSpace="srgb":i.map.encoding=3001);break;case"DisplacementColor":i.displacementMap=r.getTexture(e,s.ID);break;case"EmissiveColor":i.emissiveMap=r.getTexture(e,s.ID),i.emissiveMap!==void 0&&("colorSpace"in i.emissiveMap?i.emissiveMap.colorSpace="srgb":i.emissiveMap.encoding=3001);break;case"NormalMap":case"Maya|TEX_normal_map":i.normalMap=r.getTexture(e,s.ID);break;case"ReflectionColor":i.envMap=r.getTexture(e,s.ID),i.envMap!==void 0&&(i.envMap.mapping=h.EquirectangularReflectionMapping,"colorSpace"in i.envMap?i.envMap.colorSpace="srgb":i.envMap.encoding=3001);break;case"SpecularColor":i.specularMap=r.getTexture(e,s.ID),i.specularMap!==void 0&&("colorSpace"in i.specularMap?i.specularMap.colorSpace="srgb":i.specularMap.encoding=3001);break;case"TransparentColor":case"TransparencyFactor":i.alphaMap=r.getTexture(e,s.ID),i.transparent=!0;break;case"AmbientColor":case"ShininessExponent":case"SpecularFactor":case"VectorDisplacementColor":default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",a);break}}),i}getTexture(t,e){return"LayeredTexture"in K.Objects&&e in K.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),e=E.get(e).children[0].ID),t.get(e)}parseDeformers(){const t={},e={};if("Deformer"in K.Objects){const n=K.Objects.Deformer;for(const i in n){const r=n[i],s=E.get(parseInt(i));if(r.attrType==="Skin"){const a=this.parseSkeleton(s,n);a.ID=i,s.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),a.geometryID=s.parents[0].ID,t[i]=a}else if(r.attrType==="BlendShape"){const a={id:i};a.rawTargets=this.parseMorphTargets(s,n),a.id=i,s.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),e[i]=a}}}return{skeletons:t,morphTargets:e}}parseSkeleton(t,e){const n=[];return t.children.forEach(function(i){const r=e[i.ID];if(r.attrType!=="Cluster")return;const s={ID:i.ID,indices:[],weights:[],transformLink:new h.Matrix4().fromArray(r.TransformLink.a)};"Indexes"in r&&(s.indices=r.Indexes.a,s.weights=r.Weights.a),n.push(s)}),{rawBones:n,bones:[]}}parseMorphTargets(t,e){const n=[];for(let i=0;i<t.children.length;i++){const r=t.children[i],s=e[r.ID],a={name:s.attrName,initialWeight:s.DeformPercent,id:s.id,fullWeights:s.FullWeights.a};if(s.attrType!=="BlendShapeChannel")return;a.geoID=E.get(parseInt(r.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,n.push(a)}return n}parseScene(t,e,n){ne=new h.Group;const i=this.parseModels(t.skeletons,e,n),r=K.Objects.Model,s=this;i.forEach(function(l){const u=r[l.ID];s.setLookAtProperties(l,u),E.get(l.ID).parents.forEach(function(c){const p=i.get(c.ID);p!==void 0&&p.add(l)}),l.parent===null&&ne.add(l)}),this.bindSkeleton(t.skeletons,e,i),this.createAmbientLight(),ne.traverse(function(l){if(l.userData.transformData){l.parent&&(l.userData.transformData.parentMatrix=l.parent.matrix,l.userData.transformData.parentMatrixWorld=l.parent.matrixWorld);const u=Ln(l.userData.transformData);l.applyMatrix4(u),l.updateWorldMatrix()}});const a=new Kr().parse();ne.children.length===1&&ne.children[0].isGroup&&(ne.children[0].animations=a,ne=ne.children[0]),ne.animations=a}parseModels(t,e,n){const i=new Map,r=K.Objects.Model;for(const s in r){const a=parseInt(s),l=r[s],u=E.get(a);let d=this.buildSkeleton(u,t,a,l.attrName);if(!d){switch(l.attrType){case"Camera":d=this.createCamera(u);break;case"Light":d=this.createLight(u);break;case"Mesh":d=this.createMesh(u,e,n);break;case"NurbsCurve":d=this.createCurve(u,e);break;case"LimbNode":case"Root":d=new h.Bone;break;case"Null":default:d=new h.Group;break}d.name=l.attrName?h.PropertyBinding.sanitizeNodeName(l.attrName):"",d.ID=a}this.getTransformData(d,l),i.set(a,d)}return i}buildSkeleton(t,e,n,i){let r=null;return t.parents.forEach(function(s){for(const a in e){const l=e[a];l.rawBones.forEach(function(u,d){if(u.ID===s.ID){const c=r;r=new h.Bone,r.matrixWorld.copy(u.transformLink),r.name=i?h.PropertyBinding.sanitizeNodeName(i):"",r.ID=n,l.bones[d]=r,c!==null&&r.add(c)}})}}),r}createCamera(t){let e,n;if(t.children.forEach(function(i){const r=K.Objects.NodeAttribute[i.ID];r!==void 0&&(n=r)}),n===void 0)e=new h.Object3D;else{let i=0;n.CameraProjectionType!==void 0&&n.CameraProjectionType.value===1&&(i=1);let r=1;n.NearPlane!==void 0&&(r=n.NearPlane.value/1e3);let s=1e3;n.FarPlane!==void 0&&(s=n.FarPlane.value/1e3);let a=window.innerWidth,l=window.innerHeight;n.AspectWidth!==void 0&&n.AspectHeight!==void 0&&(a=n.AspectWidth.value,l=n.AspectHeight.value);const u=a/l;let d=45;n.FieldOfView!==void 0&&(d=n.FieldOfView.value);const c=n.FocalLength?n.FocalLength.value:null;switch(i){case 0:e=new h.PerspectiveCamera(d,u,r,s),c!==null&&e.setFocalLength(c);break;case 1:e=new h.OrthographicCamera(-a/2,a/2,l/2,-l/2,r,s);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+i+"."),e=new h.Object3D;break}}return e}createLight(t){let e,n;if(t.children.forEach(function(i){const r=K.Objects.NodeAttribute[i.ID];r!==void 0&&(n=r)}),n===void 0)e=new h.Object3D;else{let i;n.LightType===void 0?i=0:i=n.LightType.value;let r=16777215;n.Color!==void 0&&(r=new h.Color().fromArray(n.Color.value));let s=n.Intensity===void 0?1:n.Intensity.value/100;n.CastLightOnObject!==void 0&&n.CastLightOnObject.value===0&&(s=0);let a=0;n.FarAttenuationEnd!==void 0&&(n.EnableFarAttenuation!==void 0&&n.EnableFarAttenuation.value===0?a=0:a=n.FarAttenuationEnd.value);const l=1;switch(i){case 0:e=new h.PointLight(r,s,a,l);break;case 1:e=new h.DirectionalLight(r,s);break;case 2:let u=Math.PI/3;n.InnerAngle!==void 0&&(u=h.MathUtils.degToRad(n.InnerAngle.value));let d=0;n.OuterAngle!==void 0&&(d=h.MathUtils.degToRad(n.OuterAngle.value),d=Math.max(d,1)),e=new h.SpotLight(r,s,a,u,d,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+n.LightType.value+", defaulting to a PointLight."),e=new h.PointLight(r,s);break}n.CastShadows!==void 0&&n.CastShadows.value===1&&(e.castShadow=!0)}return e}createMesh(t,e,n){let i,r=null,s=null;const a=[];return t.children.forEach(function(l){e.has(l.ID)&&(r=e.get(l.ID)),n.has(l.ID)&&a.push(n.get(l.ID))}),a.length>1?s=a:a.length>0?s=a[0]:(s=new h.MeshPhongMaterial({color:13421772}),a.push(s)),"color"in r.attributes&&a.forEach(function(l){l.vertexColors=!0}),r.FBX_Deformer?(i=new h.SkinnedMesh(r,s),i.normalizeSkinWeights()):i=new h.Mesh(r,s),i}createCurve(t,e){const n=t.children.reduce(function(r,s){return e.has(s.ID)&&(r=e.get(s.ID)),r},null),i=new h.LineBasicMaterial({color:3342591,linewidth:1});return new h.Line(n,i)}getTransformData(t,e){const n={};"InheritType"in e&&(n.inheritType=parseInt(e.InheritType.value)),"RotationOrder"in e?n.eulerOrder=Sn(e.RotationOrder.value):n.eulerOrder="ZYX","Lcl_Translation"in e&&(n.translation=e.Lcl_Translation.value),"PreRotation"in e&&(n.preRotation=e.PreRotation.value),"Lcl_Rotation"in e&&(n.rotation=e.Lcl_Rotation.value),"PostRotation"in e&&(n.postRotation=e.PostRotation.value),"Lcl_Scaling"in e&&(n.scale=e.Lcl_Scaling.value),"ScalingOffset"in e&&(n.scalingOffset=e.ScalingOffset.value),"ScalingPivot"in e&&(n.scalingPivot=e.ScalingPivot.value),"RotationOffset"in e&&(n.rotationOffset=e.RotationOffset.value),"RotationPivot"in e&&(n.rotationPivot=e.RotationPivot.value),t.userData.transformData=n}setLookAtProperties(t,e){"LookAtProperty"in e&&E.get(t.ID).children.forEach(function(i){if(i.relationship==="LookAtProperty"){const r=K.Objects.Model[i.ID];if("Lcl_Translation"in r){const s=r.Lcl_Translation.value;t.target!==void 0?(t.target.position.fromArray(s),ne.add(t.target)):t.lookAt(new h.Vector3().fromArray(s))}}})}bindSkeleton(t,e,n){const i=this.parsePoseNodes();for(const r in t){const s=t[r];E.get(parseInt(s.ID)).parents.forEach(function(l){if(e.has(l.ID)){const u=l.ID;E.get(u).parents.forEach(function(c){n.has(c.ID)&&n.get(c.ID).bind(new h.Skeleton(s.bones),i[c.ID])})}})}}parsePoseNodes(){const t={};if("Pose"in K.Objects){const e=K.Objects.Pose;for(const n in e)if(e[n].attrType==="BindPose"&&e[n].NbPoseNodes>0){const i=e[n].PoseNode;Array.isArray(i)?i.forEach(function(r){t[r.Node]=new h.Matrix4().fromArray(r.Matrix.a)}):t[i.Node]=new h.Matrix4().fromArray(i.Matrix.a)}}return t}createAmbientLight(){if("GlobalSettings"in K&&"AmbientColor"in K.GlobalSettings){const t=K.GlobalSettings.AmbientColor.value,e=t[0],n=t[1],i=t[2];if(e!==0||n!==0||i!==0){const r=new h.Color(e,n,i);ne.add(new h.AmbientLight(r,1))}}}}class Yr{parse(t){const e=new Map;if("Geometry"in K.Objects){const n=K.Objects.Geometry;for(const i in n){const r=E.get(parseInt(i)),s=this.parseGeometry(r,n[i],t);e.set(parseInt(i),s)}}return e}parseGeometry(t,e,n){switch(e.attrType){case"Mesh":return this.parseMeshGeometry(t,e,n);case"NurbsCurve":return this.parseNurbsGeometry(e)}}parseMeshGeometry(t,e,n){const i=n.skeletons,r=[],s=t.parents.map(function(c){return K.Objects.Model[c.ID]});if(s.length===0)return;const a=t.children.reduce(function(c,p){return i[p.ID]!==void 0&&(c=i[p.ID]),c},null);t.children.forEach(function(c){n.morphTargets[c.ID]!==void 0&&r.push(n.morphTargets[c.ID])});const l=s[0],u={};"RotationOrder"in l&&(u.eulerOrder=Sn(l.RotationOrder.value)),"InheritType"in l&&(u.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(u.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(u.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(u.scale=l.GeometricScaling.value);const d=Ln(u);return this.genGeometry(e,a,r,d)}genGeometry(t,e,n,i){const r=new h.BufferGeometry;t.attrName&&(r.name=t.attrName);const s=this.parseGeoNode(t,e),a=this.genBuffers(s),l=new h.Float32BufferAttribute(a.vertex,3);if(l.applyMatrix4(i),r.setAttribute("position",l),a.colors.length>0&&r.setAttribute("color",new h.Float32BufferAttribute(a.colors,3)),e&&(r.setAttribute("skinIndex",new h.Uint16BufferAttribute(a.weightsIndices,4)),r.setAttribute("skinWeight",new h.Float32BufferAttribute(a.vertexWeights,4)),r.FBX_Deformer=e),a.normal.length>0){const u=new h.Matrix3().getNormalMatrix(i),d=new h.Float32BufferAttribute(a.normal,3);d.applyNormalMatrix(u),r.setAttribute("normal",d)}if(a.uvs.forEach(function(u,d){Lt==="uv2"&&d++;const c=d===0?"uv":`uv${d}`;r.setAttribute(c,new h.Float32BufferAttribute(a.uvs[d],2))}),s.material&&s.material.mappingType!=="AllSame"){let u=a.materialIndex[0],d=0;if(a.materialIndex.forEach(function(c,p){c!==u&&(r.addGroup(d,p-d,u),u=c,d=p)}),r.groups.length>0){const c=r.groups[r.groups.length-1],p=c.start+c.count;p!==a.materialIndex.length&&r.addGroup(p,a.materialIndex.length-p,u)}r.groups.length===0&&r.addGroup(0,a.materialIndex.length,a.materialIndex[0])}return this.addMorphTargets(r,t,n,i),r}parseGeoNode(t,e){const n={};if(n.vertexPositions=t.Vertices!==void 0?t.Vertices.a:[],n.vertexIndices=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],t.LayerElementColor&&(n.color=this.parseVertexColors(t.LayerElementColor[0])),t.LayerElementMaterial&&(n.material=this.parseMaterialIndices(t.LayerElementMaterial[0])),t.LayerElementNormal&&(n.normal=this.parseNormals(t.LayerElementNormal[0])),t.LayerElementUV){n.uv=[];let i=0;for(;t.LayerElementUV[i];)t.LayerElementUV[i].UV&&n.uv.push(this.parseUVs(t.LayerElementUV[i])),i++}return n.weightTable={},e!==null&&(n.skeleton=e,e.rawBones.forEach(function(i,r){i.indices.forEach(function(s,a){n.weightTable[s]===void 0&&(n.weightTable[s]=[]),n.weightTable[s].push({id:r,weight:i.weights[a]})})})),n}genBuffers(t){const e={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let n=0,i=0,r=!1,s=[],a=[],l=[],u=[],d=[],c=[];const p=this;return t.vertexIndices.forEach(function(f,m){let v,g=!1;f<0&&(f=f^-1,g=!0);let b=[],y=[];if(s.push(f*3,f*3+1,f*3+2),t.color){const w=lt(m,n,f,t.color);l.push(w[0],w[1],w[2])}if(t.skeleton){if(t.weightTable[f]!==void 0&&t.weightTable[f].forEach(function(w){y.push(w.weight),b.push(w.id)}),y.length>4){r||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),r=!0);const w=[0,0,0,0],S=[0,0,0,0];y.forEach(function(P,I){let T=P,M=b[I];S.forEach(function(A,L,Z){if(T>A){Z[L]=T,T=A;const W=w[L];w[L]=M,M=W}})}),b=w,y=S}for(;y.length<4;)y.push(0),b.push(0);for(let w=0;w<4;++w)d.push(y[w]),c.push(b[w])}if(t.normal){const w=lt(m,n,f,t.normal);a.push(w[0],w[1],w[2])}t.material&&t.material.mappingType!=="AllSame"&&(v=lt(m,n,f,t.material)[0]),t.uv&&t.uv.forEach(function(w,S){const P=lt(m,n,f,w);u[S]===void 0&&(u[S]=[]),u[S].push(P[0]),u[S].push(P[1])}),i++,g&&(p.genFace(e,t,s,v,a,l,u,d,c,i),n++,i=0,s=[],a=[],l=[],u=[],d=[],c=[])}),e}genFace(t,e,n,i,r,s,a,l,u,d){for(let c=2;c<d;c++)t.vertex.push(e.vertexPositions[n[0]]),t.vertex.push(e.vertexPositions[n[1]]),t.vertex.push(e.vertexPositions[n[2]]),t.vertex.push(e.vertexPositions[n[(c-1)*3]]),t.vertex.push(e.vertexPositions[n[(c-1)*3+1]]),t.vertex.push(e.vertexPositions[n[(c-1)*3+2]]),t.vertex.push(e.vertexPositions[n[c*3]]),t.vertex.push(e.vertexPositions[n[c*3+1]]),t.vertex.push(e.vertexPositions[n[c*3+2]]),e.skeleton&&(t.vertexWeights.push(l[0]),t.vertexWeights.push(l[1]),t.vertexWeights.push(l[2]),t.vertexWeights.push(l[3]),t.vertexWeights.push(l[(c-1)*4]),t.vertexWeights.push(l[(c-1)*4+1]),t.vertexWeights.push(l[(c-1)*4+2]),t.vertexWeights.push(l[(c-1)*4+3]),t.vertexWeights.push(l[c*4]),t.vertexWeights.push(l[c*4+1]),t.vertexWeights.push(l[c*4+2]),t.vertexWeights.push(l[c*4+3]),t.weightsIndices.push(u[0]),t.weightsIndices.push(u[1]),t.weightsIndices.push(u[2]),t.weightsIndices.push(u[3]),t.weightsIndices.push(u[(c-1)*4]),t.weightsIndices.push(u[(c-1)*4+1]),t.weightsIndices.push(u[(c-1)*4+2]),t.weightsIndices.push(u[(c-1)*4+3]),t.weightsIndices.push(u[c*4]),t.weightsIndices.push(u[c*4+1]),t.weightsIndices.push(u[c*4+2]),t.weightsIndices.push(u[c*4+3])),e.color&&(t.colors.push(s[0]),t.colors.push(s[1]),t.colors.push(s[2]),t.colors.push(s[(c-1)*3]),t.colors.push(s[(c-1)*3+1]),t.colors.push(s[(c-1)*3+2]),t.colors.push(s[c*3]),t.colors.push(s[c*3+1]),t.colors.push(s[c*3+2])),e.material&&e.material.mappingType!=="AllSame"&&(t.materialIndex.push(i),t.materialIndex.push(i),t.materialIndex.push(i)),e.normal&&(t.normal.push(r[0]),t.normal.push(r[1]),t.normal.push(r[2]),t.normal.push(r[(c-1)*3]),t.normal.push(r[(c-1)*3+1]),t.normal.push(r[(c-1)*3+2]),t.normal.push(r[c*3]),t.normal.push(r[c*3+1]),t.normal.push(r[c*3+2])),e.uv&&e.uv.forEach(function(p,f){t.uvs[f]===void 0&&(t.uvs[f]=[]),t.uvs[f].push(a[f][0]),t.uvs[f].push(a[f][1]),t.uvs[f].push(a[f][(c-1)*2]),t.uvs[f].push(a[f][(c-1)*2+1]),t.uvs[f].push(a[f][c*2]),t.uvs[f].push(a[f][c*2+1])})}addMorphTargets(t,e,n,i){if(n.length===0)return;t.morphTargetsRelative=!0,t.morphAttributes.position=[];const r=this;n.forEach(function(s){s.rawTargets.forEach(function(a){const l=K.Objects.Geometry[a.geoID];l!==void 0&&r.genMorphGeometry(t,e,l,i,a.name)})})}genMorphGeometry(t,e,n,i,r){const s=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],a=n.Vertices!==void 0?n.Vertices.a:[],l=n.Indexes!==void 0?n.Indexes.a:[],u=t.attributes.position.count*3,d=new Float32Array(u);for(let m=0;m<l.length;m++){const v=l[m]*3;d[v]=a[m*3],d[v+1]=a[m*3+1],d[v+2]=a[m*3+2]}const c={vertexIndices:s,vertexPositions:d},p=this.genBuffers(c),f=new h.Float32BufferAttribute(p.vertex,3);f.name=r||n.attrName,f.applyMatrix4(i),t.morphAttributes.position.push(f)}parseNormals(t){const e=t.MappingInformationType,n=t.ReferenceInformationType,i=t.Normals.a;let r=[];return n==="IndexToDirect"&&("NormalIndex"in t?r=t.NormalIndex.a:"NormalsIndex"in t&&(r=t.NormalsIndex.a)),{dataSize:3,buffer:i,indices:r,mappingType:e,referenceType:n}}parseUVs(t){const e=t.MappingInformationType,n=t.ReferenceInformationType,i=t.UV.a;let r=[];return n==="IndexToDirect"&&(r=t.UVIndex.a),{dataSize:2,buffer:i,indices:r,mappingType:e,referenceType:n}}parseVertexColors(t){const e=t.MappingInformationType,n=t.ReferenceInformationType,i=t.Colors.a;let r=[];return n==="IndexToDirect"&&(r=t.ColorIndex.a),{dataSize:4,buffer:i,indices:r,mappingType:e,referenceType:n}}parseMaterialIndices(t){const e=t.MappingInformationType,n=t.ReferenceInformationType;if(e==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:n};const i=t.Materials.a,r=[];for(let s=0;s<i.length;++s)r.push(s);return{dataSize:1,buffer:i,indices:r,mappingType:e,referenceType:n}}parseNurbsGeometry(t){if(bn===void 0)return console.error("THREE.FBXLoader: The loader relies on NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry."),new h.BufferGeometry;const e=parseInt(t.Order);if(isNaN(e))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",t.Order,t.id),new h.BufferGeometry;const n=e-1,i=t.KnotVector.a,r=[],s=t.Points.a;for(let c=0,p=s.length;c<p;c+=4)r.push(new h.Vector4().fromArray(s,c));let a,l;if(t.Form==="Closed")r.push(r[0]);else if(t.Form==="Periodic"){a=n,l=i.length-1-a;for(let c=0;c<n;++c)r.push(r[c])}const d=new bn(n,i,r,a,l).getPoints(r.length*12);return new h.BufferGeometry().setFromPoints(d)}}class Kr{parse(){const t=[],e=this.parseClips();if(e!==void 0)for(const n in e){const i=e[n],r=this.addClip(i);t.push(r)}return t}parseClips(){if(K.Objects.AnimationCurve===void 0)return;const t=this.parseAnimationCurveNodes();this.parseAnimationCurves(t);const e=this.parseAnimationLayers(t);return this.parseAnimStacks(e)}parseAnimationCurveNodes(){const t=K.Objects.AnimationCurveNode,e=new Map;for(const n in t){const i=t[n];if(i.attrName.match(/S|R|T|DeformPercent/)!==null){const r={id:i.id,attr:i.attrName,curves:{}};e.set(r.id,r)}}return e}parseAnimationCurves(t){const e=K.Objects.AnimationCurve;for(const n in e){const i={id:e[n].id,times:e[n].KeyTime.a.map(Jr),values:e[n].KeyValueFloat.a},r=E.get(i.id);if(r!==void 0){const s=r.parents[0].ID,a=r.parents[0].relationship;a.match(/X/)?t.get(s).curves.x=i:a.match(/Y/)?t.get(s).curves.y=i:a.match(/Z/)?t.get(s).curves.z=i:a.match(/d|DeformPercent/)&&t.has(s)&&(t.get(s).curves.morph=i)}}}parseAnimationLayers(t){const e=K.Objects.AnimationLayer,n=new Map;for(const i in e){const r=[],s=E.get(parseInt(i));s!==void 0&&(s.children.forEach(function(l,u){if(t.has(l.ID)){const d=t.get(l.ID);if(d.curves.x!==void 0||d.curves.y!==void 0||d.curves.z!==void 0){if(r[u]===void 0){const c=E.get(l.ID).parents.filter(function(p){return p.relationship!==void 0})[0].ID;if(c!==void 0){const p=K.Objects.Model[c.toString()];if(p===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const f={modelName:p.attrName?h.PropertyBinding.sanitizeNodeName(p.attrName):"",ID:p.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ne.traverse(function(m){m.ID===p.id&&(f.transform=m.matrix,m.userData.transformData&&(f.eulerOrder=m.userData.transformData.eulerOrder))}),f.transform||(f.transform=new h.Matrix4),"PreRotation"in p&&(f.preRotation=p.PreRotation.value),"PostRotation"in p&&(f.postRotation=p.PostRotation.value),r[u]=f}}r[u]&&(r[u][d.attr]=d)}else if(d.curves.morph!==void 0){if(r[u]===void 0){const c=E.get(l.ID).parents.filter(function(b){return b.relationship!==void 0})[0].ID,p=E.get(c).parents[0].ID,f=E.get(p).parents[0].ID,m=E.get(f).parents[0].ID,v=K.Objects.Model[m],g={modelName:v.attrName?h.PropertyBinding.sanitizeNodeName(v.attrName):"",morphName:K.Objects.Deformer[c].attrName};r[u]=g}r[u][d.attr]=d}}}),n.set(parseInt(i),r))}return n}parseAnimStacks(t){const e=K.Objects.AnimationStack,n={};for(const i in e){const r=E.get(parseInt(i)).children;r.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const s=t.get(r[0].ID);n[i]={name:e[i].attrName,layer:s}}return n}addClip(t){let e=[];const n=this;return t.layer.forEach(function(i){e=e.concat(n.generateTracks(i))}),new h.AnimationClip(t.name,-1,e)}generateTracks(t){const e=[];let n=new h.Vector3,i=new h.Quaternion,r=new h.Vector3;if(t.transform&&t.transform.decompose(n,i,r),n=n.toArray(),i=new h.Euler().setFromQuaternion(i,t.eulerOrder).toArray(),r=r.toArray(),t.T!==void 0&&Object.keys(t.T.curves).length>0){const s=this.generateVectorTrack(t.modelName,t.T.curves,n,"position");s!==void 0&&e.push(s)}if(t.R!==void 0&&Object.keys(t.R.curves).length>0){const s=this.generateRotationTrack(t.modelName,t.R.curves,i,t.preRotation,t.postRotation,t.eulerOrder);s!==void 0&&e.push(s)}if(t.S!==void 0&&Object.keys(t.S.curves).length>0){const s=this.generateVectorTrack(t.modelName,t.S.curves,r,"scale");s!==void 0&&e.push(s)}if(t.DeformPercent!==void 0){const s=this.generateMorphTrack(t);s!==void 0&&e.push(s)}return e}generateVectorTrack(t,e,n,i){const r=this.getTimesForAllAxes(e),s=this.getKeyframeTrackValues(r,e,n);return new h.VectorKeyframeTrack(t+"."+i,r,s)}generateRotationTrack(t,e,n,i,r,s){e.x!==void 0&&(this.interpolateRotations(e.x),e.x.values=e.x.values.map(h.MathUtils.degToRad)),e.y!==void 0&&(this.interpolateRotations(e.y),e.y.values=e.y.values.map(h.MathUtils.degToRad)),e.z!==void 0&&(this.interpolateRotations(e.z),e.z.values=e.z.values.map(h.MathUtils.degToRad));const a=this.getTimesForAllAxes(e),l=this.getKeyframeTrackValues(a,e,n);i!==void 0&&(i=i.map(h.MathUtils.degToRad),i.push(s),i=new h.Euler().fromArray(i),i=new h.Quaternion().setFromEuler(i)),r!==void 0&&(r=r.map(h.MathUtils.degToRad),r.push(s),r=new h.Euler().fromArray(r),r=new h.Quaternion().setFromEuler(r).invert());const u=new h.Quaternion,d=new h.Euler,c=[];for(let p=0;p<l.length;p+=3)d.set(l[p],l[p+1],l[p+2],s),u.setFromEuler(d),i!==void 0&&u.premultiply(i),r!==void 0&&u.multiply(r),u.toArray(c,p/3*4);return new h.QuaternionKeyframeTrack(t+".quaternion",a,c)}generateMorphTrack(t){const e=t.DeformPercent.curves.morph,n=e.values.map(function(r){return r/100}),i=ne.getObjectByName(t.modelName).morphTargetDictionary[t.morphName];return new h.NumberKeyframeTrack(t.modelName+".morphTargetInfluences["+i+"]",e.times,n)}getTimesForAllAxes(t){let e=[];if(t.x!==void 0&&(e=e.concat(t.x.times)),t.y!==void 0&&(e=e.concat(t.y.times)),t.z!==void 0&&(e=e.concat(t.z.times)),e=e.sort(function(n,i){return n-i}),e.length>1){let n=1,i=e[0];for(let r=1;r<e.length;r++){const s=e[r];s!==i&&(e[n]=s,i=s,n++)}e=e.slice(0,n)}return e}getKeyframeTrackValues(t,e,n){const i=n,r=[];let s=-1,a=-1,l=-1;return t.forEach(function(u){if(e.x&&(s=e.x.times.indexOf(u)),e.y&&(a=e.y.times.indexOf(u)),e.z&&(l=e.z.times.indexOf(u)),s!==-1){const d=e.x.values[s];r.push(d),i[0]=d}else r.push(i[0]);if(a!==-1){const d=e.y.values[a];r.push(d),i[1]=d}else r.push(i[1]);if(l!==-1){const d=e.z.values[l];r.push(d),i[2]=d}else r.push(i[2])}),r}interpolateRotations(t){for(let e=1;e<t.values.length;e++){const n=t.values[e-1],i=t.values[e]-n,r=Math.abs(i);if(r>=180){const s=r/180,a=i/s;let l=n+a;const u=t.times[e-1],c=(t.times[e]-u)/s;let p=u+c;const f=[],m=[];for(;p<t.times[e];)f.push(p),p+=c,m.push(l),l+=a;t.times=_n(t.times,e,f),t.values=_n(t.values,e,m)}}}}class Br{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(t){this.nodeStack.push(t),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(t,e){this.currentProp=t,this.currentPropName=e}parse(t){this.currentIndent=0,this.allNodes=new wn,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const e=this,n=t.split(/[\r\n]+/);return n.forEach(function(i,r){const s=i.match(/^[\s\t]*;/),a=i.match(/^[\s\t]*$/);if(s||a)return;const l=i.match("^\\t{"+e.currentIndent+"}(\\w+):(.*){",""),u=i.match("^\\t{"+e.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),d=i.match("^\\t{"+(e.currentIndent-1)+"}}");l?e.parseNodeBegin(i,l):u?e.parseNodeProperty(i,u,n[++r]):d?e.popStack():i.match(/^[^\s\t}]/)&&e.parseNodePropertyContinued(i)}),this.allNodes}parseNodeBegin(t,e){const n=e[1].trim().replace(/^"/,"").replace(/"$/,""),i=e[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),r={name:n},s=this.parseNodeAttr(i),a=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(n,r):n in a?(n==="PoseNode"?a.PoseNode.push(r):a[n].id!==void 0&&(a[n]={},a[n][a[n].id]=a[n]),s.id!==""&&(a[n][s.id]=r)):typeof s.id=="number"?(a[n]={},a[n][s.id]=r):n!=="Properties70"&&(n==="PoseNode"?a[n]=[r]:a[n]=r),typeof s.id=="number"&&(r.id=s.id),s.name!==""&&(r.attrName=s.name),s.type!==""&&(r.attrType=s.type),this.pushStack(r)}parseNodeAttr(t){let e=t[0];t[0]!==""&&(e=parseInt(t[0]),isNaN(e)&&(e=t[0]));let n="",i="";return t.length>1&&(n=t[1].replace(/^(\w+)::/,""),i=t[2]),{id:e,name:n,type:i}}parseNodeProperty(t,e,n){let i=e[1].replace(/^"/,"").replace(/"$/,"").trim(),r=e[2].replace(/^"/,"").replace(/"$/,"").trim();i==="Content"&&r===","&&(r=n.replace(/"/g,"").replace(/,$/,"").trim());const s=this.getCurrentNode();if(s.name==="Properties70"){this.parseNodeSpecialProperty(t,i,r);return}if(i==="C"){const l=r.split(",").slice(1),u=parseInt(l[0]),d=parseInt(l[1]);let c=r.split(",").slice(3);c=c.map(function(p){return p.trim().replace(/^"/,"")}),i="connections",r=[u,d],Hr(r,c),s[i]===void 0&&(s[i]=[])}i==="Node"&&(s.id=r),i in s&&Array.isArray(s[i])?s[i].push(r):i!=="a"?s[i]=r:s.a=r,this.setCurrentProp(s,i),i==="a"&&r.slice(-1)!==","&&(s.a=Vt(r))}parseNodePropertyContinued(t){const e=this.getCurrentNode();e.a+=t,t.slice(-1)!==","&&(e.a=Vt(e.a))}parseNodeSpecialProperty(t,e,n){const i=n.split('",').map(function(d){return d.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=i[0],s=i[1],a=i[2],l=i[3];let u=i[4];switch(s){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":u=parseFloat(u);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":u=Vt(u);break}this.getPrevNode()[r]={type:s,type2:a,flag:l,value:u},this.setCurrentProp(this.getPrevNode(),r)}}class Nr{parse(t){const e=new vn(t);e.skip(23);const n=e.getUint32();if(n<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+n);const i=new wn;for(;!this.endOfContent(e);){const r=this.parseNode(e,n);r!==null&&i.add(r.name,r)}return i}endOfContent(t){return t.size()%16===0?(t.getOffset()+160+16&-16)>=t.size():t.getOffset()+160+16>=t.size()}parseNode(t,e){const n={},i=e>=7500?t.getUint64():t.getUint32(),r=e>=7500?t.getUint64():t.getUint32();e>=7500?t.getUint64():t.getUint32();const s=t.getUint8(),a=t.getString(s);if(i===0)return null;const l=[];for(let p=0;p<r;p++)l.push(this.parseProperty(t));const u=l.length>0?l[0]:"",d=l.length>1?l[1]:"",c=l.length>2?l[2]:"";for(n.singleProperty=r===1&&t.getOffset()===i;i>t.getOffset();){const p=this.parseNode(t,e);p!==null&&this.parseSubNode(a,n,p)}return n.propertyList=l,typeof u=="number"&&(n.id=u),d!==""&&(n.attrName=d),c!==""&&(n.attrType=c),a!==""&&(n.name=a),n}parseSubNode(t,e,n){if(n.singleProperty===!0){const i=n.propertyList[0];Array.isArray(i)?(e[n.name]=n,n.a=i):e[n.name]=i}else if(t==="Connections"&&n.name==="C"){const i=[];n.propertyList.forEach(function(r,s){s!==0&&i.push(r)}),e.connections===void 0&&(e.connections=[]),e.connections.push(i)}else if(n.name==="Properties70")Object.keys(n).forEach(function(r){e[r]=n[r]});else if(t==="Properties70"&&n.name==="P"){let i=n.propertyList[0],r=n.propertyList[1];const s=n.propertyList[2],a=n.propertyList[3];let l;i.indexOf("Lcl ")===0&&(i=i.replace("Lcl ","Lcl_")),r.indexOf("Lcl ")===0&&(r=r.replace("Lcl ","Lcl_")),r==="Color"||r==="ColorRGB"||r==="Vector"||r==="Vector3D"||r.indexOf("Lcl_")===0?l=[n.propertyList[4],n.propertyList[5],n.propertyList[6]]:l=n.propertyList[4],e[i]={type:r,type2:s,flag:a,value:l}}else e[n.name]===void 0?typeof n.id=="number"?(e[n.name]={},e[n.name][n.id]=n):e[n.name]=n:n.name==="PoseNode"?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(n)):e[n.name][n.id]===void 0&&(e[n.name][n.id]=n)}parseProperty(t){const e=t.getString(1);let n;switch(e){case"C":return t.getBoolean();case"D":return t.getFloat64();case"F":return t.getFloat32();case"I":return t.getInt32();case"L":return t.getInt64();case"R":return n=t.getUint32(),t.getArrayBuffer(n);case"S":return n=t.getUint32(),t.getString(n);case"Y":return t.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const i=t.getUint32(),r=t.getUint32(),s=t.getUint32();if(r===0)switch(e){case"b":case"c":return t.getBooleanArray(i);case"d":return t.getFloat64Array(i);case"f":return t.getFloat32Array(i);case"i":return t.getInt32Array(i);case"l":return t.getInt64Array(i)}const a=Oi(new Uint8Array(t.getArrayBuffer(s))),l=new vn(a.buffer);switch(e){case"b":case"c":return l.getBooleanArray(i);case"d":return l.getFloat64Array(i);case"f":return l.getFloat32Array(i);case"i":return l.getInt32Array(i);case"l":return l.getInt64Array(i)}default:throw new Error("THREE.FBXLoader: Unknown property type "+e)}}}class vn{constructor(t,e){this.dv=new DataView(t),this.offset=0,this.littleEndian=e!==void 0?e:!0}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(t){this.offset+=t}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(t){const e=[];for(let n=0;n<t;n++)e.push(this.getBoolean());return e}getUint8(){const t=this.dv.getUint8(this.offset);return this.offset+=1,t}getInt16(){const t=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}getInt32(){const t=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}getInt32Array(t){const e=[];for(let n=0;n<t;n++)e.push(this.getInt32());return e}getUint32(){const t=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}getInt64(){let t,e;return this.littleEndian?(t=this.getUint32(),e=this.getUint32()):(e=this.getUint32(),t=this.getUint32()),e&2147483648?(e=~e&4294967295,t=~t&4294967295,t===4294967295&&(e=e+1&4294967295),t=t+1&4294967295,-(e*4294967296+t)):e*4294967296+t}getInt64Array(t){const e=[];for(let n=0;n<t;n++)e.push(this.getInt64());return e}getUint64(){let t,e;return this.littleEndian?(t=this.getUint32(),e=this.getUint32()):(e=this.getUint32(),t=this.getUint32()),e*4294967296+t}getFloat32(){const t=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}getFloat32Array(t){const e=[];for(let n=0;n<t;n++)e.push(this.getFloat32());return e}getFloat64(){const t=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}getFloat64Array(t){const e=[];for(let n=0;n<t;n++)e.push(this.getFloat64());return e}getArrayBuffer(t){const e=this.dv.buffer.slice(this.offset,this.offset+t);return this.offset+=t,e}getString(t){let e=[];for(let i=0;i<t;i++)e[i]=this.getUint8();const n=e.indexOf(0);return n>=0&&(e=e.slice(0,n)),ze(new Uint8Array(e))}}class wn{add(t,e){this[t]=e}}function jr(o){const t="Kaydara FBX Binary \0";return o.byteLength>=t.length&&t===Mn(o,0,t.length)}function Rr(o){const t=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let e=0;function n(i){const r=o[i-1];return o=o.slice(e+i),e++,r}for(let i=0;i<t.length;++i)if(n(1)===t[i])return!1;return!0}function xn(o){const t=/FBXVersion: (\d+)/,e=o.match(t);if(e)return parseInt(e[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function Jr(o){return o/46186158e3}const Qr=[];function lt(o,t,e,n){let i;switch(n.mappingType){case"ByPolygonVertex":i=o;break;case"ByPolygon":i=t;break;case"ByVertice":i=e;break;case"AllSame":i=n.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+n.mappingType)}n.referenceType==="IndexToDirect"&&(i=n.indices[i]);const r=i*n.dataSize,s=r+n.dataSize;return Er(Qr,n.buffer,r,s)}const Gt=new h.Euler,Ue=new h.Vector3;function Ln(o){const t=new h.Matrix4,e=new h.Matrix4,n=new h.Matrix4,i=new h.Matrix4,r=new h.Matrix4,s=new h.Matrix4,a=new h.Matrix4,l=new h.Matrix4,u=new h.Matrix4,d=new h.Matrix4,c=new h.Matrix4,p=new h.Matrix4,f=o.inheritType?o.inheritType:0;if(o.translation&&t.setPosition(Ue.fromArray(o.translation)),o.preRotation){const L=o.preRotation.map(h.MathUtils.degToRad);L.push(o.eulerOrder),e.makeRotationFromEuler(Gt.fromArray(L))}if(o.rotation){const L=o.rotation.map(h.MathUtils.degToRad);L.push(o.eulerOrder),n.makeRotationFromEuler(Gt.fromArray(L))}if(o.postRotation){const L=o.postRotation.map(h.MathUtils.degToRad);L.push(o.eulerOrder),i.makeRotationFromEuler(Gt.fromArray(L)),i.invert()}o.scale&&r.scale(Ue.fromArray(o.scale)),o.scalingOffset&&a.setPosition(Ue.fromArray(o.scalingOffset)),o.scalingPivot&&s.setPosition(Ue.fromArray(o.scalingPivot)),o.rotationOffset&&l.setPosition(Ue.fromArray(o.rotationOffset)),o.rotationPivot&&u.setPosition(Ue.fromArray(o.rotationPivot)),o.parentMatrixWorld&&(c.copy(o.parentMatrix),d.copy(o.parentMatrixWorld));const m=e.clone().multiply(n).multiply(i),v=new h.Matrix4;v.extractRotation(d);const g=new h.Matrix4;g.copyPosition(d);const b=g.clone().invert().multiply(d),y=v.clone().invert().multiply(b),w=r,S=new h.Matrix4;if(f===0)S.copy(v).multiply(m).multiply(y).multiply(w);else if(f===1)S.copy(v).multiply(y).multiply(m).multiply(w);else{const Z=new h.Matrix4().scale(new h.Vector3().setFromMatrixScale(c)).clone().invert(),W=y.clone().multiply(Z);S.copy(v).multiply(m).multiply(W).multiply(w)}const P=u.clone().invert(),I=s.clone().invert();let T=t.clone().multiply(l).multiply(u).multiply(e).multiply(n).multiply(i).multiply(P).multiply(a).multiply(s).multiply(r).multiply(I);const M=new h.Matrix4().copyPosition(T),A=d.clone().multiply(M);return p.copyPosition(A),T=p.clone().multiply(S),T.premultiply(d.invert()),T}function Sn(o){o=o||0;const t=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return o===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),t[0]):t[o]}function Vt(o){return o.split(",").map(function(e){return parseFloat(e)})}function Mn(o,t,e){return t===void 0&&(t=0),e===void 0&&(e=o.byteLength),ze(new Uint8Array(o,t,e))}function Hr(o,t){for(let e=0,n=o.length,i=t.length;e<i;e++,n++)o[n]=t[e]}function Er(o,t,e,n){for(let i=e,r=0;i<n;i++,r++)o[r]=t[i];return o}function _n(o,t,e){return o.slice(0,t).concat(e).concat(o.slice(t))}class qr extends h.DataTextureLoader{constructor(t){super(t),this.type=h.HalfFloatType}parse(t){const s=function(M,A){switch(M){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(A||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(A||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(A||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(A||""))}},d=`
98
+ `,c=function(M,A,L){A=A||1024;let W=M.pos,C=-1,V=0,D="",G=String.fromCharCode.apply(null,new Uint16Array(M.subarray(W,W+128)));for(;0>(C=G.indexOf(d))&&V<A&&W<M.byteLength;)D+=G,V+=G.length,W+=128,G+=String.fromCharCode.apply(null,new Uint16Array(M.subarray(W,W+128)));return-1<C?(M.pos+=V+C+1,D+G.slice(0,C)):!1},p=function(M){const A=/^#\?(\S+)/,L=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,Z=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,W=/^\s*FORMAT=(\S+)\s*$/,C=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,V={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let D,G;for((M.pos>=M.byteLength||!(D=c(M)))&&s(1,"no header found"),(G=D.match(A))||s(3,"bad initial token"),V.valid|=1,V.programtype=G[1],V.string+=D+`
99
+ `;D=c(M),D!==!1;){if(V.string+=D+`
100
+ `,D.charAt(0)==="#"){V.comments+=D+`
101
+ `;continue}if((G=D.match(L))&&(V.gamma=parseFloat(G[1])),(G=D.match(Z))&&(V.exposure=parseFloat(G[1])),(G=D.match(W))&&(V.valid|=2,V.format=G[1]),(G=D.match(C))&&(V.valid|=4,V.height=parseInt(G[1],10),V.width=parseInt(G[2],10)),V.valid&2&&V.valid&4)break}return V.valid&2||s(3,"missing format specifier"),V.valid&4||s(3,"missing image size specifier"),V},f=function(M,A,L){const Z=A;if(Z<8||Z>32767||M[0]!==2||M[1]!==2||M[2]&128)return new Uint8Array(M);Z!==(M[2]<<8|M[3])&&s(3,"wrong scanline width");const W=new Uint8Array(4*A*L);W.length||s(4,"unable to allocate buffer space");let C=0,V=0;const D=4*Z,G=new Uint8Array(4),X=new Uint8Array(D);let U=L;for(;U>0&&V<M.byteLength;){V+4>M.byteLength&&s(1),G[0]=M[V++],G[1]=M[V++],G[2]=M[V++],G[3]=M[V++],(G[0]!=2||G[1]!=2||(G[2]<<8|G[3])!=Z)&&s(3,"bad rgbe scanline format");let z=0,j;for(;z<D&&V<M.byteLength;){j=M[V++];const B=j>128;if(B&&(j-=128),(j===0||z+j>D)&&s(3,"bad scanline data"),B){const J=M[V++];for(let de=0;de<j;de++)X[z++]=J}else X.set(M.subarray(V,V+j),z),z+=j,V+=j}const H=Z;for(let B=0;B<H;B++){let J=0;W[C]=X[B+J],J+=Z,W[C+1]=X[B+J],J+=Z,W[C+2]=X[B+J],J+=Z,W[C+3]=X[B+J],C+=4}U--}return W},m=function(M,A,L,Z){const W=M[A+3],C=Math.pow(2,W-128)/255;L[Z+0]=M[A+0]*C,L[Z+1]=M[A+1]*C,L[Z+2]=M[A+2]*C,L[Z+3]=1},v=function(M,A,L,Z){const W=M[A+3],C=Math.pow(2,W-128)/255;L[Z+0]=h.DataUtils.toHalfFloat(Math.min(M[A+0]*C,65504)),L[Z+1]=h.DataUtils.toHalfFloat(Math.min(M[A+1]*C,65504)),L[Z+2]=h.DataUtils.toHalfFloat(Math.min(M[A+2]*C,65504)),L[Z+3]=h.DataUtils.toHalfFloat(1)},g=new Uint8Array(t);g.pos=0;const b=p(g),y=b.width,w=b.height,S=f(g.subarray(g.pos),y,w);let P,I,T;switch(this.type){case h.FloatType:T=S.length/4;const M=new Float32Array(T*4);for(let L=0;L<T;L++)m(S,L*4,M,L*4);P=M,I=h.FloatType;break;case h.HalfFloatType:T=S.length/4;const A=new Uint16Array(T*4);for(let L=0;L<T;L++)v(S,L*4,A,L*4);P=A,I=h.HalfFloatType;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:y,height:w,data:P,header:b.string,gamma:b.gamma,exposure:b.exposure,type:I}}setDataType(t){return this.type=t,this}load(t,e,n,i){function r(s,a){switch(s.type){case h.FloatType:case h.HalfFloatType:"colorSpace"in s?s.colorSpace="srgb-linear":s.encoding=3e3,s.minFilter=h.LinearFilter,s.magFilter=h.LinearFilter,s.generateMipmaps=!1,s.flipY=!0;break}e&&e(s,a)}return super.load(t,r,n,i)}}const Ct=new WeakMap;class $r extends h.Loader{constructor(t){super(t),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(t){return this.decoderPath=t,this}setDecoderConfig(t){return this.decoderConfig=t,this}setWorkerLimit(t){return this.workerLimit=t,this}load(t,e,n,i){const r=new h.FileLoader(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(t,s=>{const a={attributeIDs:this.defaultAttributeIDs,attributeTypes:this.defaultAttributeTypes,useUniqueIDs:!1};this.decodeGeometry(s,a).then(e).catch(i)},n,i)}decodeDracoFile(t,e,n,i){const r={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!n};this.decodeGeometry(t,r).then(e)}decodeGeometry(t,e){for(const l in e.attributeTypes){const u=e.attributeTypes[l];u.BYTES_PER_ELEMENT!==void 0&&(e.attributeTypes[l]=u.name)}const n=JSON.stringify(e);if(Ct.has(t)){const l=Ct.get(t);if(l.key===n)return l.promise;if(t.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i;const r=this.workerNextTaskID++,s=t.byteLength,a=this._getWorker(r,s).then(l=>(i=l,new Promise((u,d)=>{i._callbacks[r]={resolve:u,reject:d},i.postMessage({type:"decode",id:r,taskConfig:e,buffer:t},[t])}))).then(l=>this._createGeometry(l.geometry));return a.catch(()=>!0).then(()=>{i&&r&&this._releaseTask(i,r)}),Ct.set(t,{key:n,promise:a}),a}_createGeometry(t){const e=new h.BufferGeometry;t.index&&e.setIndex(new h.BufferAttribute(t.index.array,1));for(let n=0;n<t.attributes.length;n++){const i=t.attributes[n],r=i.name,s=i.array,a=i.itemSize;e.setAttribute(r,new h.BufferAttribute(s,a))}return e}_loadLibrary(t,e){const n=new h.FileLoader(this.manager);return n.setPath(this.decoderPath),n.setResponseType(e),n.setWithCredentials(this.withCredentials),new Promise((i,r)=>{n.load(t,i,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const t=typeof WebAssembly!="object"||this.decoderConfig.type==="js",e=[];return t?e.push(this._loadLibrary("draco_decoder.js","text")):(e.push(this._loadLibrary("draco_wasm_wrapper.js","text")),e.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(e).then(n=>{const i=n[0];t||(this.decoderConfig.wasmBinary=n[1]);const r=es.toString(),s=["/* draco decoder */",i,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
102
+ `);this.workerSourceURL=URL.createObjectURL(new Blob([s]))}),this.decoderPending}_getWorker(t,e){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const i=new Worker(this.workerSourceURL);i._callbacks={},i._taskCosts={},i._taskLoad=0,i.postMessage({type:"init",decoderConfig:this.decoderConfig}),i.onmessage=function(r){const s=r.data;switch(s.type){case"decode":i._callbacks[s.id].resolve(s);break;case"error":i._callbacks[s.id].reject(s);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+s.type+'"')}},this.workerPool.push(i)}else this.workerPool.sort(function(i,r){return i._taskLoad>r._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[t]=e,n._taskLoad+=e,n})}_releaseTask(t,e){t._taskLoad-=t._taskCosts[e],delete t._callbacks[e],delete t._taskCosts[e]}debug(){console.log("Task load: ",this.workerPool.map(t=>t._taskLoad))}dispose(){for(let t=0;t<this.workerPool.length;++t)this.workerPool[t].terminate();return this.workerPool.length=0,this}}function es(){let o,t;onmessage=function(s){const a=s.data;switch(a.type){case"init":o=a.decoderConfig,t=new Promise(function(d){o.onModuleLoaded=function(c){d({draco:c})},DracoDecoderModule(o)});break;case"decode":const l=a.buffer,u=a.taskConfig;t.then(d=>{const c=d.draco,p=new c.Decoder,f=new c.DecoderBuffer;f.Init(new Int8Array(l),l.byteLength);try{const m=e(c,p,f,u),v=m.attributes.map(g=>g.array.buffer);m.index&&v.push(m.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:m},v)}catch(m){console.error(m),self.postMessage({type:"error",id:a.id,error:m.message})}finally{c.destroy(f),c.destroy(p)}});break}};function e(s,a,l,u){const d=u.attributeIDs,c=u.attributeTypes;let p,f;const m=a.GetEncodedGeometryType(l);if(m===s.TRIANGULAR_MESH)p=new s.Mesh,f=a.DecodeBufferToMesh(l,p);else if(m===s.POINT_CLOUD)p=new s.PointCloud,f=a.DecodeBufferToPointCloud(l,p);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||p.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const v={index:null,attributes:[]};for(const g in d){const b=self[c[g]];let y,w;if(u.useUniqueIDs)w=d[g],y=a.GetAttributeByUniqueId(p,w);else{if(w=a.GetAttributeId(p,s[d[g]]),w===-1)continue;y=a.GetAttribute(p,w)}v.attributes.push(i(s,a,p,g,b,y))}return m===s.TRIANGULAR_MESH&&(v.index=n(s,a,p)),s.destroy(p),v}function n(s,a,l){const d=l.num_faces()*3,c=d*4,p=s._malloc(c);a.GetTrianglesUInt32Array(l,c,p);const f=new Uint32Array(s.HEAPF32.buffer,p,d).slice();return s._free(p),{array:f,itemSize:1}}function i(s,a,l,u,d,c){const p=c.num_components(),m=l.num_points()*p,v=m*d.BYTES_PER_ELEMENT,g=r(s,d),b=s._malloc(v);a.GetAttributeDataArrayForAllPoints(l,c,g,v,b);const y=new d(s.HEAPF32.buffer,b,m).slice();return s._free(b),{name:u,array:y,itemSize:p}}function r(s,a){switch(a){case Float32Array:return s.DT_FLOAT32;case Int8Array:return s.DT_INT8;case Int16Array:return s.DT_INT16;case Int32Array:return s.DT_INT32;case Uint8Array:return s.DT_UINT8;case Uint16Array:return s.DT_UINT16;case Uint32Array:return s.DT_UINT32}}}const Zn=new h.Box3,ct=new h.Vector3;class In extends h.InstancedBufferGeometry{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry";const t=[-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],e=[-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],n=[0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5];this.setIndex(n),this.setAttribute("position",new h.Float32BufferAttribute(t,3)),this.setAttribute("uv",new h.Float32BufferAttribute(e,2))}applyMatrix4(t){const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;return e!==void 0&&(e.applyMatrix4(t),n.applyMatrix4(t),e.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(t){let e;t instanceof Float32Array?e=t:Array.isArray(t)&&(e=new Float32Array(t));const n=new h.InstancedInterleavedBuffer(e,6,1);return this.setAttribute("instanceStart",new h.InterleavedBufferAttribute(n,3,0)),this.setAttribute("instanceEnd",new h.InterleavedBufferAttribute(n,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(t,e=3){let n;t instanceof Float32Array?n=t:Array.isArray(t)&&(n=new Float32Array(t));const i=new h.InstancedInterleavedBuffer(n,e*2,1);return this.setAttribute("instanceColorStart",new h.InterleavedBufferAttribute(i,e,0)),this.setAttribute("instanceColorEnd",new h.InterleavedBufferAttribute(i,e,e)),this}fromWireframeGeometry(t){return this.setPositions(t.attributes.position.array),this}fromEdgesGeometry(t){return this.setPositions(t.attributes.position.array),this}fromMesh(t){return this.fromWireframeGeometry(new h.WireframeGeometry(t.geometry)),this}fromLineSegments(t){const e=t.geometry;return this.setPositions(e.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new h.Box3);const t=this.attributes.instanceStart,e=this.attributes.instanceEnd;t!==void 0&&e!==void 0&&(this.boundingBox.setFromBufferAttribute(t),Zn.setFromBufferAttribute(e),this.boundingBox.union(Zn))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new h.Sphere),this.boundingBox===null&&this.computeBoundingBox();const t=this.attributes.instanceStart,e=this.attributes.instanceEnd;if(t!==void 0&&e!==void 0){const n=this.boundingSphere.center;this.boundingBox.getCenter(n);let i=0;for(let r=0,s=t.count;r<s;r++)ct.fromBufferAttribute(t,r),i=Math.max(i,n.distanceToSquared(ct)),ct.fromBufferAttribute(e,r),i=Math.max(i,n.distanceToSquared(ct));this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",this)}}toJSON(){}applyMatrix(t){return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."),this.applyMatrix4(t)}}class ut extends In{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(t){const e=t.length-3,n=new Float32Array(2*e);for(let i=0;i<e;i+=3)n[2*i]=t[i],n[2*i+1]=t[i+1],n[2*i+2]=t[i+2],n[2*i+3]=t[i+3],n[2*i+4]=t[i+4],n[2*i+5]=t[i+5];return super.setPositions(n),this}setColors(t,e=3){const n=t.length-e,i=new Float32Array(2*n);if(e===3)for(let r=0;r<n;r+=e)i[2*r]=t[r],i[2*r+1]=t[r+1],i[2*r+2]=t[r+2],i[2*r+3]=t[r+3],i[2*r+4]=t[r+4],i[2*r+5]=t[r+5];else for(let r=0;r<n;r+=e)i[2*r]=t[r],i[2*r+1]=t[r+1],i[2*r+2]=t[r+2],i[2*r+3]=t[r+3],i[2*r+4]=t[r+4],i[2*r+5]=t[r+5],i[2*r+6]=t[r+6],i[2*r+7]=t[r+7];return super.setColors(i,e),this}fromLine(t){const e=t.geometry;return this.setPositions(e.attributes.position.array),this}}class Je extends h.ShaderMaterial{constructor(t){super({type:"LineMaterial",uniforms:h.UniformsUtils.clone(h.UniformsUtils.merge([h.UniformsLib.common,h.UniformsLib.fog,{worldUnits:{value:1},linewidth:{value:1},resolution:{value:new h.Vector2(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}}])),vertexShader:`
103
+ #include <common>
104
+ #include <fog_pars_vertex>
105
+ #include <logdepthbuf_pars_vertex>
106
+ #include <clipping_planes_pars_vertex>
107
+
108
+ uniform float linewidth;
109
+ uniform vec2 resolution;
110
+
111
+ attribute vec3 instanceStart;
112
+ attribute vec3 instanceEnd;
113
+
114
+ #ifdef USE_COLOR
115
+ #ifdef USE_LINE_COLOR_ALPHA
116
+ varying vec4 vLineColor;
117
+ attribute vec4 instanceColorStart;
118
+ attribute vec4 instanceColorEnd;
119
+ #else
120
+ varying vec3 vLineColor;
121
+ attribute vec3 instanceColorStart;
122
+ attribute vec3 instanceColorEnd;
123
+ #endif
124
+ #endif
125
+
126
+ #ifdef WORLD_UNITS
127
+
128
+ varying vec4 worldPos;
129
+ varying vec3 worldStart;
130
+ varying vec3 worldEnd;
131
+
132
+ #ifdef USE_DASH
133
+
134
+ varying vec2 vUv;
135
+
136
+ #endif
137
+
138
+ #else
139
+
140
+ varying vec2 vUv;
141
+
142
+ #endif
143
+
144
+ #ifdef USE_DASH
145
+
146
+ uniform float dashScale;
147
+ attribute float instanceDistanceStart;
148
+ attribute float instanceDistanceEnd;
149
+ varying float vLineDistance;
150
+
151
+ #endif
152
+
153
+ void trimSegment( const in vec4 start, inout vec4 end ) {
154
+
155
+ // trim end segment so it terminates between the camera plane and the near plane
156
+
157
+ // conservative estimate of the near plane
158
+ float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
159
+ float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
160
+ float nearEstimate = - 0.5 * b / a;
161
+
162
+ float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
163
+
164
+ end.xyz = mix( start.xyz, end.xyz, alpha );
165
+
166
+ }
167
+
168
+ void main() {
169
+
170
+ #ifdef USE_COLOR
171
+
172
+ vLineColor = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
173
+
174
+ #endif
175
+
176
+ #ifdef USE_DASH
177
+
178
+ vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
179
+ vUv = uv;
180
+
181
+ #endif
182
+
183
+ float aspect = resolution.x / resolution.y;
184
+
185
+ // camera space
186
+ vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
187
+ vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
188
+
189
+ #ifdef WORLD_UNITS
190
+
191
+ worldStart = start.xyz;
192
+ worldEnd = end.xyz;
193
+
194
+ #else
195
+
196
+ vUv = uv;
197
+
198
+ #endif
199
+
200
+ // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
201
+ // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
202
+ // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
203
+ // perhaps there is a more elegant solution -- WestLangley
204
+
205
+ bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
206
+
207
+ if ( perspective ) {
208
+
209
+ if ( start.z < 0.0 && end.z >= 0.0 ) {
210
+
211
+ trimSegment( start, end );
212
+
213
+ } else if ( end.z < 0.0 && start.z >= 0.0 ) {
214
+
215
+ trimSegment( end, start );
216
+
217
+ }
218
+
219
+ }
220
+
221
+ // clip space
222
+ vec4 clipStart = projectionMatrix * start;
223
+ vec4 clipEnd = projectionMatrix * end;
224
+
225
+ // ndc space
226
+ vec3 ndcStart = clipStart.xyz / clipStart.w;
227
+ vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
228
+
229
+ // direction
230
+ vec2 dir = ndcEnd.xy - ndcStart.xy;
231
+
232
+ // account for clip-space aspect ratio
233
+ dir.x *= aspect;
234
+ dir = normalize( dir );
235
+
236
+ #ifdef WORLD_UNITS
237
+
238
+ // get the offset direction as perpendicular to the view vector
239
+ vec3 worldDir = normalize( end.xyz - start.xyz );
240
+ vec3 offset;
241
+ if ( position.y < 0.5 ) {
242
+
243
+ offset = normalize( cross( start.xyz, worldDir ) );
244
+
245
+ } else {
246
+
247
+ offset = normalize( cross( end.xyz, worldDir ) );
248
+
249
+ }
250
+
251
+ // sign flip
252
+ if ( position.x < 0.0 ) offset *= - 1.0;
253
+
254
+ float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
255
+
256
+ // don't extend the line if we're rendering dashes because we
257
+ // won't be rendering the endcaps
258
+ #ifndef USE_DASH
259
+
260
+ // extend the line bounds to encompass endcaps
261
+ start.xyz += - worldDir * linewidth * 0.5;
262
+ end.xyz += worldDir * linewidth * 0.5;
263
+
264
+ // shift the position of the quad so it hugs the forward edge of the line
265
+ offset.xy -= dir * forwardOffset;
266
+ offset.z += 0.5;
267
+
268
+ #endif
269
+
270
+ // endcaps
271
+ if ( position.y > 1.0 || position.y < 0.0 ) {
272
+
273
+ offset.xy += dir * 2.0 * forwardOffset;
274
+
275
+ }
276
+
277
+ // adjust for linewidth
278
+ offset *= linewidth * 0.5;
279
+
280
+ // set the world position
281
+ worldPos = ( position.y < 0.5 ) ? start : end;
282
+ worldPos.xyz += offset;
283
+
284
+ // project the worldpos
285
+ vec4 clip = projectionMatrix * worldPos;
286
+
287
+ // shift the depth of the projected points so the line
288
+ // segments overlap neatly
289
+ vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
290
+ clip.z = clipPose.z * clip.w;
291
+
292
+ #else
293
+
294
+ vec2 offset = vec2( dir.y, - dir.x );
295
+ // undo aspect ratio adjustment
296
+ dir.x /= aspect;
297
+ offset.x /= aspect;
298
+
299
+ // sign flip
300
+ if ( position.x < 0.0 ) offset *= - 1.0;
301
+
302
+ // endcaps
303
+ if ( position.y < 0.0 ) {
304
+
305
+ offset += - dir;
306
+
307
+ } else if ( position.y > 1.0 ) {
308
+
309
+ offset += dir;
310
+
311
+ }
312
+
313
+ // adjust for linewidth
314
+ offset *= linewidth;
315
+
316
+ // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
317
+ offset /= resolution.y;
318
+
319
+ // select end
320
+ vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
321
+
322
+ // back to clip space
323
+ offset *= clip.w;
324
+
325
+ clip.xy += offset;
326
+
327
+ #endif
328
+
329
+ gl_Position = clip;
330
+
331
+ vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
332
+
333
+ #include <logdepthbuf_vertex>
334
+ #include <clipping_planes_vertex>
335
+ #include <fog_vertex>
336
+
337
+ }
338
+ `,fragmentShader:`
339
+ uniform vec3 diffuse;
340
+ uniform float opacity;
341
+ uniform float linewidth;
342
+
343
+ #ifdef USE_DASH
344
+
345
+ uniform float dashOffset;
346
+ uniform float dashSize;
347
+ uniform float gapSize;
348
+
349
+ #endif
350
+
351
+ varying float vLineDistance;
352
+
353
+ #ifdef WORLD_UNITS
354
+
355
+ varying vec4 worldPos;
356
+ varying vec3 worldStart;
357
+ varying vec3 worldEnd;
358
+
359
+ #ifdef USE_DASH
360
+
361
+ varying vec2 vUv;
362
+
363
+ #endif
364
+
365
+ #else
366
+
367
+ varying vec2 vUv;
368
+
369
+ #endif
370
+
371
+ #include <common>
372
+ #include <fog_pars_fragment>
373
+ #include <logdepthbuf_pars_fragment>
374
+ #include <clipping_planes_pars_fragment>
375
+
376
+ #ifdef USE_COLOR
377
+ #ifdef USE_LINE_COLOR_ALPHA
378
+ varying vec4 vLineColor;
379
+ #else
380
+ varying vec3 vLineColor;
381
+ #endif
382
+ #endif
383
+
384
+ vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
385
+
386
+ float mua;
387
+ float mub;
388
+
389
+ vec3 p13 = p1 - p3;
390
+ vec3 p43 = p4 - p3;
391
+
392
+ vec3 p21 = p2 - p1;
393
+
394
+ float d1343 = dot( p13, p43 );
395
+ float d4321 = dot( p43, p21 );
396
+ float d1321 = dot( p13, p21 );
397
+ float d4343 = dot( p43, p43 );
398
+ float d2121 = dot( p21, p21 );
399
+
400
+ float denom = d2121 * d4343 - d4321 * d4321;
401
+
402
+ float numer = d1343 * d4321 - d1321 * d4343;
403
+
404
+ mua = numer / denom;
405
+ mua = clamp( mua, 0.0, 1.0 );
406
+ mub = ( d1343 + d4321 * ( mua ) ) / d4343;
407
+ mub = clamp( mub, 0.0, 1.0 );
408
+
409
+ return vec2( mua, mub );
410
+
411
+ }
412
+
413
+ void main() {
414
+
415
+ #include <clipping_planes_fragment>
416
+
417
+ #ifdef USE_DASH
418
+
419
+ if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
420
+
421
+ if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
422
+
423
+ #endif
424
+
425
+ float alpha = opacity;
426
+
427
+ #ifdef WORLD_UNITS
428
+
429
+ // Find the closest points on the view ray and the line segment
430
+ vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
431
+ vec3 lineDir = worldEnd - worldStart;
432
+ vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
433
+
434
+ vec3 p1 = worldStart + lineDir * params.x;
435
+ vec3 p2 = rayEnd * params.y;
436
+ vec3 delta = p1 - p2;
437
+ float len = length( delta );
438
+ float norm = len / linewidth;
439
+
440
+ #ifndef USE_DASH
441
+
442
+ #ifdef USE_ALPHA_TO_COVERAGE
443
+
444
+ float dnorm = fwidth( norm );
445
+ alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
446
+
447
+ #else
448
+
449
+ if ( norm > 0.5 ) {
450
+
451
+ discard;
452
+
453
+ }
454
+
455
+ #endif
456
+
457
+ #endif
458
+
459
+ #else
460
+
461
+ #ifdef USE_ALPHA_TO_COVERAGE
462
+
463
+ // artifacts appear on some hardware if a derivative is taken within a conditional
464
+ float a = vUv.x;
465
+ float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
466
+ float len2 = a * a + b * b;
467
+ float dlen = fwidth( len2 );
468
+
469
+ if ( abs( vUv.y ) > 1.0 ) {
470
+
471
+ alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
472
+
473
+ }
474
+
475
+ #else
476
+
477
+ if ( abs( vUv.y ) > 1.0 ) {
478
+
479
+ float a = vUv.x;
480
+ float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
481
+ float len2 = a * a + b * b;
482
+
483
+ if ( len2 > 1.0 ) discard;
484
+
485
+ }
486
+
487
+ #endif
488
+
489
+ #endif
490
+
491
+ vec4 diffuseColor = vec4( diffuse, alpha );
492
+ #ifdef USE_COLOR
493
+ #ifdef USE_LINE_COLOR_ALPHA
494
+ diffuseColor *= vLineColor;
495
+ #else
496
+ diffuseColor.rgb *= vLineColor;
497
+ #endif
498
+ #endif
499
+
500
+ #include <logdepthbuf_fragment>
501
+
502
+ gl_FragColor = diffuseColor;
503
+
504
+ #include <tonemapping_fragment>
505
+ #include <${ot>=154?"colorspace_fragment":"encodings_fragment"}>
506
+ #include <fog_fragment>
507
+ #include <premultiplied_alpha_fragment>
508
+
509
+ }
510
+ `,clipping:!0}),this.isLineMaterial=!0,this.onBeforeCompile=function(){this.transparent?this.defines.USE_LINE_COLOR_ALPHA="1":delete this.defines.USE_LINE_COLOR_ALPHA},Object.defineProperties(this,{color:{enumerable:!0,get:function(){return this.uniforms.diffuse.value},set:function(e){this.uniforms.diffuse.value=e}},worldUnits:{enumerable:!0,get:function(){return"WORLD_UNITS"in this.defines},set:function(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}},linewidth:{enumerable:!0,get:function(){return this.uniforms.linewidth.value},set:function(e){this.uniforms.linewidth.value=e}},dashed:{enumerable:!0,get:function(){return"USE_DASH"in this.defines},set(e){!!e!="USE_DASH"in this.defines&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}},dashScale:{enumerable:!0,get:function(){return this.uniforms.dashScale.value},set:function(e){this.uniforms.dashScale.value=e}},dashSize:{enumerable:!0,get:function(){return this.uniforms.dashSize.value},set:function(e){this.uniforms.dashSize.value=e}},dashOffset:{enumerable:!0,get:function(){return this.uniforms.dashOffset.value},set:function(e){this.uniforms.dashOffset.value=e}},gapSize:{enumerable:!0,get:function(){return this.uniforms.gapSize.value},set:function(e){this.uniforms.gapSize.value=e}},opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(e){this.uniforms.opacity.value=e}},resolution:{enumerable:!0,get:function(){return this.uniforms.resolution.value},set:function(e){this.uniforms.resolution.value.copy(e)}},alphaToCoverage:{enumerable:!0,get:function(){return"USE_ALPHA_TO_COVERAGE"in this.defines},set:function(e){!!e!="USE_ALPHA_TO_COVERAGE"in this.defines&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1)}}}),this.setValues(t)}}const kt=new h.Vector4,Tn=new h.Vector3,Pn=new h.Vector3,$=new h.Vector4,ee=new h.Vector4,me=new h.Vector4,Dt=new h.Vector3,Ft=new h.Matrix4,te=new h.Line3,An=new h.Vector3,ht=new h.Box3,dt=new h.Sphere,ye=new h.Vector4;let ge,De;function Wn(o,t,e){return ye.set(0,0,-t,1).applyMatrix4(o.projectionMatrix),ye.multiplyScalar(1/ye.w),ye.x=De/e.width,ye.y=De/e.height,ye.applyMatrix4(o.projectionMatrixInverse),ye.multiplyScalar(1/ye.w),Math.abs(Math.max(ye.x,ye.y))}function ts(o,t){const e=o.matrixWorld,n=o.geometry,i=n.attributes.instanceStart,r=n.attributes.instanceEnd,s=Math.min(n.instanceCount,i.count);for(let a=0,l=s;a<l;a++){te.start.fromBufferAttribute(i,a),te.end.fromBufferAttribute(r,a),te.applyMatrix4(e);const u=new h.Vector3,d=new h.Vector3;ge.distanceSqToSegment(te.start,te.end,d,u),d.distanceTo(u)<De*.5&&t.push({point:d,pointOnLine:u,distance:ge.origin.distanceTo(d),object:o,face:null,faceIndex:a,uv:null,[Lt]:null})}}function ns(o,t,e){const n=t.projectionMatrix,r=o.material.resolution,s=o.matrixWorld,a=o.geometry,l=a.attributes.instanceStart,u=a.attributes.instanceEnd,d=Math.min(a.instanceCount,l.count),c=-t.near;ge.at(1,me),me.w=1,me.applyMatrix4(t.matrixWorldInverse),me.applyMatrix4(n),me.multiplyScalar(1/me.w),me.x*=r.x/2,me.y*=r.y/2,me.z=0,Dt.copy(me),Ft.multiplyMatrices(t.matrixWorldInverse,s);for(let p=0,f=d;p<f;p++){if($.fromBufferAttribute(l,p),ee.fromBufferAttribute(u,p),$.w=1,ee.w=1,$.applyMatrix4(Ft),ee.applyMatrix4(Ft),$.z>c&&ee.z>c)continue;if($.z>c){const w=$.z-ee.z,S=($.z-c)/w;$.lerp(ee,S)}else if(ee.z>c){const w=ee.z-$.z,S=(ee.z-c)/w;ee.lerp($,S)}$.applyMatrix4(n),ee.applyMatrix4(n),$.multiplyScalar(1/$.w),ee.multiplyScalar(1/ee.w),$.x*=r.x/2,$.y*=r.y/2,ee.x*=r.x/2,ee.y*=r.y/2,te.start.copy($),te.start.z=0,te.end.copy(ee),te.end.z=0;const v=te.closestPointToPointParameter(Dt,!0);te.at(v,An);const g=h.MathUtils.lerp($.z,ee.z,v),b=g>=-1&&g<=1,y=Dt.distanceTo(An)<De*.5;if(b&&y){te.start.fromBufferAttribute(l,p),te.end.fromBufferAttribute(u,p),te.start.applyMatrix4(s),te.end.applyMatrix4(s);const w=new h.Vector3,S=new h.Vector3;ge.distanceSqToSegment(te.start,te.end,S,w),e.push({point:S,pointOnLine:w,distance:ge.origin.distanceTo(S),object:o,face:null,faceIndex:p,uv:null,[Lt]:null})}}}class is extends h.Mesh{constructor(t=new In,e=new Je({color:Math.random()*16777215})){super(t,e),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const t=this.geometry,e=t.attributes.instanceStart,n=t.attributes.instanceEnd,i=new Float32Array(2*e.count);for(let s=0,a=0,l=e.count;s<l;s++,a+=2)Tn.fromBufferAttribute(e,s),Pn.fromBufferAttribute(n,s),i[a]=a===0?0:i[a-1],i[a+1]=i[a]+Tn.distanceTo(Pn);const r=new h.InstancedInterleavedBuffer(i,2,1);return t.setAttribute("instanceDistanceStart",new h.InterleavedBufferAttribute(r,1,0)),t.setAttribute("instanceDistanceEnd",new h.InterleavedBufferAttribute(r,1,1)),this}raycast(t,e){const n=this.material.worldUnits,i=t.camera;i===null&&!n&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const r=t.params.Line2!==void 0&&t.params.Line2.threshold||0;ge=t.ray;const s=this.matrixWorld,a=this.geometry,l=this.material;De=l.linewidth+r,a.boundingSphere===null&&a.computeBoundingSphere(),dt.copy(a.boundingSphere).applyMatrix4(s);let u;if(n)u=De*.5;else{const c=Math.max(i.near,dt.distanceToPoint(ge.origin));u=Wn(i,c,l.resolution)}if(dt.radius+=u,ge.intersectsSphere(dt)===!1)return;a.boundingBox===null&&a.computeBoundingBox(),ht.copy(a.boundingBox).applyMatrix4(s);let d;if(n)d=De*.5;else{const c=Math.max(i.near,ht.distanceToPoint(ge.origin));d=Wn(i,c,l.resolution)}ht.expandByScalar(d),ge.intersectsBox(ht)!==!1&&(n?ts(this,e):ns(this,i,e))}onBeforeRender(t){const e=this.material.uniforms;e&&e.resolution&&(t.getViewport(kt),this.material.uniforms.resolution.value.set(kt.z,kt.w))}}class Ot extends is{constructor(t=new ut,e=new Je({color:Math.random()*16777215})){super(t,e),this.isLine2=!0,this.type="Line2"}}var Ye=Object.freeze({Linear:Object.freeze({None:function(o){return o},In:function(o){return this.None(o)},Out:function(o){return this.None(o)},InOut:function(o){return this.None(o)}}),Quadratic:Object.freeze({In:function(o){return o*o},Out:function(o){return o*(2-o)},InOut:function(o){return(o*=2)<1?.5*o*o:-.5*(--o*(o-2)-1)}}),Cubic:Object.freeze({In:function(o){return o*o*o},Out:function(o){return--o*o*o+1},InOut:function(o){return(o*=2)<1?.5*o*o*o:.5*((o-=2)*o*o+2)}}),Quartic:Object.freeze({In:function(o){return o*o*o*o},Out:function(o){return 1- --o*o*o*o},InOut:function(o){return(o*=2)<1?.5*o*o*o*o:-.5*((o-=2)*o*o*o-2)}}),Quintic:Object.freeze({In:function(o){return o*o*o*o*o},Out:function(o){return--o*o*o*o*o+1},InOut:function(o){return(o*=2)<1?.5*o*o*o*o*o:.5*((o-=2)*o*o*o*o+2)}}),Sinusoidal:Object.freeze({In:function(o){return 1-Math.sin((1-o)*Math.PI/2)},Out:function(o){return Math.sin(o*Math.PI/2)},InOut:function(o){return .5*(1-Math.sin(Math.PI*(.5-o)))}}),Exponential:Object.freeze({In:function(o){return o===0?0:Math.pow(1024,o-1)},Out:function(o){return o===1?1:1-Math.pow(2,-10*o)},InOut:function(o){return o===0?0:o===1?1:(o*=2)<1?.5*Math.pow(1024,o-1):.5*(-Math.pow(2,-10*(o-1))+2)}}),Circular:Object.freeze({In:function(o){return 1-Math.sqrt(1-o*o)},Out:function(o){return Math.sqrt(1- --o*o)},InOut:function(o){return(o*=2)<1?-.5*(Math.sqrt(1-o*o)-1):.5*(Math.sqrt(1-(o-=2)*o)+1)}}),Elastic:Object.freeze({In:function(o){return o===0?0:o===1?1:-Math.pow(2,10*(o-1))*Math.sin((o-1.1)*5*Math.PI)},Out:function(o){return o===0?0:o===1?1:Math.pow(2,-10*o)*Math.sin((o-.1)*5*Math.PI)+1},InOut:function(o){return o===0?0:o===1?1:(o*=2,o<1?-.5*Math.pow(2,10*(o-1))*Math.sin((o-1.1)*5*Math.PI):.5*Math.pow(2,-10*(o-1))*Math.sin((o-1.1)*5*Math.PI)+1)}}),Back:Object.freeze({In:function(o){var t=1.70158;return o===1?1:o*o*((t+1)*o-t)},Out:function(o){var t=1.70158;return o===0?0:--o*o*((t+1)*o+t)+1},InOut:function(o){var t=2.5949095;return(o*=2)<1?.5*(o*o*((t+1)*o-t)):.5*((o-=2)*o*((t+1)*o+t)+2)}}),Bounce:Object.freeze({In:function(o){return 1-Ye.Bounce.Out(1-o)},Out:function(o){return o<1/2.75?7.5625*o*o:o<2/2.75?7.5625*(o-=1.5/2.75)*o+.75:o<2.5/2.75?7.5625*(o-=2.25/2.75)*o+.9375:7.5625*(o-=2.625/2.75)*o+.984375},InOut:function(o){return o<.5?Ye.Bounce.In(o*2)*.5:Ye.Bounce.Out(o*2-1)*.5+.5}}),generatePow:function(o){return o===void 0&&(o=4),o=o<Number.EPSILON?Number.EPSILON:o,o=o>1e4?1e4:o,{In:function(t){return Math.pow(t,o)},Out:function(t){return 1-Math.pow(1-t,o)},InOut:function(t){return t<.5?Math.pow(t*2,o)/2:(1-Math.pow(2-t*2,o))/2+.5}}}}),Qe=function(){return performance.now()},rs=function(){function o(){this._tweens={},this._tweensAddedDuringUpdate={}}return o.prototype.getAll=function(){var t=this;return Object.keys(this._tweens).map(function(e){return t._tweens[e]})},o.prototype.removeAll=function(){this._tweens={}},o.prototype.add=function(t){this._tweens[t.getId()]=t,this._tweensAddedDuringUpdate[t.getId()]=t},o.prototype.remove=function(t){delete this._tweens[t.getId()],delete this._tweensAddedDuringUpdate[t.getId()]},o.prototype.update=function(t,e){t===void 0&&(t=Qe()),e===void 0&&(e=!1);var n=Object.keys(this._tweens);if(n.length===0)return!1;for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<n.length;i++){var r=this._tweens[n[i]],s=!e;r&&r.update(t,s)===!1&&!e&&delete this._tweens[n[i]]}n=Object.keys(this._tweensAddedDuringUpdate)}return!0},o}(),zt={Linear:function(o,t){var e=o.length-1,n=e*t,i=Math.floor(n),r=zt.Utils.Linear;return t<0?r(o[0],o[1],n):t>1?r(o[e],o[e-1],e-n):r(o[i],o[i+1>e?e:i+1],n-i)},Utils:{Linear:function(o,t,e){return(t-o)*e+o}}},Gn=function(){function o(){}return o.nextId=function(){return o._nextId++},o._nextId=0,o}(),Xt=new rs,Vn=function(){function o(t,e){e===void 0&&(e=Xt),this._object=t,this._group=e,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=Ye.Linear.None,this._interpolationFunction=zt.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=Gn.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1}return o.prototype.getId=function(){return this._id},o.prototype.isPlaying=function(){return this._isPlaying},o.prototype.isPaused=function(){return this._isPaused},o.prototype.getDuration=function(){return this._duration},o.prototype.to=function(t,e){if(e===void 0&&(e=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=t,this._propertiesAreSetUp=!1,this._duration=e<0?0:e,this},o.prototype.duration=function(t){return t===void 0&&(t=1e3),this._duration=t<0?0:t,this},o.prototype.dynamic=function(t){return t===void 0&&(t=!1),this._isDynamic=t,this},o.prototype.start=function(t,e){if(t===void 0&&(t=Qe()),e===void 0&&(e=!1),this._isPlaying)return this;if(this._group&&this._group.add(this),this._repeat=this._initialRepeat,this._reversed){this._reversed=!1;for(var n in this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n]}if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=t,this._startTime+=this._delayTime,!this._propertiesAreSetUp||e){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,e)}return this},o.prototype.startFromCurrentValues=function(t){return this.start(t,!0)},o.prototype._setupProperties=function(t,e,n,i,r){for(var s in n){var a=t[s],l=Array.isArray(a),u=l?"array":typeof a,d=!l&&Array.isArray(n[s]);if(!(u==="undefined"||u==="function")){if(d){var c=n[s];if(c.length===0)continue;for(var p=[a],f=0,m=c.length;f<m;f+=1){var v=this._handleRelativeValue(a,c[f]);if(isNaN(v)){d=!1,console.warn("Found invalid interpolation list. Skipping.");break}p.push(v)}d&&(n[s]=p)}if((u==="object"||l)&&a&&!d){e[s]=l?[]:{};var g=a;for(var b in g)e[s][b]=g[b];i[s]=l?[]:{};var c=n[s];if(!this._isDynamic){var y={};for(var b in c)y[b]=c[b];n[s]=c=y}this._setupProperties(g,e[s],c,i[s],r)}else(typeof e[s]>"u"||r)&&(e[s]=a),l||(e[s]*=1),d?i[s]=n[s].slice().reverse():i[s]=e[s]||0}}},o.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._group&&this._group.remove(this),this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},o.prototype.end=function(){return this._goToEnd=!0,this.update(1/0),this},o.prototype.pause=function(t){return t===void 0&&(t=Qe()),this._isPaused||!this._isPlaying?this:(this._isPaused=!0,this._pauseStart=t,this._group&&this._group.remove(this),this)},o.prototype.resume=function(t){return t===void 0&&(t=Qe()),!this._isPaused||!this._isPlaying?this:(this._isPaused=!1,this._startTime+=t-this._pauseStart,this._pauseStart=0,this._group&&this._group.add(this),this)},o.prototype.stopChainedTweens=function(){for(var t=0,e=this._chainedTweens.length;t<e;t++)this._chainedTweens[t].stop();return this},o.prototype.group=function(t){return t===void 0&&(t=Xt),this._group=t,this},o.prototype.delay=function(t){return t===void 0&&(t=0),this._delayTime=t,this},o.prototype.repeat=function(t){return t===void 0&&(t=0),this._initialRepeat=t,this._repeat=t,this},o.prototype.repeatDelay=function(t){return this._repeatDelayTime=t,this},o.prototype.yoyo=function(t){return t===void 0&&(t=!1),this._yoyo=t,this},o.prototype.easing=function(t){return t===void 0&&(t=Ye.Linear.None),this._easingFunction=t,this},o.prototype.interpolation=function(t){return t===void 0&&(t=zt.Linear),this._interpolationFunction=t,this},o.prototype.chain=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return this._chainedTweens=t,this},o.prototype.onStart=function(t){return this._onStartCallback=t,this},o.prototype.onEveryStart=function(t){return this._onEveryStartCallback=t,this},o.prototype.onUpdate=function(t){return this._onUpdateCallback=t,this},o.prototype.onRepeat=function(t){return this._onRepeatCallback=t,this},o.prototype.onComplete=function(t){return this._onCompleteCallback=t,this},o.prototype.onStop=function(t){return this._onStopCallback=t,this},o.prototype.update=function(t,e){var n=this,i;if(t===void 0&&(t=Qe()),e===void 0&&(e=!0),this._isPaused)return!0;var r,s=this._startTime+this._duration;if(!this._goToEnd&&!this._isPlaying){if(t>s)return!1;e&&this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;this._onStartCallbackFired===!1&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),this._onEveryStartCallbackFired===!1&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,l=this._duration+((i=this._repeatDelayTime)!==null&&i!==void 0?i:this._delayTime),u=this._duration+this._repeat*l,d=function(){if(n._duration===0||a>u)return 1;var g=Math.trunc(a/l),b=a-g*l,y=Math.min(b/n._duration,1);return y===0&&a===n._duration?1:y},c=d(),p=this._easingFunction(c);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,p),this._onUpdateCallback&&this._onUpdateCallback(this._object,c),this._duration===0||a>=this._duration)if(this._repeat>0){var f=Math.min(Math.trunc((a-this._duration)/l)+1,this._repeat);isFinite(this._repeat)&&(this._repeat-=f);for(r in this._valuesStartRepeat)!this._yoyo&&typeof this._valuesEnd[r]=="string"&&(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=l*f,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}else{this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var m=0,v=this._chainedTweens.length;m<v;m++)this._chainedTweens[m].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},o.prototype._updateProperties=function(t,e,n,i){for(var r in n)if(e[r]!==void 0){var s=e[r]||0,a=n[r],l=Array.isArray(t[r]),u=Array.isArray(a),d=!l&&u;d?t[r]=this._interpolationFunction(a,i):typeof a=="object"&&a?this._updateProperties(t[r],s,a,i):(a=this._handleRelativeValue(s,a),typeof a=="number"&&(t[r]=s+(a-s)*i))}},o.prototype._handleRelativeValue=function(t,e){return typeof e!="string"?e:e.charAt(0)==="+"||e.charAt(0)==="-"?t+parseFloat(e):parseFloat(e)},o.prototype._swapEndStartRepeatValues=function(t){var e=this._valuesStartRepeat[t],n=this._valuesEnd[t];typeof n=="string"?this._valuesStartRepeat[t]=this._valuesStartRepeat[t]+parseFloat(n):this._valuesStartRepeat[t]=this._valuesEnd[t],this._valuesEnd[t]=e},o}();Gn.nextId;var be=Xt;be.getAll.bind(be),be.removeAll.bind(be),be.add.bind(be),be.remove.bind(be);var ss=be.update.bind(be);class Cn extends h.EventDispatcher{constructor(e,n={}){super();x(this,"scene");x(this,"renderer");x(this,"camera");x(this,"controls");x(this,"ambLight");x(this,"dirLight");x(this,"clouds",null);x(this,"container");x(this,"_clock",new h.Clock);x(this,"stats");x(this,"_animationCallbacks",new Set);x(this,"_fogFactor",1);const{antialias:i=!1,stencil:r=!0,logarithmicDepthBuffer:s=!0,skybox:a}=n;this.renderer=this._createRenderer(i,r,s),this.scene=this._createScene(a),this.camera=this._createCamera(),e&&this.addTo(e),this.controls=this._createControls(),this.ambLight=this._createAmbLight(),this.scene.add(this.ambLight),this.dirLight=this._createDirLight(),this.scene.add(this.dirLight),this.scene.add(this.dirLight.target),this.renderer.setAnimationLoop(this.animate.bind(this)),n.debug&&(this.stats=new Be,document.body.appendChild(this.stats.dom))}get fogFactor(){return this._fogFactor}set fogFactor(e){this._fogFactor=e,this.controls.dispatchEvent({type:"change",target:this.controls})}get width(){return this.container?.clientWidth||0}get height(){return this.container?.clientHeight||0}addTo(e){const n=typeof e=="string"?document.querySelector(e):e;if(n instanceof HTMLElement)this.container=n,n.appendChild(this.renderer.domElement),new ResizeObserver(this.resize.bind(this)).observe(n);else throw`${e} not found!}`;return this}_createScene(e){const n=new h.Scene,i=e?.defaultColor||14414079;if(n.background=new h.Color(i),n.fog=new h.FogExp2(i,0),e?.files){const r=new h.CubeTextureLoader;e.path&&r.setPath(e.path),r.load(e.files,s=>{n.background=s},void 0,s=>{console.error("Error loading skybox:",s),n.background=new h.Color(i)})}else e?.hdr&&this._loadHDRWithPMREM(n,e);return n}async _loadHDRWithPMREM(e,n){try{if(n){const r=await new qr().setPath(n.path||"").setDataType(h.FloatType).loadAsync(n.hdr);r.colorSpace=h.LinearSRGBColorSpace;const s=new h.PMREMGenerator(this.renderer),a=s.fromEquirectangular(r).texture;console.log("HDR加载完成:",r,"环境贴图:",a),e.background=a,e.environment=a,this.dirLight.intensity=5,n?.hdrExposure!==void 0&&(this.renderer.toneMappingExposure=n.hdrExposure),r.dispose(),s.dispose()}}catch(i){console.error("加载HDR失败:",i),e.background=new h.Color(n?.defaultColor||14414079)}}_createRenderer(e,n,i){const r=new h.WebGLRenderer({antialias:e,logarithmicDepthBuffer:i,stencil:n,alpha:!0,precision:"highp",powerPreference:"high-performance",failIfMajorPerformanceCaveat:!0});if(r.sortObjects=!0,r.setPixelRatio(window.devicePixelRatio),r.domElement.tabIndex=0,r.shadowMap.enabled=!0,r.shadowMap.type=h.PCFSoftShadowMap,r.toneMapping=h.ACESFilmicToneMapping,r.toneMappingExposure=2,r.outputColorSpace="srgb-linear",r.capabilities.isWebGL2){const s=r.getContext();s.getExtension("EXT_color_buffer_float"),s.getExtension("OES_texture_float_linear")}return r}_createCamera(){const e=new h.PerspectiveCamera(70,1,100,5e4);return e.position.set(0,3e4*1e3,0),e}_createControls(){const e=new Hi(this.camera,this.renderer.domElement),n=1.52;return e.target.set(0,0,-3e3),e.screenSpacePanning=!1,e.minDistance=100/2,e.maxDistance=3e7,e.maxPolarAngle=n,e.enableDamping=!0,e.dampingFactor=.05,e.keyPanSpeed=5,e.listenToKeyEvents(this.renderer.domElement),e.addEventListener("change",()=>{const i=Math.max(e.getPolarAngle(),.1),r=Math.max(e.getDistance(),100);e.zoomSpeed=Math.max(Math.log(r/1e3),0)+.5,this.camera.far=h.MathUtils.clamp(r/i*8,100,5e4*1e3),this.camera.near=this.camera.far/1e4,this.camera.updateProjectionMatrix(),this.scene.fog instanceof h.FogExp2&&(this.scene.fog.density=i/(r+5)*this.fogFactor*.25);const a=r>8e6;e.minAzimuthAngle=a?0:-1/0,e.maxAzimuthAngle=a?0:1/0;const l=1e7,u=4;e.maxPolarAngle=Math.min(Math.pow(l/r,u),n)}),e}_createAmbLight(){return new h.AmbientLight(16777215,.1)}_createDirLight(){const e=new h.DirectionalLight(16777215,3);return e.position.set(0,2e3,1e3),e.castShadow=!0,e.shadow.mapSize.width=2048,e.shadow.mapSize.height=2048,e.shadow.camera.near=100,e.shadow.camera.far=1e6,e.shadow.camera.left=-1e4,e.shadow.camera.right=1e4,e.shadow.camera.top=1e4,e.shadow.camera.bottom=-1e4,e}resize(){const e=this.width,n=this.height;return this.renderer.setSize(e,n),this.camera.aspect=e/n,this.camera.updateProjectionMatrix(),this.renderer.render(this.scene,this.camera),this}addAnimationCallback(e){return this._animationCallbacks.add(e),()=>this._animationCallbacks.delete(e)}animate(){const e=this._clock.getDelta(),n=this._clock.getElapsedTime();this._animationCallbacks.forEach(i=>i(e,n)),this.controls.update(),this.renderer.render(this.scene,this.camera),ss(),this.stats&&this.stats.update(),this.dispatchEvent({type:"update",delta:e})}flyTo(e,n,i=!0,r){if(this.controls.target.copy(e),i){const s=this.camera.position;new Vn(s).to({y:2e7,z:0},500).chain(new Vn(s).to(n,2e3).easing(Ye.Quintic.Out).onComplete(a=>r&&r(a))).start()}else this.camera.position.copy(n)}getState(){return{centerPosition:this.controls.target,cameraPosition:this.camera.position}}}class os extends h.LoadingManager{constructor(){super(...arguments);x(this,"onParseEnd")}parseEnd(e){this.onParseEnd&&this.onParseEnd(e)}}const ie={manager:new os,demLoaderMap:new Map,imgLoaderMap:new Map,registerMaterialLoader(o){ie.imgLoaderMap.set(o.dataType,o),o.info.author=o.info.author??$t.name},registerGeometryLoader(o){ie.demLoaderMap.set(o.dataType,o),o.info.author=o.info.author??$t.name},getMaterialLoader(o){const t=ie.imgLoaderMap.get(o.dataType);if(t)return t;throw`Source dataType "${o.dataType}" is not support!`},getGeometryLoader(o){const t=ie.demLoaderMap.get(o.dataType);if(t)return t;throw`Source dataType "${o.dataType}" is not support!`}};function kn(o,t){const e=Math.floor(o[0]*t),n=Math.floor(o[1]*t),i=Math.floor((o[2]-o[0])*t),r=Math.floor((o[3]-o[1])*t);return{sx:e,sy:n,sw:i,sh:r}}function Dn(o,t,e,n){if(n<o.minLevel)return{url:void 0,clipBounds:[0,0,1,1]};if(n<=o.maxLevel)return{url:o._getUrl(t,e,n),clipBounds:[0,0,1,1]};const i=as(t,e,n,o.maxLevel),r=i.parentNO;return{url:o._getUrl(r.x,r.y,r.z),clipBounds:i.bounds}}function as(o,t,e,n){const i=e-n,r={x:o>>i,y:t>>i,z:e-i},s=Math.pow(2,i),a=Math.pow(.5,i),l=o%s/s-.5+a/2,u=t%s/s-.5+a/2,d=new h.Vector2(l,u),c=new h.Box2().setFromCenterAndSize(d,new h.Vector2(a,a)),p=[c.min.x+.5,c.min.y+.5,c.max.x+.5,c.max.y+.5];return{parentNO:r,bounds:p}}class Fn{constructor(){x(this,"_imgSource",[]);x(this,"_demSource");x(this,"manager",ie.manager)}get imgSource(){return this._imgSource}set imgSource(t){this._imgSource=t}get demSource(){return this._demSource}set demSource(t){this._demSource=t}async load(t){const e=await this.loadGeometry(t),n=await this.loadMaterial(t);console.assert(!!n&&!!e);for(let i=0;i<n.length;i++)e.addGroup(0,1/0,i);return{materials:n,geometry:e}}unload(t){const e=t.material,n=t.geometry;for(let i=0;i<e.length;i++)e[i].dispose();n.dispose()}async loadGeometry(t){let e;if(this.demSource&&t.z>=this.demSource.minLevel&&this._isBoundsInSourceBounds(this.demSource,t.bounds)){const n=ie.getGeometryLoader(this.demSource),i=this.demSource;e=await n.load({source:i,...t}).catch(r=>(console.error("Load material error",i.dataType,t.x,t.y,t.z),new h.PlaneGeometry)),e.addEventListener("dispose",()=>{n.unload&&n.unload(e)})}else e=new h.PlaneGeometry;return e}async loadMaterial(t){const n=this.imgSource.filter(i=>t.z>=i.minLevel&&this._isBoundsInSourceBounds(i,t.bounds)).map(async i=>{const r=ie.getMaterialLoader(i),s=await r.load({source:i,...t}).catch(l=>(console.error("Load material error",i.dataType,t.x,t.y,t.z),new h.MeshBasicMaterial)),a=l=>{r.unload&&r.unload(l.target),l.target.removeEventListener("dispose",a)};return s instanceof h.MeshBasicMaterial||s.addEventListener("dispose",a),s});return Promise.all(n)}_isBoundsInSourceBounds(t,e){const n=t._projectionBounds;return!(e[2]<n[0]||e[3]<n[1]||e[0]>n[2]||e[1]>n[3])}}function pt(...o){const t=o,e=t&&t.length>1&&t[0].constructor||null;if(!e)throw new Error("concatenateTypedArrays - incorrect quantity of arguments or arguments have incompatible data types");const n=t.reduce((s,a)=>s+a.length,0),i=new e(n);let r=0;for(const s of t)i.set(s,r),r+=s.length;return i}function ls(o,t,e,n){const i=cs(t),r=i.length,s=new Float32Array(r*6),a=new Float32Array(r*4),l=new t.constructor(r*6),u=new Float32Array(r*6);for(let c=0;c<r;c++)us({edge:i[c],edgeIndex:c,attributes:o,skirtHeight:e,newPosition:s,newTexcoord0:a,newTriangles:l,newNormals:u});o.position.value=pt(o.position.value,s),o.texcoord.value=pt(o.texcoord.value,a),o.normal.value=pt(o.normal.value,u);const d=pt(t,l);return{attributes:o,indices:d}}function cs(o){const t=[],e=Array.isArray(o)?o:Array.from(o);for(let i=0;i<e.length;i+=3){const r=e[i],s=e[i+1],a=e[i+2];t.push([r,s],[s,a],[a,r])}t.sort(([i,r],[s,a])=>{const l=Math.min(i,r),u=Math.min(s,a);return l!==u?l-u:Math.max(i,r)-Math.max(s,a)});const n=[];for(let i=0;i<t.length;i++)i+1<t.length&&t[i][0]===t[i+1][1]&&t[i][1]===t[i+1][0]?i++:n.push(t[i]);return n}function us({edge:o,edgeIndex:t,attributes:e,skirtHeight:n,newPosition:i,newTexcoord0:r,newTriangles:s,newNormals:a}){const l=e.position.value.length,u=t*2,d=u+1;i.set(e.position.value.subarray(o[0]*3,o[0]*3+3),u*3),i[u*3+2]=i[u*3+2]-n,i.set(e.position.value.subarray(o[1]*3,o[1]*3+3),d*3),i[d*3+2]=i[d*3+2]-n,r.set(e.texcoord.value.subarray(o[0]*2,o[0]*2+2),u*2),r.set(e.texcoord.value.subarray(o[1]*2,o[1]*2+2),d*2);const c=t*2*3;s[c]=o[0],s[c+1]=l/3+d,s[c+2]=o[1],s[c+3]=l/3+d,s[c+4]=o[0],s[c+5]=l/3+u,a[c]=0,a[c+1]=0,a[c+2]=1,a[c+3]=0,a[c+4]=0,a[c+5]=1}function hs(o){if(o.length<4)throw new Error(`DEM array must > 4, got ${o.length}!`);const t=Math.floor(Math.sqrt(o.length)),e=t,n=t,i=On(n,e);return{attributes:ds(o,n,e),indices:i}}function ds(o,t,e){const n=e*t,i=new Float32Array(n*3),r=new Float32Array(n*2);let s=0;for(let a=0;a<t;a++)for(let l=0;l<e;l++){const u=l/(e-1),d=a/(t-1);r[s*2]=u,r[s*2+1]=d,i[s*3]=u-.5,i[s*3+1]=d-.5,i[s*3+2]=o[(t-a-1)*e+l],s++}return{position:{value:i,size:3},texcoord:{value:r,size:2},normal:{value:zn(i,On(t,e)),size:3}}}function On(o,t){const e=6*(t-1)*(o-1),n=new Uint16Array(e);let i=0;for(let r=0;r<o-1;r++)for(let s=0;s<t-1;s++){const a=r*t+s,l=a+1,u=a+t,d=u+1,c=i*6;n[c]=a,n[c+1]=l,n[c+2]=u,n[c+3]=u,n[c+4]=l,n[c+5]=d,i++}return n}function zn(o,t){const e=new Float32Array(o.length);for(let n=0;n<t.length;n+=3){const i=t[n]*3,r=t[n+1]*3,s=t[n+2]*3,a=o[i],l=o[i+1],u=o[i+2],d=o[r],c=o[r+1],p=o[r+2],f=o[s],m=o[s+1],v=o[s+2],g=d-a,b=c-l,y=p-u,w=f-a,S=m-l,P=v-u,I=b*P-y*S,T=y*w-g*P,M=g*S-b*w,A=Math.sqrt(I*I+T*T+M*M),L=[0,0,1];if(A>0){const Z=1/A;L[0]=I*Z,L[1]=T*Z,L[2]=M*Z}for(let Z=0;Z<3;Z++)e[i+Z]=e[r+Z]=e[s+Z]=L[Z]}return e}class Ut extends h.PlaneGeometry{constructor(){super(...arguments);x(this,"type","TileGeometry")}setData(e,n=1e3){let i=e instanceof Float32Array?hs(e):e;i=ls(i.attributes,i.indices,n);const{attributes:r,indices:s}=i;return this.setIndex(new h.BufferAttribute(s,1)),this.setAttribute("position",new h.BufferAttribute(r.position.value,r.position.size)),this.setAttribute("uv",new h.BufferAttribute(r.texcoord.value,r.texcoord.size)),this.setAttribute("normal",new h.BufferAttribute(r.normal.value,r.normal.size)),this.computeBoundingBox(),this.computeBoundingSphere(),this}}class ps{constructor(t=257){x(this,"gridSize");x(this,"numTriangles");x(this,"numParentTriangles");x(this,"indices");x(this,"coords");this.gridSize=t;const e=t-1;if(e&e-1)throw new Error(`Expected grid size to be 2^n+1, got ${t}.`);this.numTriangles=e*e*2-2,this.numParentTriangles=this.numTriangles-e*e,this.indices=new Uint32Array(this.gridSize*this.gridSize),this.coords=new Uint16Array(this.numTriangles*4);for(let n=0;n<this.numTriangles;n++){let i=n+2,r=0,s=0,a=0,l=0,u=0,d=0;for(i&1?a=l=u=e:r=s=d=e;(i>>=1)>1;){const p=r+a>>1,f=s+l>>1;i&1?(a=r,l=s,r=u,s=d):(r=a,s=l,a=u,l=d),u=p,d=f}const c=n*4;this.coords[c+0]=r,this.coords[c+1]=s,this.coords[c+2]=a,this.coords[c+3]=l}}createTile(t){return new fs(t,this)}}class fs{constructor(t,e){x(this,"martini");x(this,"terrain");x(this,"errors");const n=e.gridSize;if(t.length!==n*n)throw new Error(`Expected terrain data of length ${n*n} (${n} x ${n}), got ${t.length}.`);this.terrain=t,this.martini=e,this.errors=new Float32Array(t.length),this.update()}update(){const{numTriangles:t,numParentTriangles:e,coords:n,gridSize:i}=this.martini,{terrain:r,errors:s}=this;for(let a=t-1;a>=0;a--){const l=a*4,u=n[l+0],d=n[l+1],c=n[l+2],p=n[l+3],f=u+c>>1,m=d+p>>1,v=f+m-d,g=m+u-f,b=(r[d*i+u]+r[p*i+c])/2,y=m*i+f,w=Math.abs(b-r[y]);if(s[y]=Math.max(s[y],w),a<e){const S=(d+g>>1)*i+(u+v>>1),P=(p+g>>1)*i+(c+v>>1);s[y]=Math.max(s[y],s[S],s[P])}}}getGeometryData(t=0){const{gridSize:e,indices:n}=this.martini,{errors:i}=this;let r=0,s=0;const a=e-1;let l,u,d=0;n.fill(0);function c(y,w,S,P,I,T){const M=y+S>>1,A=w+P>>1;Math.abs(y-I)+Math.abs(w-T)>1&&i[A*e+M]>t?(c(I,T,y,w,M,A),c(S,P,I,T,M,A)):(l=w*e+y,u=P*e+S,d=T*e+I,n[l]===0&&(n[l]=++r),n[u]===0&&(n[u]=++r),n[d]===0&&(n[d]=++r),s++)}c(0,0,a,a,a,0),c(a,a,0,0,0,a);const p=r*2,f=s*3,m=new Uint16Array(p),v=new Uint32Array(f);let g=0;function b(y,w,S,P,I,T){const M=y+S>>1,A=w+P>>1;if(Math.abs(y-I)+Math.abs(w-T)>1&&i[A*e+M]>t)b(I,T,y,w,M,A),b(S,P,I,T,M,A);else{const L=n[w*e+y]-1,Z=n[P*e+S]-1,W=n[T*e+I]-1;m[2*L]=y,m[2*L+1]=w,m[2*Z]=S,m[2*Z+1]=P,m[2*W]=I,m[2*W+1]=T,v[g++]=L,v[g++]=Z,v[g++]=W}}return b(0,0,a,a,a,0),b(a,a,0,0,0,a),{attributes:this._getMeshAttributes(this.terrain,m,v),indices:v}}_getMeshAttributes(t,e,n){const i=Math.floor(Math.sqrt(t.length)),r=i-1,s=e.length/2,a=new Float32Array(s*3),l=new Float32Array(s*2);for(let d=0;d<s;d++){const c=e[d*2],p=e[d*2+1],f=p*i+c;a[3*d+0]=c/r-.5,a[3*d+1]=.5-p/r,a[3*d+2]=t[f],l[2*d+0]=c/r,l[2*d+1]=1-p/r}const u=zn(a,n);return{position:{value:a,size:3},texcoord:{value:l,size:2},normal:{value:u,size:3}}}}class Xn{constructor(){x(this,"info",{version:"0.10.0",description:"Terrain loader base class"});x(this,"dataType","")}async load(t){const{source:e,x:n,y:i,z:r}=t,{url:s,clipBounds:a}=Dn(e,n,i,r);if(!s)return new Ut;const l=await this.doLoad(s,{source:e,x:n,y:i,z:r,bounds:a});return ie.manager.parseEnd(s),l}}class ms extends h.MeshStandardMaterial{constructor(t={}){super({transparent:!0,side:h.FrontSide,...t})}setTexture(t){this.map=t,this.needsUpdate=!0}dispose(){const t=this.map;t&&(t.image instanceof ImageBitmap&&t.image.close(),t.dispose())}}class ys{constructor(){x(this,"info",{version:"0.10.0",description:"Image loader base class"});x(this,"dataType","")}async load(t){const{source:e,x:n,y:i,z:r}=t,s=new ms,{url:a,clipBounds:l}=Dn(e,n,i,r);if(a){const u=await this.doLoad(a,{source:e,x:n,y:i,z:r,bounds:l});s.map=u,ie.manager.parseEnd(a)}return s}}class gs extends ys{constructor(){super(...arguments);x(this,"info",{version:"0.10.0",description:"Tile image loader. It can load xyz tile image."});x(this,"dataType","image");x(this,"loader",new h.ImageLoader(ie.manager))}async doLoad(e,n){const i=await this.loader.loadAsync(e).catch(a=>new Image(1,1)),r=new h.Texture;r.colorSpace=h.SRGBColorSpace;const{bounds:s}=n;return s[2]-s[0]<1?r.image=bs(i,s):r.image=i,r.needsUpdate=!0,r}}function bs(o,t){const e=o.width,n=new OffscreenCanvas(e,e),i=n.getContext("2d"),{sx:r,sy:s,sw:a,sh:l}=kn(t,o.width);return i.drawImage(o,r,s,a,l,0,0,e,e),n}const vs=`{
511
+ "name": "@terra.gl/core",
512
+ "version": "0.0.1-alpha.6",
513
+ "type": "module",
514
+ "files": [
515
+ "dist"
516
+ ],
517
+ "main": "./dist/index.umd.cjs",
518
+ "module": "./dist/index.js",
519
+ "types": "./dist/index.d.ts",
520
+ "exports": {
521
+ ".": {
522
+ "import": "./dist/index.js",
523
+ "require": "./dist/index.umd.cjs",
524
+ "types": "./dist/index.d.ts"
525
+ }
526
+ },
527
+ "author": {
528
+ "name": "criska"
529
+ },
530
+ "description": "a map using threejs",
531
+ "license": "MIT",
532
+ "keywords": [
533
+ "three",
534
+ "gis",
535
+ "tile",
536
+ "map",
537
+ "3D",
538
+ "cesium",
539
+ "mapbox"
540
+ ],
541
+ "scripts": {
542
+ "dev": "vite build --watch",
543
+ "build": "tsc && vite build"
544
+ },
545
+ "peerDependencies": {
546
+ "three": "^0.171.0"
547
+ },
548
+ "publishConfig": {
549
+ "registry": "https://registry.npmjs.org/",
550
+ "access": "public"
551
+ },
552
+ "dependencies": {
553
+ "@pmndrs/vanilla": "^1.20.4",
554
+ "@takram/three-atmosphere": "^0.11.2",
555
+ "@takram/three-clouds": "^0.2.2",
556
+ "@takram/three-geospatial": "^0.2.1",
557
+ "@takram/three-geospatial-effects": "^0.3.1",
558
+ "@types/earcut": "^3.0.0",
559
+ "@types/geojson": "^7946.0.16",
560
+ "earcut": "^3.0.1",
561
+ "postprocessing": "^6.37.3",
562
+ "three-stdlib": "^2.36.0"
563
+ }
564
+ }
565
+ `;var He=(o=>(o[o.none=0]="none",o[o.create=1]="create",o[o.remove=2]="remove",o))(He||{});function ws(o,t){const e=o.position.clone().setZ(o.maxZ).applyMatrix4(o.matrixWorld);return t.distanceTo(e)}function xs(o){const t=o.scale,e=new h.Vector3(-t.x,-t.y,0).applyMatrix4(o.matrixWorld),n=new h.Vector3(t.x,t.y,0).applyMatrix4(o.matrixWorld);return e.sub(n).length()}function Ls(o){return o.distToCamera/o.sizeInWorld*.8}function Ss(o,t,e,n){const i=Ls(o);if(o.isLeaf){if(o.inFrustum&&o.z<e&&(o.z<t||o.showing)&&(o.z<t||i<n))return 1}else if(o.z>=t&&(o.z>e||i>n))return 2;return 0}function Ms(o,t,e,n){const i=[],r=n+1,s=t*2,a=0,l=.25,u=o.imgSource[0].projectionID==="4326";if(n===0&&u){const d=e,c=new h.Vector3(.5,1,1),p=new le(s,d,r),f=new le(s,d,r);p.position.set(-.25,0,a),p.scale.copy(c),f.position.set(l,0,a),f.scale.copy(c),i.push(p,f)}else{const d=e*2,c=new h.Vector3(.5,.5,1),p=new le(s,d,r),f=new le(s+1,d,r),m=new le(s,d+1,r),v=new le(s+1,d+1,r);p.position.set(-.25,l,a),p.scale.copy(c),f.position.set(l,l,a),f.scale.copy(c),m.position.set(-.25,-.25,a),m.scale.copy(c),v.position.set(l,-.25,a),v.scale.copy(c),i.push(p,f,m,v)}return i}const _s=10,Zs=new h.InstancedBufferGeometry,Is=new h.Vector3,Ts=new h.Matrix4,Ps=new h.Box3(new h.Vector3(-.5,-.5,0),new h.Vector3(.5,.5,1)),Un=new h.Frustum,Fe=class Fe extends h.Mesh{constructor(e=0,n=0,i=0){super(Zs,[]);x(this,"x");x(this,"y");x(this,"z");x(this,"isTile",!0);x(this,"parent",null);x(this,"children",[]);x(this,"_ready",!1);x(this,"_isDummy",!1);x(this,"_showing",!1);x(this,"_maxZ",0);x(this,"distToCamera",0);x(this,"sizeInWorld",0);x(this,"_loaded",!1);x(this,"_inFrustum",!1);this.x=e,this.y=n,this.z=i,this.name=`Tile ${i}-${e}-${n}`,this.up.set(0,0,1),this.matrixAutoUpdate=!1}static get downloadThreads(){return Fe._downloadThreads}get isDummy(){return this._isDummy}get showing(){return this._showing}set showing(e){this._showing=e,this.material.forEach(n=>n.visible=e)}get maxZ(){return this._maxZ}set maxZ(e){this._maxZ=e}get index(){return this.parent?this.parent.children.indexOf(this):-1}get loaded(){return this._loaded}get inFrustum(){return this._inFrustum}set inFrustum(e){this._inFrustum=e}get isLeaf(){return this.children.filter(e=>e.isTile).length===0}traverse(e){e(this),this.children.forEach(n=>{n.isTile&&n.traverse(e)})}traverseVisible(e){this.visible&&(e(this),this.children.forEach(n=>{n.isTile&&n.traverseVisible(e)}))}raycast(e,n){this.showing&&this.loaded&&this.isTile&&super.raycast(e,n)}LOD(e){if(Fe.downloadThreads>_s)return{action:He.none};let n=[];const{loader:i,minLevel:r,maxLevel:s,LODThreshold:a}=e,l=Ss(this,r,s,a);return l===He.create&&(n=Ms(i,this.x,this.y,this.z),this.add(...n)),{action:l,newTiles:n}}_checkVisible(){const e=this.parent;if(e&&e.isTile){const n=e.children.filter(r=>r.isTile),i=n.every(r=>r.loaded);e.showing=!i,n.forEach(r=>r.showing=i)}return this}async _load(e){Fe._downloadThreads++;const{x:n,y:i,z:r}=this,s=await e.load({x:n,y:i,z:r,bounds:[-1/0,-1/0,1/0,1/0]});return this.material=s.materials,this.geometry=s.geometry,this.maxZ=this.geometry.boundingBox?.max.z||0,this._loaded=!0,Fe._downloadThreads--,this}_init(){this.updateMatrix(),this.updateMatrixWorld(),this.sizeInWorld=xs(this)}update(e){if(console.assert(this.z===0),!this.parent)return this;Un.setFromProjectionMatrix(Ts.multiplyMatrices(e.camera.projectionMatrix,e.camera.matrixWorldInverse));const n=e.camera.getWorldPosition(Is);return this.traverse(i=>{i.receiveShadow=this.receiveShadow,i.castShadow=this.castShadow;const r=Ps.clone().applyMatrix4(i.matrixWorld);r.max.setY(9e3),i.inFrustum=Un.intersectsBox(r),i.distToCamera=ws(i,n);const{action:s,newTiles:a}=i.LOD(e);this._doAction(i,s,a,e)}),this._checkReady(),this}_doAction(e,n,i,r){return n===He.create?i?.forEach(s=>{s._init(),s._isDummy=s.z<r.minLevel,this.dispatchEvent({type:"tile-created",tile:s}),s.isDummy||s._load(r.loader).then(()=>{s._checkVisible(),this.dispatchEvent({type:"tile-loaded",tile:s})})}):n===He.remove&&(e.showing=!0,e._unLoad(!1,r.loader),this.dispatchEvent({type:"tile-unload",tile:e})),this}reload(e){return this._unLoad(!0,e),this}_checkReady(){return this._ready||(this._ready=!0,this.traverse(e=>{if(e.isLeaf&&e.loaded&&!e.isDummy){this._ready=!1;return}}),this._ready&&this.dispatchEvent({type:"ready"})),this}_unLoad(e,n){return e&&this.isTile&&!this.isDummy&&(this.dispatchEvent({type:"unload"}),n?.unload?.(this)),this.children.forEach(i=>i._unLoad(!0,n)),this.clear(),this}};x(Fe,"_downloadThreads",0);let le=Fe;class We{constructor(t){x(this,"dataType","image");x(this,"attribution","isource");x(this,"minLevel",0);x(this,"maxLevel",18);x(this,"projectionID","3857");x(this,"url","");x(this,"subdomains",[]);x(this,"s","");x(this,"opacity",1);x(this,"isTMS",!1);x(this,"bounds",[-180,-85,180,85]);x(this,"_projectionBounds",[-1/0,-1/0,1/0,1/0]);Object.assign(this,t)}getUrl(t,e,n){const i={...this,x:t,y:e,z:n};return As(this.url,i)}_getUrl(t,e,n){const i=this.subdomains.length;if(i>0){const s=Math.floor(Math.random()*i);this.s=this.subdomains[s]}const r=this.isTMS?Math.pow(2,n)-1-e:e;return this.getUrl(t,r,n)}static create(t){return new We(t)}}function As(o,t){const e=/\{ *([\w_-]+) *\}/g;return o.replace(e,(n,i)=>{const r=t[i]??(()=>{throw new Error(`source url template error, No value provided for variable: ${n}`)})();return typeof r=="function"?r(t):r})}const{version:ta,author:na}=JSON.parse(vs);function Ws(o){return ie.registerMaterialLoader(o),o}function Yn(o){return ie.registerGeometryLoader(o),o}Ws(new gs);class Kn{constructor(t=4){this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(t){if(!this.workers[t]){const e=this.workerCreator();e.addEventListener("message",this._onMessage.bind(this,t)),this.workers[t]=e}}_getIdleWorker(){for(let t=0;t<this.pool;t++)if(!(this.workerStatus&1<<t))return t;return-1}_onMessage(t,e){const n=this.workersResolve[t];if(n&&n(e),this.queue.length){const{resolve:i,msg:r,transfer:s}=this.queue.shift();this.workersResolve[t]=i,this.workers[t].postMessage(r,s)}else this.workerStatus^=1<<t}setWorkerCreator(t){this.workerCreator=t}setWorkerLimit(t){this.pool=t}postMessage(t,e){return new Promise(n=>{const i=this._getIdleWorker();i!==-1?(this._initWorker(i),this.workerStatus|=1<<i,this.workersResolve[i]=n,this.workers[i].postMessage(t,e)):this.queue.push({resolve:n,msg:t,transfer:e})})}dispose(){this.workers.forEach(t=>t.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const Bn="dmFyIGNlPU9iamVjdC5kZWZpbmVQcm9wZXJ0eTt2YXIgbWU9KGosWixxKT0+WiBpbiBqP2NlKGosWix7ZW51bWVyYWJsZTohMCxjb25maW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charCodeAt(0)),Nn=typeof self<"u"&&self.Blob&&new Blob([Gs(Bn)],{type:"text/javascript;charset=utf-8"});function Vs(o){let t;try{if(t=Nn&&(self.URL||self.webkitURL).createObjectURL(Nn),!t)throw"";const e=new Worker(t,{name:o?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;base64,"+Bn,{name:o?.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}/* Copyright 2015-2021 Esri. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 @preserve */const Cs=function(){var o={};o.defaultNoDataValue=-34027999387901484e22,o.decode=function(s,a){a=a||{};var l=a.encodedMaskData||a.encodedMaskData===null,u=i(s,a.inputOffset||0,l),d=a.noDataValue!==null?a.noDataValue:o.defaultNoDataValue,c=t(u,a.pixelType||Float32Array,a.encodedMaskData,d,a.returnMask),p={width:u.width,height:u.height,pixelData:c.resultPixels,minValue:c.minValue,maxValue:u.pixels.maxValue,noDataValue:d};return c.resultMask&&(p.maskData=c.resultMask),a.returnEncodedMask&&u.mask&&(p.encodedMaskData=u.mask.bitset?u.mask.bitset:null),a.returnFileInfo&&(p.fileInfo=e(u),a.computeUsedBitDepths&&(p.fileInfo.bitDepths=n(u))),p};var t=function(s,a,l,u,d){var c=0,p=s.pixels.numBlocksX,f=s.pixels.numBlocksY,m=Math.floor(s.width/p),v=Math.floor(s.height/f),g=2*s.maxZError,b=Number.MAX_VALUE,y;l=l||(s.mask?s.mask.bitset:null);var w,S;w=new a(s.width*s.height),d&&l&&(S=new Uint8Array(s.width*s.height));for(var P=new Float32Array(m*v),I,T,M=0;M<=f;M++){var A=M!==f?v:s.height%f;if(A!==0)for(var L=0;L<=p;L++){var Z=L!==p?m:s.width%p;if(Z!==0){var W=M*s.width*v+L*m,C=s.width-Z,V=s.pixels.blocks[c],D,G,X;V.encoding<2?(V.encoding===0?D=V.rawData:(r(V.stuffedData,V.bitsPerPixel,V.numValidPixels,V.offset,g,P,s.pixels.maxValue),D=P),G=0):V.encoding===2?X=0:X=V.offset;var U;if(l)for(T=0;T<A;T++){for(W&7&&(U=l[W>>3],U<<=W&7),I=0;I<Z;I++)W&7||(U=l[W>>3]),U&128?(S&&(S[W]=1),y=V.encoding<2?D[G++]:X,b=b>y?y:b,w[W++]=y):(S&&(S[W]=0),w[W++]=u),U<<=1;W+=C}else if(V.encoding<2)for(T=0;T<A;T++){for(I=0;I<Z;I++)y=D[G++],b=b>y?y:b,w[W++]=y;W+=C}else for(b=b>X?X:b,T=0;T<A;T++){for(I=0;I<Z;I++)w[W++]=X;W+=C}if(V.encoding===1&&G!==V.numValidPixels)throw"Block and Mask do not match";c++}}}return{resultPixels:w,resultMask:S,minValue:b}},e=function(s){return{fileIdentifierString:s.fileIdentifierString,fileVersion:s.fileVersion,imageType:s.imageType,height:s.height,width:s.width,maxZError:s.maxZError,eofOffset:s.eofOffset,mask:s.mask?{numBlocksX:s.mask.numBlocksX,numBlocksY:s.mask.numBlocksY,numBytes:s.mask.numBytes,maxValue:s.mask.maxValue}:null,pixels:{numBlocksX:s.pixels.numBlocksX,numBlocksY:s.pixels.numBlocksY,numBytes:s.pixels.numBytes,maxValue:s.pixels.maxValue,noDataValue:s.noDataValue}}},n=function(s){for(var a=s.pixels.numBlocksX*s.pixels.numBlocksY,l={},u=0;u<a;u++){var d=s.pixels.blocks[u];d.encoding===0?l.float32=!0:d.encoding===1?l[d.bitsPerPixel]=!0:l[0]=!0}return Object.keys(l)},i=function(s,a,l){var u={},d=new Uint8Array(s,a,10);if(u.fileIdentifierString=String.fromCharCode.apply(null,d),u.fileIdentifierString.trim()!=="CntZImage")throw"Unexpected file identifier string: "+u.fileIdentifierString;a+=10;var c=new DataView(s,a,24);if(u.fileVersion=c.getInt32(0,!0),u.imageType=c.getInt32(4,!0),u.height=c.getUint32(8,!0),u.width=c.getUint32(12,!0),u.maxZError=c.getFloat64(16,!0),a+=24,!l)if(c=new DataView(s,a,16),u.mask={},u.mask.numBlocksY=c.getUint32(0,!0),u.mask.numBlocksX=c.getUint32(4,!0),u.mask.numBytes=c.getUint32(8,!0),u.mask.maxValue=c.getFloat32(12,!0),a+=16,u.mask.numBytes>0){var p=new Uint8Array(Math.ceil(u.width*u.height/8));c=new DataView(s,a,u.mask.numBytes);var f=c.getInt16(0,!0),m=2,v=0;do{if(f>0)for(;f--;)p[v++]=c.getUint8(m++);else{var g=c.getUint8(m++);for(f=-f;f--;)p[v++]=g}f=c.getInt16(m,!0),m+=2}while(m<u.mask.numBytes);if(f!==-32768||v<p.length)throw"Unexpected end of mask RLE encoding";u.mask.bitset=p,a+=u.mask.numBytes}else u.mask.numBytes|u.mask.numBlocksY|u.mask.maxValue||(u.mask.bitset=new Uint8Array(Math.ceil(u.width*u.height/8)));c=new DataView(s,a,16),u.pixels={},u.pixels.numBlocksY=c.getUint32(0,!0),u.pixels.numBlocksX=c.getUint32(4,!0),u.pixels.numBytes=c.getUint32(8,!0),u.pixels.maxValue=c.getFloat32(12,!0),a+=16;var b=u.pixels.numBlocksX,y=u.pixels.numBlocksY,w=b+(u.width%b>0?1:0),S=y+(u.height%y>0?1:0);u.pixels.blocks=new Array(w*S);for(var P=0,I=0;I<S;I++)for(var T=0;T<w;T++){var M=0,A=s.byteLength-a;c=new DataView(s,a,Math.min(10,A));var L={};u.pixels.blocks[P++]=L;var Z=c.getUint8(0);if(M++,L.encoding=Z&63,L.encoding>3)throw"Invalid block encoding ("+L.encoding+")";if(L.encoding===2){a++;continue}if(Z!==0&&Z!==2){if(Z>>=6,L.offsetType=Z,Z===2)L.offset=c.getInt8(1),M++;else if(Z===1)L.offset=c.getInt16(1,!0),M+=2;else if(Z===0)L.offset=c.getFloat32(1,!0),M+=4;else throw"Invalid block offset type";if(L.encoding===1)if(Z=c.getUint8(M),M++,L.bitsPerPixel=Z&63,Z>>=6,L.numValidPixelsType=Z,Z===2)L.numValidPixels=c.getUint8(M),M++;else if(Z===1)L.numValidPixels=c.getUint16(M,!0),M+=2;else if(Z===0)L.numValidPixels=c.getUint32(M,!0),M+=4;else throw"Invalid valid pixel count type"}if(a+=M,L.encoding!==3){var W,C;if(L.encoding===0){var V=(u.pixels.numBytes-1)/4;if(V!==Math.floor(V))throw"uncompressed block has invalid length";W=new ArrayBuffer(V*4),C=new Uint8Array(W),C.set(new Uint8Array(s,a,V*4));var D=new Float32Array(W);L.rawData=D,a+=V*4}else if(L.encoding===1){var G=Math.ceil(L.numValidPixels*L.bitsPerPixel/8),X=Math.ceil(G/4);W=new ArrayBuffer(X*4),C=new Uint8Array(W),C.set(new Uint8Array(s,a,G)),L.stuffedData=new Uint32Array(W),a+=G}}}return u.eofOffset=a,u},r=function(s,a,l,u,d,c,p){var f=(1<<a)-1,m=0,v,g=0,b,y,w=Math.ceil((p-u)/d),S=s.length*4-Math.ceil(a*l/8);for(s[s.length-1]<<=8*S,v=0;v<l;v++){if(g===0&&(y=s[m++],g=32),g>=a)b=y>>>g-a&f,g-=a;else{var P=a-g;b=(y&f)<<P&f,y=s[m++],g=32-P,b+=y>>>g}c[v]=b<w?u+b*d:p}return c};return o}(),ks=function(){var o={unstuff:function(i,r,s,a,l,u,d,c){var p=(1<<s)-1,f=0,m,v=0,g,b,y,w,S=i.length*4-Math.ceil(s*a/8);if(i[i.length-1]<<=8*S,l)for(m=0;m<a;m++)v===0&&(b=i[f++],v=32),v>=s?(g=b>>>v-s&p,v-=s):(y=s-v,g=(b&p)<<y&p,b=i[f++],v=32-y,g+=b>>>v),r[m]=l[g];else for(w=Math.ceil((c-u)/d),m=0;m<a;m++)v===0&&(b=i[f++],v=32),v>=s?(g=b>>>v-s&p,v-=s):(y=s-v,g=(b&p)<<y&p,b=i[f++],v=32-y,g+=b>>>v),r[m]=g<w?u+g*d:c},unstuffLUT:function(i,r,s,a,l,u){var d=(1<<r)-1,c=0,p=0,f=0,m=0,v=0,g,b=[],y=i.length*4-Math.ceil(r*s/8);i[i.length-1]<<=8*y;var w=Math.ceil((u-a)/l);for(p=0;p<s;p++)m===0&&(g=i[c++],m=32),m>=r?(v=g>>>m-r&d,m-=r):(f=r-m,v=(g&d)<<f&d,g=i[c++],m=32-f,v+=g>>>m),b[p]=v<w?a+v*l:u;return b.unshift(a),b},unstuff2:function(i,r,s,a,l,u,d,c){var p=(1<<s)-1,f=0,m,v=0,g=0,b,y,w;if(l)for(m=0;m<a;m++)v===0&&(y=i[f++],v=32,g=0),v>=s?(b=y>>>g&p,v-=s,g+=s):(w=s-v,b=y>>>g&p,y=i[f++],v=32-w,b|=(y&(1<<w)-1)<<s-w,g=w),r[m]=l[b];else{var S=Math.ceil((c-u)/d);for(m=0;m<a;m++)v===0&&(y=i[f++],v=32,g=0),v>=s?(b=y>>>g&p,v-=s,g+=s):(w=s-v,b=y>>>g&p,y=i[f++],v=32-w,b|=(y&(1<<w)-1)<<s-w,g=w),r[m]=b<S?u+b*d:c}return r},unstuffLUT2:function(i,r,s,a,l,u){var d=(1<<r)-1,c=0,p=0,f=0,m=0,v=0,g=0,b,y=[],w=Math.ceil((u-a)/l);for(p=0;p<s;p++)m===0&&(b=i[c++],m=32,g=0),m>=r?(v=b>>>g&d,m-=r,g+=r):(f=r-m,v=b>>>g&d,b=i[c++],m=32-f,v|=(b&(1<<f)-1)<<r-f,g=f),y[p]=v<w?a+v*l:u;return y.unshift(a),y},originalUnstuff:function(i,r,s,a){var l=(1<<s)-1,u=0,d,c=0,p,f,m,v=i.length*4-Math.ceil(s*a/8);for(i[i.length-1]<<=8*v,d=0;d<a;d++)c===0&&(f=i[u++],c=32),c>=s?(p=f>>>c-s&l,c-=s):(m=s-c,p=(f&l)<<m&l,f=i[u++],c=32-m,p+=f>>>c),r[d]=p;return r},originalUnstuff2:function(i,r,s,a){var l=(1<<s)-1,u=0,d,c=0,p=0,f,m,v;for(d=0;d<a;d++)c===0&&(m=i[u++],c=32,p=0),c>=s?(f=m>>>p&l,c-=s,p+=s):(v=s-c,f=m>>>p&l,m=i[u++],c=32-v,f|=(m&(1<<v)-1)<<s-v,p=v),r[d]=f;return r}},t={HUFFMAN_LUT_BITS_MAX:12,computeChecksumFletcher32:function(i){for(var r=65535,s=65535,a=i.length,l=Math.floor(a/2),u=0;l;){var d=l>=359?359:l;l-=d;do r+=i[u++]<<8,s+=r+=i[u++];while(--d);r=(r&65535)+(r>>>16),s=(s&65535)+(s>>>16)}return a&1&&(s+=r+=i[u]<<8),r=(r&65535)+(r>>>16),s=(s&65535)+(s>>>16),(s<<16|r)>>>0},readHeaderInfo:function(i,r){var s=r.ptr,a=new Uint8Array(i,s,6),l={};if(l.fileIdentifierString=String.fromCharCode.apply(null,a),l.fileIdentifierString.lastIndexOf("Lerc2",0)!==0)throw"Unexpected file identifier string (expect Lerc2 ): "+l.fileIdentifierString;s+=6;var u=new DataView(i,s,8),d=u.getInt32(0,!0);l.fileVersion=d,s+=4,d>=3&&(l.checksum=u.getUint32(4,!0),s+=4),u=new DataView(i,s,12),l.height=u.getUint32(0,!0),l.width=u.getUint32(4,!0),s+=8,d>=4?(l.numDims=u.getUint32(8,!0),s+=4):l.numDims=1,u=new DataView(i,s,40),l.numValidPixel=u.getUint32(0,!0),l.microBlockSize=u.getInt32(4,!0),l.blobSize=u.getInt32(8,!0),l.imageType=u.getInt32(12,!0),l.maxZError=u.getFloat64(16,!0),l.zMin=u.getFloat64(24,!0),l.zMax=u.getFloat64(32,!0),s+=40,r.headerInfo=l,r.ptr=s;var c,p;if(d>=3&&(p=d>=4?52:48,c=this.computeChecksumFletcher32(new Uint8Array(i,s-p,l.blobSize-14)),c!==l.checksum))throw"Checksum failed.";return!0},checkMinMaxRanges:function(i,r){var s=r.headerInfo,a=this.getDataTypeArray(s.imageType),l=s.numDims*this.getDataTypeSize(s.imageType),u=this.readSubArray(i,r.ptr,a,l),d=this.readSubArray(i,r.ptr+l,a,l);r.ptr+=2*l;var c,p=!0;for(c=0;c<s.numDims;c++)if(u[c]!==d[c]){p=!1;break}return s.minValues=u,s.maxValues=d,p},readSubArray:function(i,r,s,a){var l;if(s===Uint8Array)l=new Uint8Array(i,r,a);else{var u=new ArrayBuffer(a),d=new Uint8Array(u);d.set(new Uint8Array(i,r,a)),l=new s(u)}return l},readMask:function(i,r){var s=r.ptr,a=r.headerInfo,l=a.width*a.height,u=a.numValidPixel,d=new DataView(i,s,4),c={};if(c.numBytes=d.getUint32(0,!0),s+=4,(u===0||l===u)&&c.numBytes!==0)throw"invalid mask";var p,f;if(u===0)p=new Uint8Array(Math.ceil(l/8)),c.bitset=p,f=new Uint8Array(l),r.pixels.resultMask=f,s+=c.numBytes;else if(c.numBytes>0){p=new Uint8Array(Math.ceil(l/8)),d=new DataView(i,s,c.numBytes);var m=d.getInt16(0,!0),v=2,g=0,b=0;do{if(m>0)for(;m--;)p[g++]=d.getUint8(v++);else for(b=d.getUint8(v++),m=-m;m--;)p[g++]=b;m=d.getInt16(v,!0),v+=2}while(v<c.numBytes);if(m!==-32768||g<p.length)throw"Unexpected end of mask RLE encoding";f=new Uint8Array(l);var y=0,w=0;for(w=0;w<l;w++)w&7?(y=p[w>>3],y<<=w&7):y=p[w>>3],y&128&&(f[w]=1);r.pixels.resultMask=f,c.bitset=p,s+=c.numBytes}return r.ptr=s,r.mask=c,!0},readDataOneSweep:function(i,r,s,a){var l=r.ptr,u=r.headerInfo,d=u.numDims,c=u.width*u.height,p=u.imageType,f=u.numValidPixel*t.getDataTypeSize(p)*d,m,v=r.pixels.resultMask;if(s===Uint8Array)m=new Uint8Array(i,l,f);else{var g=new ArrayBuffer(f),b=new Uint8Array(g);b.set(new Uint8Array(i,l,f)),m=new s(g)}if(m.length===c*d)a?r.pixels.resultPixels=t.swapDimensionOrder(m,c,d,s,!0):r.pixels.resultPixels=m;else{r.pixels.resultPixels=new s(c*d);var y=0,w=0,S=0,P=0;if(d>1){if(a){for(w=0;w<c;w++)if(v[w])for(P=w,S=0;S<d;S++,P+=c)r.pixels.resultPixels[P]=m[y++]}else for(w=0;w<c;w++)if(v[w])for(P=w*d,S=0;S<d;S++)r.pixels.resultPixels[P+S]=m[y++]}else for(w=0;w<c;w++)v[w]&&(r.pixels.resultPixels[w]=m[y++])}return l+=f,r.ptr=l,!0},readHuffmanTree:function(i,r){var s=this.HUFFMAN_LUT_BITS_MAX,a=new DataView(i,r.ptr,16);r.ptr+=16;var l=a.getInt32(0,!0);if(l<2)throw"unsupported Huffman version";var u=a.getInt32(4,!0),d=a.getInt32(8,!0),c=a.getInt32(12,!0);if(d>=c)return!1;var p=new Uint32Array(c-d);t.decodeBits(i,r,p);var f=[],m,v,g,b;for(m=d;m<c;m++)v=m-(m<u?0:u),f[v]={first:p[m-d],second:null};var y=i.byteLength-r.ptr,w=Math.ceil(y/4),S=new ArrayBuffer(w*4),P=new Uint8Array(S);P.set(new Uint8Array(i,r.ptr,y));var I=new Uint32Array(S),T=0,M,A=0;for(M=I[0],m=d;m<c;m++)v=m-(m<u?0:u),b=f[v].first,b>0&&(f[v].second=M<<T>>>32-b,32-T>=b?(T+=b,T===32&&(T=0,A++,M=I[A])):(T+=b-32,A++,M=I[A],f[v].second|=M>>>32-T));var L=0,Z=0,W=new e;for(m=0;m<f.length;m++)f[m]!==void 0&&(L=Math.max(L,f[m].first));L>=s?Z=s:Z=L;var C=[],V,D,G,X,U,z;for(m=d;m<c;m++)if(v=m-(m<u?0:u),b=f[v].first,b>0)if(V=[b,v],b<=Z)for(D=f[v].second<<Z-b,G=1<<Z-b,g=0;g<G;g++)C[D|g]=V;else for(D=f[v].second,z=W,X=b-1;X>=0;X--)U=D>>>X&1,U?(z.right||(z.right=new e),z=z.right):(z.left||(z.left=new e),z=z.left),X===0&&!z.val&&(z.val=V[1]);return{decodeLut:C,numBitsLUTQick:Z,numBitsLUT:L,tree:W,stuffedData:I,srcPtr:A,bitPos:T}},readHuffman:function(i,r,s,a){var l=r.headerInfo,u=l.numDims,d=r.headerInfo.height,c=r.headerInfo.width,p=c*d,f=this.readHuffmanTree(i,r),m=f.decodeLut,v=f.tree,g=f.stuffedData,b=f.srcPtr,y=f.bitPos,w=f.numBitsLUTQick,S=f.numBitsLUT,P=r.headerInfo.imageType===0?128:0,I,T,M,A=r.pixels.resultMask,L,Z,W,C,V,D,G,X=0;y>0&&(b++,y=0);var U=g[b],z=r.encodeMode===1,j=new s(p*u),H=j,B;if(u<2||z){for(B=0;B<u;B++)if(u>1&&(H=new s(j.buffer,p*B,p),X=0),r.headerInfo.numValidPixel===c*d)for(D=0,C=0;C<d;C++)for(V=0;V<c;V++,D++){if(T=0,L=U<<y>>>32-w,Z=L,32-y<w&&(L|=g[b+1]>>>64-y-w,Z=L),m[Z])T=m[Z][1],y+=m[Z][0];else for(L=U<<y>>>32-S,Z=L,32-y<S&&(L|=g[b+1]>>>64-y-S,Z=L),I=v,G=0;G<S;G++)if(W=L>>>S-G-1&1,I=W?I.right:I.left,!(I.left||I.right)){T=I.val,y=y+G+1;break}y>=32&&(y-=32,b++,U=g[b]),M=T-P,z?(V>0?M+=X:C>0?M+=H[D-c]:M+=X,M&=255,H[D]=M,X=M):H[D]=M}else for(D=0,C=0;C<d;C++)for(V=0;V<c;V++,D++)if(A[D]){if(T=0,L=U<<y>>>32-w,Z=L,32-y<w&&(L|=g[b+1]>>>64-y-w,Z=L),m[Z])T=m[Z][1],y+=m[Z][0];else for(L=U<<y>>>32-S,Z=L,32-y<S&&(L|=g[b+1]>>>64-y-S,Z=L),I=v,G=0;G<S;G++)if(W=L>>>S-G-1&1,I=W?I.right:I.left,!(I.left||I.right)){T=I.val,y=y+G+1;break}y>=32&&(y-=32,b++,U=g[b]),M=T-P,z?(V>0&&A[D-1]?M+=X:C>0&&A[D-c]?M+=H[D-c]:M+=X,M&=255,H[D]=M,X=M):H[D]=M}}else for(D=0,C=0;C<d;C++)for(V=0;V<c;V++)if(D=C*c+V,!A||A[D])for(B=0;B<u;B++,D+=p){if(T=0,L=U<<y>>>32-w,Z=L,32-y<w&&(L|=g[b+1]>>>64-y-w,Z=L),m[Z])T=m[Z][1],y+=m[Z][0];else for(L=U<<y>>>32-S,Z=L,32-y<S&&(L|=g[b+1]>>>64-y-S,Z=L),I=v,G=0;G<S;G++)if(W=L>>>S-G-1&1,I=W?I.right:I.left,!(I.left||I.right)){T=I.val,y=y+G+1;break}y>=32&&(y-=32,b++,U=g[b]),M=T-P,H[D]=M}r.ptr=r.ptr+(b+1)*4+(y>0?4:0),r.pixels.resultPixels=j,u>1&&!a&&(r.pixels.resultPixels=t.swapDimensionOrder(j,p,u,s))},decodeBits:function(i,r,s,a,l){{var u=r.headerInfo,d=u.fileVersion,c=0,p=i.byteLength-r.ptr>=5?5:i.byteLength-r.ptr,f=new DataView(i,r.ptr,p),m=f.getUint8(0);c++;var v=m>>6,g=v===0?4:3-v,b=(m&32)>0,y=m&31,w=0;if(g===1)w=f.getUint8(c),c++;else if(g===2)w=f.getUint16(c,!0),c+=2;else if(g===4)w=f.getUint32(c,!0),c+=4;else throw"Invalid valid pixel count type";var S=2*u.maxZError,P,I,T,M,A,L,Z,W,C,V=u.numDims>1?u.maxValues[l]:u.zMax;if(b){for(r.counter.lut++,W=f.getUint8(c),c++,M=Math.ceil((W-1)*y/8),A=Math.ceil(M/4),I=new ArrayBuffer(A*4),T=new Uint8Array(I),r.ptr+=c,T.set(new Uint8Array(i,r.ptr,M)),Z=new Uint32Array(I),r.ptr+=M,C=0;W-1>>>C;)C++;M=Math.ceil(w*C/8),A=Math.ceil(M/4),I=new ArrayBuffer(A*4),T=new Uint8Array(I),T.set(new Uint8Array(i,r.ptr,M)),P=new Uint32Array(I),r.ptr+=M,d>=3?L=o.unstuffLUT2(Z,y,W-1,a,S,V):L=o.unstuffLUT(Z,y,W-1,a,S,V),d>=3?o.unstuff2(P,s,C,w,L):o.unstuff(P,s,C,w,L)}else r.counter.bitstuffer++,C=y,r.ptr+=c,C>0&&(M=Math.ceil(w*C/8),A=Math.ceil(M/4),I=new ArrayBuffer(A*4),T=new Uint8Array(I),T.set(new Uint8Array(i,r.ptr,M)),P=new Uint32Array(I),r.ptr+=M,d>=3?a==null?o.originalUnstuff2(P,s,C,w):o.unstuff2(P,s,C,w,!1,a,S,V):a==null?o.originalUnstuff(P,s,C,w):o.unstuff(P,s,C,w,!1,a,S,V))}},readTiles:function(i,r,s,a){var l=r.headerInfo,u=l.width,d=l.height,c=u*d,p=l.microBlockSize,f=l.imageType,m=t.getDataTypeSize(f),v=Math.ceil(u/p),g=Math.ceil(d/p);r.pixels.numBlocksY=g,r.pixels.numBlocksX=v,r.pixels.ptr=0;var b=0,y=0,w=0,S=0,P=0,I=0,T=0,M=0,A=0,L=0,Z=0,W=0,C=0,V=0,D=0,G=0,X,U,z,j,H,B,J=new s(p*p),de=d%p||p,Ke=u%p||p,Le,pe,Se=l.numDims,Me,ce=r.pixels.resultMask,re=r.pixels.resultPixels,wt=l.fileVersion,et=wt>=5?14:15,fe,tt=l.zMax,ve;for(w=0;w<g;w++)for(P=w!==g-1?p:de,S=0;S<v;S++)for(I=S!==v-1?p:Ke,Z=w*u*p+S*p,W=u-I,Me=0;Me<Se;Me++){if(Se>1?(ve=re,Z=w*u*p+S*p,re=new s(r.pixels.resultPixels.buffer,c*Me*m,c),tt=l.maxValues[Me]):ve=null,T=i.byteLength-r.ptr,X=new DataView(i,r.ptr,Math.min(10,T)),U={},G=0,M=X.getUint8(0),G++,fe=l.fileVersion>=5?M&4:0,A=M>>6&255,L=M>>2&et,L!==(S*p>>3&et)||fe&&Me===0)throw"integrity issue";if(B=M&3,B>3)throw r.ptr+=G,"Invalid block encoding ("+B+")";if(B===2){if(fe)if(ce)for(b=0;b<P;b++)for(y=0;y<I;y++)ce[Z]&&(re[Z]=ve[Z]),Z++;else for(b=0;b<P;b++)for(y=0;y<I;y++)re[Z]=ve[Z],Z++;r.counter.constant++,r.ptr+=G;continue}else if(B===0){if(fe)throw"integrity issue";if(r.counter.uncompressed++,r.ptr+=G,C=P*I*m,V=i.byteLength-r.ptr,C=C<V?C:V,z=new ArrayBuffer(C%m===0?C:C+m-C%m),j=new Uint8Array(z),j.set(new Uint8Array(i,r.ptr,C)),H=new s(z),D=0,ce)for(b=0;b<P;b++){for(y=0;y<I;y++)ce[Z]&&(re[Z]=H[D++]),Z++;Z+=W}else for(b=0;b<P;b++){for(y=0;y<I;y++)re[Z++]=H[D++];Z+=W}r.ptr+=D*m}else if(Le=t.getDataTypeUsed(fe&&f<6?4:f,A),pe=t.getOnePixel(U,G,Le,X),G+=t.getDataTypeSize(Le),B===3)if(r.ptr+=G,r.counter.constantoffset++,ce)for(b=0;b<P;b++){for(y=0;y<I;y++)ce[Z]&&(re[Z]=fe?Math.min(tt,ve[Z]+pe):pe),Z++;Z+=W}else for(b=0;b<P;b++){for(y=0;y<I;y++)re[Z]=fe?Math.min(tt,ve[Z]+pe):pe,Z++;Z+=W}else if(r.ptr+=G,t.decodeBits(i,r,J,pe,Me),G=0,fe)if(ce)for(b=0;b<P;b++){for(y=0;y<I;y++)ce[Z]&&(re[Z]=J[G++]+ve[Z]),Z++;Z+=W}else for(b=0;b<P;b++){for(y=0;y<I;y++)re[Z]=J[G++]+ve[Z],Z++;Z+=W}else if(ce)for(b=0;b<P;b++){for(y=0;y<I;y++)ce[Z]&&(re[Z]=J[G++]),Z++;Z+=W}else for(b=0;b<P;b++){for(y=0;y<I;y++)re[Z++]=J[G++];Z+=W}}Se>1&&!a&&(r.pixels.resultPixels=t.swapDimensionOrder(r.pixels.resultPixels,c,Se,s))},formatFileInfo:function(i){return{fileIdentifierString:i.headerInfo.fileIdentifierString,fileVersion:i.headerInfo.fileVersion,imageType:i.headerInfo.imageType,height:i.headerInfo.height,width:i.headerInfo.width,numValidPixel:i.headerInfo.numValidPixel,microBlockSize:i.headerInfo.microBlockSize,blobSize:i.headerInfo.blobSize,maxZError:i.headerInfo.maxZError,pixelType:t.getPixelType(i.headerInfo.imageType),eofOffset:i.eofOffset,mask:i.mask?{numBytes:i.mask.numBytes}:null,pixels:{numBlocksX:i.pixels.numBlocksX,numBlocksY:i.pixels.numBlocksY,maxValue:i.headerInfo.zMax,minValue:i.headerInfo.zMin,noDataValue:i.noDataValue}}},constructConstantSurface:function(i,r){var s=i.headerInfo.zMax,a=i.headerInfo.zMin,l=i.headerInfo.maxValues,u=i.headerInfo.numDims,d=i.headerInfo.height*i.headerInfo.width,c=0,p=0,f=0,m=i.pixels.resultMask,v=i.pixels.resultPixels;if(m)if(u>1){if(r)for(c=0;c<u;c++)for(f=c*d,s=l[c],p=0;p<d;p++)m[p]&&(v[f+p]=s);else for(p=0;p<d;p++)if(m[p])for(f=p*u,c=0;c<u;c++)v[f+u]=l[c]}else for(p=0;p<d;p++)m[p]&&(v[p]=s);else if(u>1&&a!==s)if(r)for(c=0;c<u;c++)for(f=c*d,s=l[c],p=0;p<d;p++)v[f+p]=s;else for(p=0;p<d;p++)for(f=p*u,c=0;c<u;c++)v[f+c]=l[c];else for(p=0;p<d*u;p++)v[p]=s},getDataTypeArray:function(i){var r;switch(i){case 0:r=Int8Array;break;case 1:r=Uint8Array;break;case 2:r=Int16Array;break;case 3:r=Uint16Array;break;case 4:r=Int32Array;break;case 5:r=Uint32Array;break;case 6:r=Float32Array;break;case 7:r=Float64Array;break;default:r=Float32Array}return r},getPixelType:function(i){var r;switch(i){case 0:r="S8";break;case 1:r="U8";break;case 2:r="S16";break;case 3:r="U16";break;case 4:r="S32";break;case 5:r="U32";break;case 6:r="F32";break;case 7:r="F64";break;default:r="F32"}return r},isValidPixelValue:function(i,r){if(r==null)return!1;var s;switch(i){case 0:s=r>=-128&&r<=127;break;case 1:s=r>=0&&r<=255;break;case 2:s=r>=-32768&&r<=32767;break;case 3:s=r>=0&&r<=65536;break;case 4:s=r>=-2147483648&&r<=2147483647;break;case 5:s=r>=0&&r<=4294967296;break;case 6:s=r>=-34027999387901484e22&&r<=34027999387901484e22;break;case 7:s=r>=-17976931348623157e292&&r<=17976931348623157e292;break;default:s=!1}return s},getDataTypeSize:function(i){var r=0;switch(i){case 0:case 1:r=1;break;case 2:case 3:r=2;break;case 4:case 5:case 6:r=4;break;case 7:r=8;break;default:r=i}return r},getDataTypeUsed:function(i,r){var s=i;switch(i){case 2:case 4:s=i-r;break;case 3:case 5:s=i-2*r;break;case 6:r===0?s=i:r===1?s=2:s=1;break;case 7:r===0?s=i:s=i-2*r+1;break;default:s=i;break}return s},getOnePixel:function(i,r,s,a){var l=0;switch(s){case 0:l=a.getInt8(r);break;case 1:l=a.getUint8(r);break;case 2:l=a.getInt16(r,!0);break;case 3:l=a.getUint16(r,!0);break;case 4:l=a.getInt32(r,!0);break;case 5:l=a.getUInt32(r,!0);break;case 6:l=a.getFloat32(r,!0);break;case 7:l=a.getFloat64(r,!0);break;default:throw"the decoder does not understand this pixel type"}return l},swapDimensionOrder:function(i,r,s,a,l){var u=0,d=0,c=0,p=0,f=i;if(s>1)if(f=new a(r*s),l)for(u=0;u<r;u++)for(p=u,c=0;c<s;c++,p+=r)f[p]=i[d++];else for(u=0;u<r;u++)for(p=u,c=0;c<s;c++,p+=r)f[d++]=i[p];return f}},e=function(i,r,s){this.val=i,this.left=r,this.right=s},n={decode:function(i,r){r=r||{};var s=r.noDataValue,a=0,l={};if(l.ptr=r.inputOffset||0,l.pixels={},!!t.readHeaderInfo(i,l)){var u=l.headerInfo,d=u.fileVersion,c=t.getDataTypeArray(u.imageType);if(d>5)throw"unsupported lerc version 2."+d;t.readMask(i,l),u.numValidPixel!==u.width*u.height&&!l.pixels.resultMask&&(l.pixels.resultMask=r.maskData);var p=u.width*u.height;l.pixels.resultPixels=new c(p*u.numDims),l.counter={onesweep:0,uncompressed:0,lut:0,bitstuffer:0,constant:0,constantoffset:0};var f=!r.returnPixelInterleavedDims;if(u.numValidPixel!==0)if(u.zMax===u.zMin)t.constructConstantSurface(l,f);else if(d>=4&&t.checkMinMaxRanges(i,l))t.constructConstantSurface(l,f);else{var m=new DataView(i,l.ptr,2),v=m.getUint8(0);if(l.ptr++,v)t.readDataOneSweep(i,l,c,f);else if(d>1&&u.imageType<=1&&Math.abs(u.maxZError-.5)<1e-5){var g=m.getUint8(1);if(l.ptr++,l.encodeMode=g,g>2||d<4&&g>1)throw"Invalid Huffman flag "+g;g?t.readHuffman(i,l,c,f):t.readTiles(i,l,c,f)}else t.readTiles(i,l,c,f)}l.eofOffset=l.ptr;var b;r.inputOffset?(b=l.headerInfo.blobSize+r.inputOffset-l.ptr,Math.abs(b)>=1&&(l.eofOffset=r.inputOffset+l.headerInfo.blobSize)):(b=l.headerInfo.blobSize-l.ptr,Math.abs(b)>=1&&(l.eofOffset=l.headerInfo.blobSize));var y={width:u.width,height:u.height,pixelData:l.pixels.resultPixels,minValue:u.zMin,maxValue:u.zMax,validPixelCount:u.numValidPixel,dimCount:u.numDims,dimStats:{minValues:u.minValues,maxValues:u.maxValues},maskData:l.pixels.resultMask};if(l.pixels.resultMask&&t.isValidPixelValue(u.imageType,s)){var w=l.pixels.resultMask;for(a=0;a<p;a++)w[a]||(y.pixelData[a]=s);y.noDataValue=s}return l.noDataValue=s,r.returnFileInfo&&(y.fileInfo=t.formatFileInfo(l)),y}},getBandCount:function(i){var r=0,s=0,a={};for(a.ptr=0,a.pixels={};s<i.byteLength-58;)t.readHeaderInfo(i,a),s+=a.headerInfo.blobSize,r++,a.ptr=s;return r}};return n}();var Ds=function(){var o=new ArrayBuffer(4),t=new Uint8Array(o),e=new Uint32Array(o);return e[0]=1,t[0]===1}(),Fs={decode:function(o,t){if(!Ds)throw"Big endian system is not supported.";t=t||{};var e=t.inputOffset||0,n=new Uint8Array(o,e,10),i=String.fromCharCode.apply(null,n),r,s;if(i.trim()==="CntZImage")r=Cs,s=1;else if(i.substring(0,5)==="Lerc2")r=ks,s=2;else throw"Unexpected file identifier string: "+i;for(var a=0,l=o.byteLength-10,u,d=[],c,p,f={width:0,height:0,pixels:[],pixelType:t.pixelType,mask:null,statistics:[]},m=0;e<l;){var v=r.decode(o,{inputOffset:e,encodedMaskData:u,maskData:p,returnMask:a===0,returnEncodedMask:a===0,returnFileInfo:!0,returnPixelInterleavedDims:t.returnPixelInterleavedDims,pixelType:t.pixelType||null,noDataValue:t.noDataValue||null});e=v.fileInfo.eofOffset,p=v.maskData,a===0&&(u=v.encodedMaskData,f.width=v.width,f.height=v.height,f.dimCount=v.dimCount||1,f.pixelType=v.pixelType||v.fileInfo.pixelType,f.mask=p),s>1&&(p&&d.push(p),v.fileInfo.mask&&v.fileInfo.mask.numBytes>0&&m++),a++,f.pixels.push(v.pixelData),f.statistics.push({minValue:v.minValue,maxValue:v.maxValue,noDataValue:v.noDataValue,dimStats:v.dimStats})}var g,b,y;if(s>1&&m>1){for(y=f.width*f.height,f.bandMasks=d,p=new Uint8Array(y),p.set(d[0]),g=1;g<d.length;g++)for(c=d[g],b=0;b<y;b++)p[b]=p[b]&c[b];f.maskData=p}return f}};const Os={0:7e3,1:6e3,2:5e3,3:4e3,4:3e3,5:2500,6:2e3,7:1500,8:800,9:500,10:200,11:100,12:40,13:12,14:5,15:2,16:1,17:.5,18:.2,19:.1,20:.01};function zs(o){const{height:t,width:e,pixels:n}=Fs.decode(o),i=new Float32Array(t*e);for(let r=0;r<i.length;r++)i[r]=n[0][r];return{array:i,width:e,height:t}}function Xs(o,t,e){let n=zs(o);e[2]-e[0]<1&&(n=Us(n,e));const{array:i,width:r}=n,a=new ps(r).createTile(i),l=Os[t]||0;return a.getGeometryData(l)}function Us(o,t){function e(a,l,u,d,c,p,f,m){const v=new Float32Array(c*p);for(let b=0;b<p;b++)for(let y=0;y<c;y++){const w=(b+d)*l+(y+u),S=b*c+y;v[S]=a[w]}const g=new Float32Array(m*f);for(let b=0;b<m;b++)for(let y=0;y<f;y++){const w=b*m+y,S=Math.round(y*p/m),I=Math.round(b*c/f)*c+S;g[w]=v[I]}return g}const n=Ys(t,o.width),i=n.sw+1,r=n.sh+1;return{array:e(o.array,o.width,n.sx,n.sy,n.sw,n.sh,i,r),width:i,height:r}}function Ys(o,t){const e=Math.floor(o[0]*t),n=Math.floor(o[1]*t),i=Math.floor((o[2]-o[0])*t),r=Math.floor((o[3]-o[1])*t);return{sx:e,sy:n,sw:i,sh:r}}const Ks=10;class Bs extends Xn{constructor(){super();x(this,"info",{version:"0.10.0",description:"Tile LERC terrain loader. It can load ArcGis-lerc format terrain data."});x(this,"dataType","lerc");x(this,"fileLoader",new h.FileLoader(ie.manager));x(this,"_workerPool",new Kn(0));this.fileLoader.setResponseType("arraybuffer"),this._workerPool.setWorkerCreator(()=>new Vs)}async doLoad(e,n){this._workerPool.pool===0&&this._workerPool.setWorkerLimit(Ks);const{z:i,bounds:r}=n,s=await this.fileLoader.loadAsync(e).catch(()=>new Float32Array(256*256)),a=Xs(s,i,r);return new Ut().setData(a)}}Yn(new Bs);const jn="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIGModCl7cmV0dXJuIGEodC5kYXRhKX1mdW5jdGlvbiBhKHQpe2Z1bmN0aW9uIG4oZSx1KXtjb25zdCByPXUqNCxbaSxmLGcsbF09ZS5zbGljZShyLHIrNCk7cmV0dXJuIGw9PT0wPzA6LTFlNCsoaTw8MTZ8Zjw8OHxnKSouMX1jb25zdCBvPXQubGVuZ3RoPj4+MixzPW5ldyBGbG9hdDMyQXJyYXkobyk7Zm9yKGxldCBlPTA7ZTxvO2UrKylzW2VdPW4odCxlKTtyZXR1cm4gc31zZWxmLm9ubWVzc2FnZT10PT57Y29uc3Qgbj1jKHQuZGF0YS5pbWdEYXRhKTtzZWxmLnBvc3RNZXNzYWdlKG4pfX0pKCk7Cg==",Ns=o=>Uint8Array.from(atob(o),t=>t.charCodeAt(0)),Rn=typeof self<"u"&&self.Blob&&new Blob([Ns(jn)],{type:"text/javascript;charset=utf-8"});function js(o){let t;try{if(t=Rn&&(self.URL||self.webkitURL).createObjectURL(Rn),!t)throw"";const e=new Worker(t,{name:o?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;base64,"+jn,{name:o?.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}const Rs=10;class Js extends Xn{constructor(){super();x(this,"info",{version:"0.10.0",description:"Mapbox-RGB terrain loader, It can load Mapbox-RGB terrain data."});x(this,"dataType","terrain-rgb");x(this,"imageLoader",new h.ImageLoader(ie.manager));x(this,"_workerPool",new Kn(0));this._workerPool.setWorkerCreator(()=>new js)}async doLoad(e,n){const i=await this.imageLoader.loadAsync(e).catch(u=>new Image),r=h.MathUtils.clamp((n.z+2)*3,2,64),s=Qs(i,n.bounds,r);let a;this._workerPool.pool===0&&this._workerPool.setWorkerLimit(Rs),a=(await this._workerPool.postMessage({imgData:s},[s.data.buffer])).data;const l=new Ut;return l.setData(a),l}}function Qs(o,t,e){const n=kn(t,o.width);e=Math.min(e,n.sw);const r=new OffscreenCanvas(e,e).getContext("2d");return r.imageSmoothingEnabled=!1,r.drawImage(o,n.sx,n.sy,n.sw,n.sh,0,0,e,e),r.getImageData(0,0,e,e)}Yn(new Js);class Jn{constructor(t=0){x(this,"_lon0",0);this._lon0=t}get lon0(){return this._lon0}getTileXWithCenterLon(t,e){const n=Math.pow(2,e);let i=t+Math.round(n/360*this._lon0);return i>=n?i-=n:i<0&&(i+=n),i}getTileXYZproj(t,e,n){const i=this.mapWidth,r=this.mapHeight/2,s=t/Math.pow(2,n)*i-i/2,a=r-e/Math.pow(2,n)*r*2;return{x:s,y:a}}getProjBoundsFromLonLat(t){const e=t[0]===-180&&t[2]===180,n=this.project(t[0]+(e?this._lon0:0),t[1]),i=this.project(t[2]+(e?this._lon0:0),t[3]);return[Math.min(n.x,i.x),Math.min(n.y,i.y),Math.max(n.x,i.x),Math.max(n.y,i.y)]}getProjBoundsFromXYZ(t,e,n){const i=this.getTileXYZproj(t,e,n),r=this.getTileXYZproj(t+1,e+1,n);return[Math.min(i.x,r.x),Math.min(i.y,r.y),Math.max(i.x,r.x),Math.max(i.y,r.y)]}getLonLatBoundsFromXYZ(t,e,n){const i=this.getProjBoundsFromXYZ(t,e,n),r=this.unProject(i[0],i[1]),s=this.unProject(i[2],i[3]);return[r.lon,r.lat,s.lon,s.lat]}}const Ee=6378e3;class Qn extends Jn{constructor(){super(...arguments);x(this,"ID","3857");x(this,"mapWidth",2*Math.PI*Ee);x(this,"mapHeight",this.mapWidth);x(this,"mapDepth",1)}project(e,n){const i=(e-this.lon0)*(Math.PI/180),r=n*(Math.PI/180),s=Ee*i,a=Ee*Math.log(Math.tan(Math.PI/4+r/2));return{x:s,y:a}}unProject(e,n){let i=e/Ee*(180/Math.PI)+this.lon0;return i>180&&(i-=360),{lat:(2*Math.atan(Math.exp(n/Ee))-Math.PI/2)*(180/Math.PI),lon:i}}}class Hs extends Jn{constructor(){super(...arguments);x(this,"ID","4326");x(this,"mapWidth",36e3);x(this,"mapHeight",18e3);x(this,"mapDepth",1)}project(e,n){return{x:(e-this.lon0)*100,y:n*100}}unProject(e,n){return{lon:e/100+this.lon0,lat:n/100}}}const Hn={createFromID:(o="3857",t)=>{let e;switch(o){case"3857":e=new Qn(t);break;case"4326":e=new Hs(t);break;default:throw new Error(`Projection ID: ${o} is not supported.`)}return e}};class Es extends Fn{constructor(){super(...arguments);x(this,"_projection")}attcth(e,n){Object.assign(this,e),this._projection=n;const i=e.imgSource,r=e.demSource;i.forEach(s=>{s._projectionBounds=n.getProjBoundsFromLonLat(s.bounds)}),r&&(r._projectionBounds=n.getProjBoundsFromLonLat(r.bounds))}async load(e){if(!this._projection)throw new Error("projection is undefined");const{x:n,y:i,z:r}=e,s=this._projection.getTileXWithCenterLon(n,r),a=this._projection.getProjBoundsFromXYZ(n,i,r),l=this._projection.getLonLatBoundsFromXYZ(n,i,r);return super.load({x:s,y:i,z:r,bounds:a,lonLatBounds:l})}}function En(o,t){const e=t.intersectObjects([o.rootTile]);for(const n of e)if(n.object instanceof le){const i=o.worldToLocal(n.point.clone()),r=o.map2geo(i);return Object.assign(n,{location:r})}}function qn(o,t){const e=new h.Vector3(0,-1,0),n=new h.Vector3(t.x,10*1e3,t.z),i=new h.Raycaster(n,e);return En(o,i)}function qs(o,t,e){const n=new h.Raycaster;return n.setFromCamera(e,o),En(t,n)}function $s(o){const t=o.loader.manager,e=(n,i)=>{o.dispatchEvent({type:n,...i})};t.onStart=(n,i,r)=>{e("loading-start",{url:n,itemsLoaded:i,itemsTotal:r})},t.onError=n=>{e("loading-error",{url:n})},t.onLoad=()=>{e("loading-complete")},t.onProgress=(n,i,r)=>{e("loading-progress",{url:n,itemsLoaded:i,itemsTotal:r})},t.onParseEnd=n=>{e("parsing-end",{url:n})},o.rootTile.addEventListener("ready",()=>e("ready")),o.rootTile.addEventListener("tile-created",n=>{e("tile-created",{tile:n.tile})}),o.rootTile.addEventListener("tile-loaded",n=>{e("tile-loaded",{tile:n.tile})}),o.rootTile.addEventListener("tile-unload",n=>{e("tile-unload",{tile:n.tile})})}class Yt extends h.Mesh{constructor(e){super();x(this,"name","map");x(this,"_clock",new h.Clock);x(this,"isLOD",!0);x(this,"autoUpdate",!0);x(this,"updateInterval",100);x(this,"rootTile");x(this,"loader");x(this,"_loader",new Es);x(this,"_minLevel",2);x(this,"_maxLevel",19);x(this,"_projection",new Qn(0));x(this,"_imgSource",[]);x(this,"_demSource");x(this,"_LODThreshold",1);this.up.set(0,0,1);const{loader:n=new Fn,rootTile:i=new le,minLevel:r=2,maxLevel:s=19,imgSource:a,demSource:l,lon0:u=0}=e;this.loader=n,i.matrixAutoUpdate=!0,i.scale.set(this.projection.mapWidth,this.projection.mapHeight,this.projection.mapDepth),this.rootTile=i,this.minLevel=r,this.maxLevel=s,this.imgSource=a,this.demSource=l,this.lon0=u,this.add(i),i.updateMatrix(),$s(this)}get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}get maxLevel(){return this._maxLevel}set maxLevel(e){this._maxLevel=e}get lon0(){return this.projection.lon0}set lon0(e){this.projection.lon0!==e&&(e!=0&&this.minLevel<1&&console.warn(`Map centralMeridian is ${this.lon0}, minLevel must > 0`),this.projection=Hn.createFromID(this.projection.ID,e),this.reload())}get projection(){return this._projection}set projection(e){(e.ID!=this.projection.ID||e.lon0!=this.lon0)&&(this.rootTile.scale.set(e.mapWidth,e.mapHeight,e.mapDepth),this._projection=e,this.reload(),this.dispatchEvent({type:"projection-changed",projection:e}))}get imgSource(){return this._imgSource}set imgSource(e){const n=Array.isArray(e)?e:[e];if(n.length===0)throw new Error("imgSource can not be empty");this.projection=Hn.createFromID(n[0].projectionID,this.projection.lon0),this._imgSource=n,this.loader.imgSource=n,this.dispatchEvent({type:"source-changed",source:e})}get demSource(){return this._demSource}set demSource(e){this._demSource=e,this.loader.demSource=this._demSource,this.dispatchEvent({type:"source-changed",source:e})}get LODThreshold(){return this._LODThreshold}set LODThreshold(e){this._LODThreshold=e}static create(e){return new Yt(e)}update(e){const n=this._clock.getElapsedTime();if(n>this.updateInterval/1e3){this._loader.attcth(this.loader,this.projection);try{this.rootTile.update({camera:e,loader:this._loader,minLevel:this.minLevel,maxLevel:this.maxLevel,LODThreshold:this.LODThreshold}),this.rootTile.castShadow=this.castShadow,this.rootTile.receiveShadow=this.receiveShadow}catch(i){console.error("Error on loading tile data.",i)}this._clock.start(),this.dispatchEvent({type:"update",delta:n})}}reload(){this.rootTile.reload(this.loader)}dispose(){this.removeFromParent(),this.reload()}geo2pos(e){return this.geo2map(e)}geo2map(e){const n=this.projection.project(e.x,e.y);return new h.Vector3(n.x,n.y,e.z)}geo2world(e){return this.localToWorld(this.geo2map(e))}pos2geo(e){return this.map2geo(e)}map2geo(e){const n=this.projection.unProject(e.x,e.y);return new h.Vector3(n.lon,n.lat,e.z)}world2geo(e){return this.pos2geo(this.worldToLocal(e.clone()))}getLocalInfoFromGeo(e){const n=this.geo2world(e);return qn(this,n)}getLocalInfoFromWorld(e){return qn(this,e)}getLocalInfoFromScreen(e,n){return qs(e,this,n)}get downloading(){return le.downloadThreads}getTileCount(){let e=0,n=0,i=0,r=0,s=0;return this.rootTile.traverse(a=>{a.isTile&&(e++,a.isLeaf&&(r++,a.inFrustum&&n++),i=Math.max(i,a.z),s=le.downloadThreads)}),{total:e,visible:n,leaf:r,maxLevel:i,downloading:s}}}function Kt(o,t,e){if(o==null||o==="")throw new Error(e||`Parameter "${t}" is required but received: ${o}`);return o}function $n(o,t,e){const n=t.split(".");let i=o;for(const r of n){if(i[r]===void 0||i[r]===null)throw new Error(`Property "${t}" is required but missing at path: "${r}"`);i=i[r]}return i}class ei{constructor(){x(this,"_dispatcher",new h.EventDispatcher);x(this,"_listenerMap",new Map)}on(t,e){const n=i=>e(i.data||i);return this._listenerMap.has(t)||this._listenerMap.set(t,new Map),this._listenerMap.get(t).set(e,n),this._dispatcher.addEventListener(t,n),this}once(t,e){const n=i=>{this.off(t,n),e(i.data||i)};return this.on(t,n)}off(t,e){const n=this._listenerMap.get(t);if(!n)return this;const i=n.get(e);return i&&(this._dispatcher.removeEventListener(t,i),n.delete(e),n.size===0&&this._listenerMap.delete(t)),this}trigger(t,e){const n={type:t,data:e};return this._dispatcher.dispatchEvent(n),this}get threeEventDispatcher(){return this._dispatcher}}function eo(o,t){return o.replace(/\{(\w+)\}/g,(e,n)=>{if(t.hasOwnProperty(n)){const i=t[n];return i!==void 0?String(i):e}throw new Error(`缺少必要参数: ${n}`)})}function to(o,...t){for(let e=0;e<t.length;e++){const n=t[e];for(const i in n)o[i]=n[i]}return o}function no(o){return o==null}function io(o=new Date){const t=o.getFullYear().toString(),e=(o.getMonth()+1).toString().padStart(2,"0"),n=o.getDate().toString().padStart(2,"0"),i=o.getHours().toString().padStart(2,"0"),r=o.getMinutes().toString().padStart(2,"0"),s=o.getSeconds().toString().padStart(2,"0");return`${t}-${e}-${n} ${i}:${r}:${s}`}function Bt(o){return class extends o{constructor(){super(...arguments);x(this,"eventClass",new ei);x(this,"on",this.eventClass.on.bind(this.eventClass));x(this,"trigger",this.eventClass.trigger.bind(this.eventClass));x(this,"off",this.eventClass.off.bind(this.eventClass))}}}function Nt(o){return class extends o{constructor(...e){super(...e);x(this,"options");this.options={}}static mergeOptions(e){const n=this.prototype,i=Object.getPrototypeOf(n);return(!n.options||n.options===i.options)&&(n.options=n.options?Object.create(n.options):{}),to(n.options,e),this}}}const ro={attribution:"",visible:!0,opacity:1};class jt extends Bt(Nt(h.Group)){constructor(e,n){super();x(this,"_id");x(this,"opacity",1);x(this,"_animationCallbacks",new Set);Kt(e,"id","Layer id must be specified"),n&&(this.opacity=n.opacity||1),this._id=e,typeof this.animate=="function"&&this._registerAnimate()}getId(){return this._id}addTo(e){return e.addLayer(this),this}getZIndex(){return 0}getOpacity(){return this.opacity}setOpacity(e){this.opacity=e,this.traverse(n=>{"material"in n&&(Array.isArray(n.material)?n.material:[n.material]).forEach(r=>{"opacity"in r&&(r.transparent=e<1,r.opacity=e,r.needsUpdate=!0)}),n instanceof h.Sprite&&(n.material.opacity=e,n.material.transparent=e<1,n.material.needsUpdate=!0)})}getMap(){return this.map?this.map:null}show(){return this.visible||(this.visible=!0,this.options.visible=!0,this.getMap()),this}hide(){return this.visible&&(this.visible=!1,this.options.visible=!1,this.getMap()),this}_bindMap(e){e&&(this.map=e,typeof this.animate=="function"&&this._registerAnimate())}_registerAnimate(){const e=this.getMap();if(!e?.viewer)return;const n=e.viewer.addAnimationCallback((i,r)=>{this.animate?.(i,r)});this._animationCallbacks.add(n)}_clearAnimationCallbacks(){this._animationCallbacks.forEach(e=>e()),this._animationCallbacks.clear()}}jt.mergeOptions(ro);class so extends h.Group{constructor(){super(...arguments);x(this,"_layers",new Set);x(this,"_layerids",new Set)}add(...e){return e.forEach(n=>{if(!(n instanceof jt))throw new Error("LayerContainer can only contain Layer instances!");const i=n.getId();if(this._layerids.has(i))throw new Error(`Layer with ID '${i}' already exists in the container!`);this._layers.add(n),this._layerids.add(i),super.add(n)}),this}remove(...e){return e.forEach(n=>{this._layers.delete(n),super.remove(n)}),this}getLayers(){return Array.from(this._layers)}getLayerById(e){for(const n of this._layers)if(n.getId()===e)return n}clearLayers(){return this._layers.clear(),super.clear(),this}}class oo{constructor(){x(this,"canvasDict",{})}getCanvas(t=40,e=30,n){const i=n?`${t}_${e}_${n}`:`${t}_${e}`;if(!this.canvasDict[i])this.canvasDict[i]=document.createElement("canvas"),this.canvasDict[i].width=t,this.canvasDict[i].height=e;else{const r=this.canvasDict[i],s=r.getContext("2d");r.width=t,r.height=e,s.clearRect(0,0,t,e)}return this.canvasDict[i]}clearCache(t,e,n){const i=n?`${t}_${e}_${n}`:`${t}_${e}`;delete this.canvasDict[i]}}class ao{}let ft=class _i extends Bt(Nt(ao)){constructor(e,n){super();x(this,"viewer");x(this,"tilemap");x(this,"center");x(this,"options");x(this,"_layerContainer");x(this,"_EventMap",{loaded:{listened:!1}});x(this,"_canvasManager",new oo);x(this,"_onLoadHooks");Kt(e,"container","Map container element must be specified");const i=["center","meshmap"];for(const b of i)$n(n,b);const r={viewer:{antialias:!0,stencil:!0,logarithmicDepthBuffer:!0}};this.options={...n,viewer:{...r.viewer,...n.viewer}},this.center=this.options.center,this.viewer=new Cn(e,this.options.viewer),this.tilemap=this.initTileMap(this.options.meshmap),this.tilemap.receiveShadow=!0,this.viewer.scene.add(this.tilemap);const s=this.tilemap.geo2world(new h.Vector3(this.center[0],this.center[1],0)),a=this.tilemap.geo2world(new h.Vector3(this.center[0],this.center[1]-.01,this.center[2]||1e3));this.viewer.camera.position.copy(a),this.viewer.controls.target.copy(s),this._layerContainer=new so,this.viewer.scene.add(this._layerContainer);const l=2,u=1,d=.5,c=3e3,p=5,f=1,m=c*3.5,v=3,g=-1e-4;this.viewer.dirLight.position.set(s.x+c*l,c*u*2,s.z+c*d),this.viewer.dirLight.target.position.copy(s),this.viewer.dirLight.castShadow=!0,this.viewer.dirLight.shadow.mapSize.width=1024*p,this.viewer.dirLight.shadow.mapSize.height=1024*p,this.viewer.dirLight.shadow.camera.near=f,this.viewer.dirLight.shadow.camera.far=m,this.viewer.dirLight.shadow.camera.left=-3e3,this.viewer.dirLight.shadow.camera.bottom=-3e3,this.viewer.dirLight.shadow.camera.top=c,this.viewer.dirLight.shadow.camera.right=c,this.viewer.dirLight.shadow.radius=v,this.viewer.dirLight.shadow.bias=g,this.viewer.dirLight.name="平行光",this.viewer.dirLight.intensity=3,this._callOnLoadHooks()}static addOnLoadHook(e,...n){const i=typeof e=="function"?e:function(){this[e].apply(this,n)},r=this.prototype;return r._onLoadHooks=r._onLoadHooks||[],r._onLoadHooks.push(i),this}_callOnLoadHooks(){const e=_i.prototype;if(e._onLoadHooks)for(let n=0,i=e._onLoadHooks.length;n<i;n++)e._onLoadHooks[n].call(this)}initTileMap(e){const n=new Yt({...e});return n.rotateX(-Math.PI/2),n.receiveShadow=!0,n.addEventListener("ready",()=>{const i={timestamp:io(),targrt:this};this._EventMap.loaded={listened:!0},this.trigger("loaded",i)}),n}addLayer(e,...n){if(!e)return this;Array.isArray(e)||(e=[e]),n?.length&&(e=e.concat(n));const i=this._layerContainer;for(let r=0,s=e.length;r<s;r++){const a=e[r],l=a.getId();if(no(l))throw new Error("Invalid id for the layer: "+l);a._bindMap(this),i.add(a)}return this}clearLayers(){return this._layerContainer.clear(),this._layerContainer}getLayers(){return this._layerContainer.getLayers()}getLayerById(e){return this._layerContainer.getLayerById(e)}geo2world(e){return this.tilemap.geo2world(e)}world2geo(e){return this.tilemap.world2geo(e)}_getCanvas(e=40,n=30,i){return this._canvasManager.getCanvas(e,n,i)}};function lo(o,t,e){const{currentTarget:n,clientX:i,clientY:r}=o;if(n instanceof HTMLElement){const s=n.clientWidth,a=n.clientHeight,l=new h.Vector2(i/s*2-1,-(r/a)*2+1);return t.getLocalInfoFromScreen(e,l)?.location}else return}const co=["click","dblclick","mousedown","mouseup","mousemove","mouseenter","mouseleave","mouseover","mouseout"];ft.prototype._removeDomEvents=function(){console.log("removeDomEvents",this)},ft.prototype._registerDomEvents=function(){const o=this.viewer.container;o&&co.forEach(t=>{o.addEventListener(t,e=>{let n=lo(e,this.tilemap,this.viewer.camera),i={targrt:this,originEvent:e,eventName:t,screenXY:{X:e.screenX,Y:e.screenY}};if(n){let r=[n.x,n.y,n.z];i={targrt:this,originEvent:e,coordiante:r,eventName:t,screenXY:{X:e.screenX,Y:e.screenY}}}this.trigger(t,i)})})},ft.addOnLoadHook("_registerDomEvents");class uo extends We{constructor(e){super(e);x(this,"dataType","image");x(this,"attribution","天地图");x(this,"token","");x(this,"style","img_w");x(this,"subdomains","01234");x(this,"url","https://t{s}.tianditu.gov.cn/DataServer?T={style}&x={x}&y={y}&l={z}&tk={token}");Object.assign(this,e)}}class ho extends We{constructor(e){super(e);x(this,"dataType","quantized-mesh");x(this,"attribution","天地图");x(this,"token","");x(this,"subdomains","01234");x(this,"url","https://t{s}.tianditu.gov.cn/mapservice/swdx?T=elv_c&tk={token}&x={x}&y={y}&l={z}");Object.assign(this,e)}}class po extends We{constructor(e){super({...e,url:e.urlTemplate,isTMS:e.isTMS||!1});x(this,"minLevel",2);x(this,"maxLevel",24)}getUrl(e,n,i){const r=this.isTMS?Math.pow(2,i)-1-n:n;return eo(this.url,{...this,x:e,y:r,z:i,tileMatrix:i,tileRow:r,tileCol:e})}}class fo extends We{constructor(e){super(e);x(this,"dataType","image");x(this,"attribution","ArcGIS");x(this,"style","World_Imagery");x(this,"url","https://services.arcgisonline.com/arcgis/rest/services/{style}/MapServer/tile/{z}/{y}/{x}");Object.assign(this,e)}}class mo extends We{constructor(e){super(e);x(this,"dataType","lerc");x(this,"attribution","ArcGIS");x(this,"minLevel",6);x(this,"maxLevel",13);x(this,"url","https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer/tile/{z}/{y}/{x}");Object.assign(this,e)}}class yo extends We{constructor(e){super(e);x(this,"token","");x(this,"format","webp");x(this,"style","cm2myr6qx001t01pi0sf7estf");x(this,"attribution","MapBox");x(this,"maxLevel",25);x(this,"url","https://api.mapbox.com/styles/v1/criska/cm2myr6qx001t01pi0sf7estf/tiles/256/{z}/{x}/{y}?access_token={token}&format={format}");Object.assign(this,e)}}const vt=class vt{constructor(t){x(this,"_cache",new Map);x(this,"_gltfLoader");x(this,"_fbxLoader");x(this,"_dracoLoader");this._gltfLoader=new qi(t),this._fbxLoader=new Xr(t)}static init(t){return this._instance||(this._instance=new vt(t)),this._instance}async load(t){const e=`${t.type}:${t.url}`;if(this._cache.has(e))return this._cloneCachedModel(e,t);t.type==="gltf"&&t.dracoOptions?.enable&&this._initDracoLoader(t.dracoOptions.decoderPath);let n,i;try{if(t.type==="gltf"){const r=await this._gltfLoader.loadAsync(t.url);n=r.scene,i=r.animations}else n=await this._fbxLoader.loadAsync(t.url),i=n.animations;return this._cache.set(e,{model:n,animations:i}),{model:this._processModel(n.clone(),t),animations:i?.map(r=>({...r,name:r.name||"unnamed"}))||[]}}catch(r){throw console.error(`Failed to load ${t.type} model:`,t.url,r),r}}_initDracoLoader(t="/draco/"){this._dracoLoader||(this._dracoLoader=new $r,this._dracoLoader.setDecoderPath(t),this._gltfLoader.setDRACOLoader(this._dracoLoader))}_cloneCachedModel(t,e){const i=this._cache.get(t).model.clone();return this._processModel(i,e)}_processModel(t,e){return e.position&&t.position.copy(e.position),e.scale&&(typeof e.scale=="number"?t.scale.setScalar(e.scale):e.scale.x!==void 0||e.scale.y!==void 0||e.scale.z!==void 0?(e.scale.x!==void 0&&(t.scale.x=e.scale.x),e.scale.y!==void 0&&(t.scale.y=e.scale.y),e.scale.z!==void 0&&(t.scale.z=e.scale.z)):t.scale.copy(e.scale)),e.rotation&&t.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e.materialOverrides&&t.traverse(n=>{if(n instanceof h.Mesh&&n.material){const i=e.materialOverrides[n.name];i&&(n.material=i)}}),t.traverse(n=>{n instanceof h.Mesh&&n.material}),t}};x(vt,"_instance");let Rt=vt;const Jt=(o,t)=>{"updateRanges"in o?o.updateRanges[0]=t:o.updateRange=t},ti=new h.Matrix4,mt=new h.Vector3,yt=new h.Quaternion,ni=new h.Vector3,ii=new h.Quaternion,qe=new h.Vector3,go=o=>class extends o{constructor(){super();const t=parseInt(h.REVISION.replace(/\D+/g,""))>=154?"opaque_fragment":"output_fragment";this.onBeforeCompile=e=>{e.vertexShader=`attribute float cloudOpacity;
566
+ varying float vOpacity;
567
+ `+e.vertexShader.replace("#include <fog_vertex>",`#include <fog_vertex>
568
+ vOpacity = cloudOpacity;
569
+ `),e.fragmentShader=`varying float vOpacity;
570
+ `+e.fragmentShader.replace(`#include <${t}>`,`#include <${t}>
571
+ gl_FragColor = vec4(outgoingLight, diffuseColor.a * vOpacity);
572
+ `)}}};class bo extends h.Group{constructor({limit:t=200,range:e,material:n=h.MeshLambertMaterial,texture:i,frustumCulled:r=!0}={}){super(),this.name="Clouds",this.ref=this;const s=this,a=new h.PlaneGeometry(1,1),l=new Float32Array(Array.from({length:t},()=>1)),u=new Float32Array(Array.from({length:t},()=>[1,1,1]).flat()),d=new h.InstancedBufferAttribute(l,1);d.setUsage(h.DynamicDrawUsage),a.setAttribute("cloudOpacity",d);const c=go(n),p=new c;p.map=i,p.transparent=!0,p.depthWrite=!1,p.needsUpdate=!0,this.cloudMaterial=p,this.instance=new h.InstancedMesh(a,p,t);const f=this.instance;f.matrixAutoUpdate=!1,f.frustumCulled=r,f.instanceColor=new h.InstancedBufferAttribute(u,3),f.instanceColor.setUsage(h.DynamicDrawUsage),s.add(f);const m=[],v=()=>{const T=m.length;let M=0;for(let A=0;A<this.ref.children.length;A++){const L=this.ref.children[A];L.cloudStateArray&&(M+=L.cloudStateArray.length)}if(T===M)return m;m.length=0;for(let A=0;A<this.ref.children.length;A++){const L=this.ref.children[A];L.cloudStateArray&&m.push(...L.cloudStateArray)}return g(),m},g=()=>{const T=Math.min(t,e!==void 0?e:t,m.length);f.count=T,Jt(f.instanceMatrix,{offset:0,count:T*16}),f.instanceColor&&Jt(f.instanceColor,{offset:0,count:T*3}),Jt(f.geometry.attributes.cloudOpacity,{offset:0,count:T})};let b=0,y=0,w;const S=new h.Quaternion,P=new h.Vector3(0,0,1),I=new h.Vector3;this.update=(T,M,A)=>{b=M,ti.copy(f.matrixWorld).invert(),T.matrixWorld.decompose(ni,ii,qe);const L=v();for(y=0;y<L.length;y++)w=L[y],w.ref.matrixWorld.decompose(mt,yt,qe),mt.add(I.copy(w.position).applyQuaternion(yt).multiply(qe)),yt.copy(ii).multiply(S.setFromAxisAngle(P,w.rotation+=A*w.rotationFactor)),qe.multiplyScalar(w.volume+(1+Math.sin(b*w.density*w.speed))/2*w.growth),w.matrix.compose(mt,yt,qe).premultiply(ti),w.dist=mt.distanceTo(ni);for(L.sort((Z,W)=>W.dist-Z.dist),y=0;y<L.length;y++)w=L[y],l[y]=w.opacity*(w.dist<w.fade-1?w.dist/w.fade:1),f.setMatrixAt(y,w.matrix),f.setColorAt(y,w.color);f.geometry.attributes.cloudOpacity.needsUpdate=!0,f.instanceMatrix.needsUpdate=!0,f.instanceColor&&(f.instanceColor.needsUpdate=!0)}}}let vo=0;class wo extends h.Group{constructor({opacity:t=1,speed:e=0,bounds:n=new h.Vector3().fromArray([5,1,1]),segments:i=20,color:r=new h.Color("#ffffff"),fade:s=10,volume:a=6,smallestVolume:l=.25,distribute:u=null,growth:d=4,concentrate:c="inside",seed:p=Math.random()}={}){super(),this.name="cloud_"+vo++,this.seed=p,this.segments=i,this.bounds=n,this.concentrate=c,this.volume=a,this.smallestVolume=l,this.distribute=u,this.growth=d,this.speed=e,this.fade=s,this.opacity=t,this.color=r,this.ref=this,this.cloudStateArray=[],this.updateCloud()}updateCloudStateArray(){if(this.cloudStateArray.length===this.segments)return;const{segments:t,uuid:e}=this;if(this.cloudStateArray.length>this.segments)this.cloudStateArray.splice(0,this.cloudStateArray.length-this.segments);else for(let n=this.cloudStateArray.length;n<t;n++)this.cloudStateArray.push({segments:t,bounds:new h.Vector3(1,1,1),position:new h.Vector3,uuid:e,index:n,ref:this,dist:0,matrix:new h.Matrix4,volume:0,length:0,speed:0,growth:0,opacity:1,fade:0,density:0,rotation:n*(Math.PI/t),rotationFactor:0,color:new h.Color})}updateCloud(){const{volume:t,color:e,speed:n,growth:i,opacity:r,fade:s,bounds:a,seed:l,cloudStateArray:u,distribute:d,segments:c,concentrate:p,smallestVolume:f}=this;this.updateCloudStateArray();let m=0;function v(){const g=Math.sin(l+m)*1e4;return m++,g-Math.floor(g)}u.forEach((g,b)=>{g.segments=c,g.volume=t,g.color=e,g.speed=n,g.growth=i,g.opacity=r,g.fade=s,g.bounds.copy(a),g.density=Math.max(.5,v()),g.rotationFactor=Math.max(.2,.5*v())*n;const y=d?.(g,b);if(y||c>1){var w;g.position.copy(g.bounds).multiply((w=y?.point)!==null&&w!==void 0?w:{x:v()*2-1,y:v()*2-1,z:v()*2-1})}const S=Math.abs(g.position.x),P=Math.abs(g.position.y),I=Math.abs(g.position.z),T=Math.max(S,P,I);g.length=1,S===T&&(g.length-=S/g.bounds.x),P===T&&(g.length-=P/g.bounds.y),I===T&&(g.length-=I/g.bounds.z),g.volume=(y?.volume!==void 0?y.volume:Math.max(Math.max(0,f),p==="random"?v():p==="inside"?g.length:1-g.length))*t})}}function ri(o,t){const e=new h.BufferGeometry;e.setAttribute("position",new h.BufferAttribute(new Float32Array([0,0,0]),3));const n=new h.Points(e,new h.PointsMaterial({size:o.size,color:o.color||16777215,sizeAttenuation:!o.glow}));return n.position.copy(t),n}async function si(o,t){const e=await Ge._loadTexture(o.url),n=new h.Sprite(new h.SpriteMaterial({map:e,color:o.color||16777215,transparent:!0,opacity:o.opacity??1,sizeAttenuation:o.sizeAttenuation??!0}));return n.scale.set(o.size[0],o.size[1],1),o.rotation&&(n.rotation.z=o.rotation),o.anchor&&n.center.set(o.anchor[0],o.anchor[1]),n.position.copy(t),n}function Qt(o,t){let e;t instanceof Float32Array?e=Array.from(t):Array.isArray(t)&&typeof t[0]=="number"?e=t:e=t.flatMap(r=>[r.x,r.y,r.z]);const n=new ut;n.setPositions(e);const i=new Je({color:new h.Color(o.color??16777215).getHex(),linewidth:o.width??2,transparent:o.opacity!==void 0&&o.opacity<1,opacity:o.opacity??1,dashed:!!o.dashArray,dashScale:o.dashArray?.[0]??1,dashSize:o.dashArray?.[0]??1,gapSize:o.dashArray?.[1]??0,resolution:new h.Vector2(window.innerWidth,window.innerHeight),alphaToCoverage:!0});return window.addEventListener("resize",()=>{i.resolution.set(window.innerWidth,window.innerHeight)}),new Ot(n,i)}async function xo(o,t){const e=o.type||(o.url.toLowerCase().endsWith(".fbx")?"fbx":"gltf");return await Rt.init().load({...o,type:e,position:t})}function Lo(o,t){const e=new h.BufferGeometry;e.setAttribute("position",new h.BufferAttribute(new Float32Array(t),3));const n=[],i=t.length/3;for(let s=1;s<i-1;s++)n.push(0,s,s+1);e.setIndex(n),e.computeVertexNormals();const r=new h.MeshBasicMaterial({color:new h.Color(o.color??16777215),transparent:o.opacity!==void 0&&o.opacity<1,opacity:o.opacity??1,wireframe:o.wireframe??!1,side:o.side==="back"?h.BackSide:o.side==="double"?h.DoubleSide:h.FrontSide,depthWrite:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1});return new h.Mesh(e,r)}function So(o,t){const e=o.extrude?.height||2e3,n=[],i=[],r=[];for(let c=0;c<t.length;c+=3){const p=t[c],f=t[c+1],m=t[c+2];i.push(new h.Vector3(p,f,m)),r.push(new h.Vector3(p,f+e,m))}n.push(...i,...r);const s=new h.BufferGeometry;s.setFromPoints(n);const a=[],l=i.length;for(let c=0;c<l;c++){const p=(c+1)%l;a.push(c,c+l,p),a.push(p,c+l,p+l)}for(let c=2;c<l;c++)a.push(0,c-1,c),a.push(l,l+c-1,l+c);s.setIndex(a),s.computeVertexNormals(),s.attributes.normal||s.computeVertexNormals();const u=new h.ShaderMaterial({uniforms:{uColor:{value:new h.Color(o.color??16777215)},uOpacity:{value:o.opacity??1},uBrightness:{value:1.2}},vertexShader:`
573
+ varying vec3 vWorldPosition;
574
+ varying vec3 vNormal;
575
+ void main() {
576
+ vNormal = normalize(normalMatrix * normal); // 法线转换到世界坐标
577
+ vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;
578
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
579
+ }
580
+ `,fragmentShader:`
581
+ uniform vec3 uColor;
582
+ uniform float uOpacity;
583
+ uniform float uBrightness;
584
+ varying vec3 vWorldPosition;
585
+ varying vec3 vNormal;
586
+
587
+ void main() {
588
+ // 1. 计算菲涅尔效应(边缘高光)
589
+ float fresnel = pow(1.0 - abs(dot(vNormal, vec3(0.0, 0.0, 1.0))), 2.0);
590
+
591
+ // 2. 内部折角增亮(根据位置模拟凹陷效果)
592
+ float innerGlow = smoothstep(0.3, 0.8, length(vWorldPosition - vec3(0.0))) * uBrightness;
593
+
594
+ // 3. 混合颜色
595
+ vec3 finalColor = uColor * (1.0 + fresnel * 0.5 + innerGlow);
596
+
597
+ // 4. 强制透明度排序(深度测试后混合)
598
+ gl_FragColor = vec4(finalColor, uOpacity);
599
+
600
+ // 5. 深度写入控制(保持与不透明物体正确交互)
601
+ if (uOpacity >= 0.99) gl_FragDepthEXT = gl_FragCoord.z;
602
+ }
603
+ `,transparent:!0,side:h.DoubleSide,depthWrite:!0}),d=new h.Mesh(s,u);return d.renderOrder=5e3,d}function Mo(o,t,e){const{geometry:n,center:i,avgY:r}=oi(e),s=new Ui(n,{textureWidth:512,textureHeight:512,waterNormals:new h.TextureLoader().load(o.normalMap,function(u){u.wrapS=u.wrapT=h.RepeatWrapping}),waterColor:o.color||"#19AAEE",sunColor:o.sunColor||"#05FFF8",distortionScale:1,alpha:o.opacity||.8}),a=s.onBeforeRender,l=s.onAfterRender;return s.onBeforeRender=(u,d,c,p,f,m)=>{t.tilemap.autoUpdate=!1,a.call(s,u,d,c,p,f,m)},s.onAfterRender=(u,d,c,p,f,m)=>{t.tilemap.autoUpdate=!0,l.call(s,u,d,c,p,f,m)},s.material.uniforms.size.value=.1,s.rotation.x=-Math.PI/2,s.position.set(i.x,r,i.z),t.viewer.addEventListener("update",()=>{s.material.uniforms.time.value+=1/60}),s}function oi(o){let t=0;for(let s=1;s<o.length;s+=3)t+=o[s];t/=o.length/3;const e={x:0,z:0},n=[];for(let s=0;s<o.length;s+=3)e.x+=o[s],e.z+=o[s+2];e.x/=o.length/3,e.z/=o.length/3;for(let s=0;s<o.length;s+=3)n.push(new h.Vector2(o[s]-e.x,-(o[s+2]-e.z)));const i=new h.Shape(n);return{geometry:new h.ShapeGeometry(i),center:e,avgY:t}}async function _o(o,t){const{geometry:e,center:n,avgY:i}=oi(t),r=await Ge._loadTexture(o.normalMap);r.wrapS=r.wrapT=h.RepeatWrapping,r.repeat.set(.01,.01),r.needsUpdate=!0;const s=new h.MeshStandardMaterial({color:new h.Color(o.color).multiplyScalar(2),roughness:0,metalness:.6,transparent:!0,opacity:.9,fog:!1,bumpMap:r,bumpScale:.6}),a=new h.Mesh(e,s);a.rotation.x=-Math.PI/2,a.position.set(n.x,i,n.z),a.castShadow=!1,a.receiveShadow=!0;let l=0;const u=2.5;return a.onBeforeRender=()=>{const d=performance.now(),c=l?(d-l)/1e3:.016;r.offset.x+=c*u*.1,r.offset.y+=c*u*.05,l=d},a}function Zo(o,t){o.color=new h.Color(o.hexcolor),o.boundstext&&(o.bounds=new h.Vector3(o.boundstext.x,o.boundstext.y,o.boundstext.z));const e=new wo(o);return e.castShadow=!0,e.scale.setScalar(50),e.position.copy(t),e}async function Io(o,t){const n={...{fontSize:48,fontFamily:"'Microsoft YaHei', sans-serif",fontWeight:"bold",fontStyle:"normal",textColor:"#ffffff",strokeColor:"#000000",strokeWidth:2,showBackground:!0,bgStyle:1,bgColor:"#3498db",bgOpacity:.8,shadowColor:"rgba(0, 0, 0, 0.5)",shadowBlur:5,shadowOffsetX:3,shadowOffsetY:3,roundRectRadius:20,bubblePointerHeight:10,bubblePointerWidth:15,bubbleBorderColor:"#ffffff",bubbleBorderWidth:3,fixedSize:50},...o};n.fontSize=Math.min(Math.max(n.fontSize,8),128);const i=document.createElement("canvas"),r=i.getContext("2d");if(!r)throw new Error("canvas context is null");const s=`${n.fontStyle} ${n.fontWeight} ${n.fontSize}px ${n.fontFamily}`;r.font=s;const a=n.showBackground?20:0,l=100,u=50,d=r.measureText(n.text),c=Math.max(l,d.width+a*2),p=Math.max(u,n.fontSize*1.5+a*2);i.width=Math.min(c,2048),i.height=Math.min(p,2048),r.clearRect(0,0,i.width,i.height),r.font=s,n.showBackground&&(n.bgStyle===1?(r.fillStyle=n.bgColor,r.globalAlpha=n.bgOpacity,r.beginPath(),ai(r,a/2,a/2,i.width-a,i.height-a,n.roundRectRadius),r.fill(),r.globalAlpha=1,r.shadowColor=n.shadowColor,r.shadowBlur=n.shadowBlur,r.shadowOffsetX=n.shadowOffsetX,r.shadowOffsetY=n.shadowOffsetY):(r.fillStyle=n.bgColor,r.globalAlpha=n.bgOpacity,r.beginPath(),li(r,i.width/2,i.height/2,i.width*.8,i.height*.8,n.roundRectRadius,n.bubblePointerHeight,n.bubblePointerWidth),r.fill(),r.globalAlpha=1,r.strokeStyle=n.bubbleBorderColor,r.lineWidth=n.bubbleBorderWidth,r.stroke())),r.textAlign="center",r.textBaseline="middle",n.strokeWidth>0&&(r.strokeStyle=n.strokeColor,r.lineWidth=n.strokeWidth,r.lineJoin="round",r.strokeText(n.text,i.width/2,i.height/2)),r.fillStyle=n.textColor,r.fillText(n.text,i.width/2,i.height/2),r.shadowColor="transparent";const f=new h.CanvasTexture(i);f.magFilter=h.NearestFilter,f.minFilter=h.LinearMipmapLinearFilter,f.anisotropy=16;const m=new h.SpriteMaterial({map:f,transparent:!0,depthTest:!1,depthWrite:!1,fog:!1}),v=new h.Sprite(m),g=n.fixedSize;return v.scale.set(i.width*g/100,i.height*g/100,1),t&&v.position.copy(t),v.renderOrder=9999,v}async function To(o,t,e){const i={...{fontSize:48,fontFamily:"'Microsoft YaHei', sans-serif",fontWeight:"bold",fontStyle:"normal",textColor:"#ffffff",strokeColor:"#000000",strokeWidth:2,showBackground:!0,bgStyle:1,bgColor:"#3498db",bgOpacity:.8,shadowColor:"rgba(0, 0, 0, 0.5)",shadowBlur:5,shadowOffsetX:3,shadowOffsetY:3,roundRectRadius:20,bubblePointerHeight:10,bubblePointerWidth:15,bubbleBorderColor:"#ffffff",bubbleBorderWidth:3,screenSpaceSize:20,maxVisibleDistance:1/0},...o};i.fontSize=Math.min(Math.max(i.fontSize,8),128);const r=document.createElement("canvas"),s=r.getContext("2d");if(!s)throw new Error("Failed to get canvas context");const a=`${i.fontStyle} ${i.fontWeight} ${i.fontSize}px ${i.fontFamily}`;s.font=a;const l=i.showBackground?20:0,u=100,d=50,c=s.measureText(i.text),p=Math.max(u,c.width+l*2),f=Math.max(d,i.fontSize*1.5+l*2);r.width=Math.min(p,2048),r.height=Math.min(f,2048),s.clearRect(0,0,r.width,r.height),s.font=a,i.showBackground&&(i.bgStyle===1?(s.fillStyle=i.bgColor,s.globalAlpha=i.bgOpacity,s.beginPath(),ai(s,l/2,l/2,r.width-l,r.height-l,i.roundRectRadius),s.fill(),s.globalAlpha=1,s.shadowColor=i.shadowColor,s.shadowBlur=i.shadowBlur,s.shadowOffsetX=i.shadowOffsetX,s.shadowOffsetY=i.shadowOffsetY):(s.fillStyle=i.bgColor,s.globalAlpha=i.bgOpacity,s.beginPath(),li(s,r.width/2,r.height/2,r.width*.8,r.height*.8,i.roundRectRadius,i.bubblePointerHeight,i.bubblePointerWidth),s.fill(),s.globalAlpha=1,s.strokeStyle=i.bubbleBorderColor,s.lineWidth=i.bubbleBorderWidth,s.stroke())),s.textAlign="center",s.textBaseline="middle",i.strokeWidth>0&&(s.strokeStyle=i.strokeColor,s.lineWidth=i.strokeWidth,s.lineJoin="round",s.strokeText(i.text,r.width/2,r.height/2)),s.fillStyle=i.textColor,s.fillText(i.text,r.width/2,r.height/2),s.shadowColor="transparent";const m=new h.CanvasTexture(r),v=new h.SpriteMaterial({map:m,transparent:!0,depthTest:!1,depthWrite:!1,fog:!1}),g=new h.Sprite(v);g.position.copy(t),g.renderOrder=9999,g.userData.isLabel=!0;const b=()=>{if(!g.visible)return;const w=e.viewer.camera.position.distanceTo(g.position);if(w>i.maxVisibleDistance){g.visible=!1;return}g.visible=!0;const S=new h.Vector2;e.viewer.renderer.getSize(S);const P=S.height,I=i.screenSpaceSize/r.height*(w/Math.tan(h.MathUtils.degToRad(e.viewer.camera.fov)/2))*(2/P);g.scale.set(I*r.width,I*r.height,1),g.lookAt(e.viewer.camera.position)};b();const y=()=>b();return g.addEventListener("dispose",()=>{e.viewer.renderer.domElement.removeEventListener("resize",b)}),e.viewer.renderer.domElement.addEventListener("resize",b),e.viewer.camera.addEventListener("change",b),g.onBeforeRender=y,g}function ai(o,t,e,n,i,r){o.beginPath(),o.moveTo(t+r,e),o.lineTo(t+n-r,e),o.quadraticCurveTo(t+n,e,t+n,e+r),o.lineTo(t+n,e+i-r),o.quadraticCurveTo(t+n,e+i,t+n-r,e+i),o.lineTo(t+r,e+i),o.quadraticCurveTo(t,e+i,t,e+i-r),o.lineTo(t,e+r),o.quadraticCurveTo(t,e,t+r,e),o.closePath()}function li(o,t,e,n,i,r,s,a){if(n<=0)throw new Error("Width must be positive");if(i<=0)throw new Error("Height must be positive");if(r<0)throw new Error("Radius cannot be negative");const l=n,u=i,d=Math.min(r,n/2,i/2),c=s??10,p=a??15;o.beginPath(),o.moveTo(t-l/2+d,e-u/2),o.lineTo(t+l/2-d,e-u/2),o.quadraticCurveTo(t+l/2,e-u/2,t+l/2,e-u/2+d),o.lineTo(t+l/2,e+u/2-d),o.quadraticCurveTo(t+l/2,e+u/2,t+l/2-d,e+u/2),o.lineTo(t+p/2,e+u/2),o.lineTo(t,e+u/2+c),o.lineTo(t-p/2,e+u/2),o.lineTo(t-l/2+d,e+u/2),o.quadraticCurveTo(t-l/2,e+u/2,t-l/2,e+u/2-d),o.lineTo(t-l/2,e-u/2+d),o.quadraticCurveTo(t-l/2,e-u/2,t-l/2+d,e-u/2),o.closePath()}async function Po(o,t,e){const{text:n,iconUrl:i,fontSize:r=30,iconSize:s=60,fontFamily:a="Arial",padding:l={},bgColor:u="rgba(0,0,0,0.0)",textColor:d="rgb(255,255,255)",strokeColor:c="rgb(0,0,0)",strokeWidth:p=r/9,iconScale:f=.8,canvasScale:m=1,renderbg:v=!0}=o,g={top:0,right:1,bottom:0,left:0,...l};let b=null;i&&(b=await Wo(i));const{canvas:y,width:w,height:S,center:P}=await Ao({text:n,iconImage:b,fontSize:r,iconSize:s,fontFamily:a,padding:g,bgColor:u,textColor:d,strokeColor:c,strokeWidth:p,iconScale:f,canvasScale:m,renderbg:v},t),I=new h.Texture(y);I.needsUpdate=!0;const T=new h.SpriteMaterial({map:I,transparent:!0,depthTest:!0,depthWrite:!0,blending:h.NormalBlending}),M=new h.Sprite(T);return M.scale.set(w,S,1),M.center.set(P[0],P[1]),e&&M.position.copy(e),M.renderOrder=999,M}async function Ao(o,t){return new Promise(e=>{const{text:n,iconImage:i,fontSize:r,iconSize:s,fontFamily:a,padding:l,bgColor:u,textColor:d,strokeColor:c,strokeWidth:p,iconScale:f,canvasScale:m,renderbg:v}=o,g=n.length*r,b=l.left+s+g+l.right,y=Math.max(s,r)+l.top+l.bottom,w=t._getCanvas(b,y,n);w.width=b,w.height=y;const S=w.getContext("2d");if(!S)throw new Error("Could not get canvas context");if(v&&(S.fillStyle=u,S.fillRect(0,0,b,y)),i){const T=l.left+s*(1-f)*.5,M=l.top+s*(1-f)*.5,A=s*f,L=s*f;S.drawImage(i,T,M,A,L)}S.font=`500 ${r}px ${a}`,S.textBaseline="middle",S.imageSmoothingEnabled=!1;const P=l.left+(i?s+2:0),I=y/2;p>0&&(S.lineWidth=p,S.strokeStyle=c,S.strokeText(n,P,I)),S.fillStyle=d,S.fillText(n,P,I),e({canvas:w,width:b/m,height:y/m,center:[s*.5/b,(1-f)*.5]})})}function Wo(o){return new Promise((t,e)=>{const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=i=>e(new Error(`Failed to load image: ${o} ${i}`)),n.src=o})}const he=class he{constructor(t){this.config=t}async applyTo(t){if(!t)return!1;try{switch(t.visible=this.config.visible!==!1,this.config.zIndex&&(t.renderOrder=this.config.zIndex),this.config.type){case"basic-point":case"icon-point":case"icon-label-point":return this._applyPointStyle(t);case"basic-line":return this._applyLineStyle(t);case"gltf":case"fbx":return this._applyModelStyle(t);case"basic-polygon":return this._applyPolygonStyle(t);case"extrude-polygon":return this._applyExtrudeStyle(t);case"water":case"base-water":return this._applyWaterStyle(t);case"cloud":return this._applyCloudStyle(t);case"canvas-label":case"canvas-label-fixed":return this._applyTextSpriteStyle(t);case"custom":return this._applyCustomStyle(t);default:throw new Error("Unknown style type")}}catch(e){return console.error("Style apply failed:",e),t.visible=!1,!1}}async _applyPointStyle(t){const e=this.config;return e.type==="icon-point"?await this._applyIconPoint(t,e):e.type==="basic-point"?this._applyBasicPoint(t,e):e.type==="icon-label-point"&&this._applyIconLabelPoint(t,e),!0}async _applyIconPoint(t,e){let n;if(t instanceof h.Sprite)n=t;else if(n=await si(e,t.position),n.position.copy(t.position),n.rotation.copy(t.rotation),n.scale.copy(t.scale),n.renderOrder=999,t.parent){let a=t.parent;a._threeGeometry=n,a._updateGeometry()}const[i,r]=e.size;if(i<=0||r<=0){console.error("Invalid sprite size:",e.size),n.visible=!1;return}const s=n.material;try{if(s.map=await he._loadTexture(e.url),!s.map)throw new Error("Texture failed to load");s.needsUpdate=!0,n.scale.set(i,r,1),e.rotation!==void 0&&(n.rotation.z=e.rotation)}catch(a){console.error("Failed to load texture:",e.url,a),n.visible=!1}}_applyBasicPoint(t,e){let n;if(t instanceof h.Points)n=t;else if(n=ri(e,t.position),n.position.copy(t.position),n.rotation.copy(t.rotation),n.scale.copy(t.scale),n.renderOrder=999,t.parent){let r=t.parent;r._threeGeometry=n,r._updateGeometry()}const i=n.material;i.size=e.size,e.color&&i.color.set(e.color),e.glow&&(i.sizeAttenuation=!1)}_applyIconLabelPoint(t,e){return!0}_applyLineStyle(t){const e=this.config;if(t.parent){let n=t.parent;n._threeGeometry=Qt(e,n._vertexPoints),n._updateGeometry()}return!0}_applyPolygonStyle(t){return this.config,!0}_applyExtrudeStyle(t){return this.config,!0}_applyWaterStyle(t){return this.config.type,!0}_applyCloudStyle(t){return this.config,!0}_applyTextSpriteStyle(t){return this.config,!0}async _applyModelStyle(t){return this.config,!0}async _applyCustomStyle(t){const n=await this.config.build();return t instanceof h.Group&&(t.clear(),t.add(n)),!0}static async _loadTexture(t){if(he._textureCache.has(t))return he._textureCache.get(t);const e=await new Promise((n,i)=>{he._textureLoader.load(t,n,void 0,i)});return e.premultiplyAlpha=!0,he._textureCache.set(t,e),e.premultiplyAlpha=!0,e}static create(t){return t instanceof he?t:new he(t)}};x(he,"_textureCache",new Map),x(he,"_textureLoader",new h.TextureLoader);let Ge=he;class $e extends Bt(Nt(h.Object3D)){constructor(e){super();x(this,"_position");x(this,"_threeGeometry");x(this,"_geometry");x(this,"_layer");x(this,"_style");x(this,"_styleQueue",[]);x(this,"_isApplyingStyle",!1);x(this,"_isGeometryInitializing",!1);Kt(e.geometry,"geometry","geometry must be specified"),this._geometry=e.geometry,this._position=new h.Vector3(0,0,0),this._threeGeometry=new h.Object3D,e.userData&&(this.userData=Object.assign({},JSON.parse(JSON.stringify(e.userData)))),e.style&&this.setStyle(e.style)}async initializeGeometry(){if(!(this._isGeometryInitializing||this._threeGeometry)){this._isGeometryInitializing=!0;try{await this._toThreeJSGeometry(),this._processStyleQueue()}finally{this._isGeometryInitializing=!1}}}setStyle(e){const n=e instanceof Ge?e:new Ge(e);this._style=n;const i=JSON.parse(JSON.stringify(n.config));return this._styleQueue.push(i),this._tryProcessQueue(),this}getStyle(){return this._style}async _applyStyleWithRetry(e,n=3,i=100){let r=null;for(let s=1;s<=n;s++)try{this._threeGeometry.parent||(this.add(this._threeGeometry),await new Promise(a=>requestAnimationFrame(a))),await e.applyTo(this._threeGeometry);return}catch(a){if(r=a,s<n){const l=i*Math.pow(2,s-1);console.warn(`[Feature] 重试中... (${s}/${n})`,{delay:l,error:a}),await new Promise(u=>setTimeout(u,l))}}throw r||new Error("样式应用失败,重试次数耗尽")}async _processStyleQueue(){if(!this._threeGeometry||this._isApplyingStyle||this._styleQueue.length===0){console.warn("[Feature] 取消处理:不满足运行时条件");return}this._isApplyingStyle=!0;const e=this._styleQueue[0];try{if(!e)throw new Error(`无效样式配置: ${JSON.stringify(e)}`);const n=new Ge(JSON.parse(JSON.stringify(e)));await this._applyStyleWithRetry(n),this._styleQueue.shift(),this._styleQueue.length>0&&await this._processStyleQueue()}catch(n){throw console.error("[Feature] 样式应用失败:",{error:n,remainingQueue:this._styleQueue.length}),n}finally{this._isApplyingStyle=!1,this._styleQueue.length>0&&this._tryProcessQueue()}}_tryProcessQueue(){this._threeGeometry&&!this._isApplyingStyle&&this._styleQueue.length>0?this._processStyleQueue().then(()=>{}).catch(n=>{console.error("[Feature] 队列处理失败:",n),this._isApplyingStyle=!1,this._tryProcessQueue()}):!this._threeGeometry&&!this._isGeometryInitializing&&(console.debug("[Feature] 触发延迟初始化"),this.initializeGeometry())}addTo(e){return e.addFeature(this),this}getLayer(){return this._layer||null}getMap(){return this._layer?.getMap()||null}_bindLayer(e){if(this._layer&&this._layer!==e)throw new Error("Feature cannot be added to multiple layers");this._layer=e}_updateGeometry(){this._disposeGeometry(),this._threeGeometry&&(this._threeGeometry.position.copy(this._position),this._threeGeometry.renderOrder=999,this.add(this._threeGeometry),this.updateMatrixWorld(!0),this._tryProcessQueue())}_remove(){return this.getLayer()?(this._unbind(),this):this}_unbind(){const e=this.getLayer();e&&(e.onRemoveFeature&&e.onRemoveFeature(this),delete this._layer)}_disposeGeometry(){this._threeGeometry&&(this.clear(),"traverse"in this&&this._threeGeometry.traverse(e=>{e instanceof h.Mesh?(e.geometry?.dispose(),Array.isArray(e.material)?e.material.forEach(n=>n.dispose()):e.material?.dispose()):"isLine"in e&&e.isLine&&(e.geometry?.dispose(),e.material?.dispose())}))}}class gt extends jt{constructor(e,n){super(e,n);x(this,"_feaList");this._feaList=[]}addFeature(e){const n=Array.isArray(e)?e:[e];for(const i of n)if(!(!i||!(i instanceof $e))&&!i.getLayer()){if(!this.validateFeature(i)){console.error(`Feature ${i.id} does not match the layer's type requirements`);continue}i._bindLayer(this),this._feaList.push(i),i.getMap()&&i._toThreeJSGeometry(),this._clouds&&(this.map.viewer.scene.add(this._clouds),console.log("我是云朵被添加cloud",this.map.viewer.scene)),this.add(i)}return this}getFeatures(e,n){if(!e)return this._feaList.slice(0);const i=[];let r,s;for(let a=0,l=this._feaList.length;a<l;a++)r=this._feaList[a],n?s=e.call(n,r):s=e(r),s&&i.push(r);return i}getCount(){return this._feaList.length}isEmpty(){return!this._feaList.length}removeFeature(e){if(!Array.isArray(e))return this.removeFeature([e]);for(let n=e.length-1;n>=0;n--)e[n]instanceof $e||(e[n]=this.removeFeature(e[n])),!(!e[n]||this!==e[n].getLayer())&&e[n]._remove();return this}onRemoveFeature(e){if(!e||this!==e.getLayer())return;const n=this._findInList(e);n>=0&&this._feaList.splice(n,1),e.parent&&e.parent===this?this.remove(e):console.warn("Feature parent mismatch:",e.parent),this._disposeFeatureResources(e)}_findInList(e){const n=this._feaList.length;if(n===0)return-1;let i=0,r=n-1,s;for(;i<=r;){if(s=Math.floor((i+r)/2),this._feaList[s]===e)return s;i=s+1}return-1}_disposeFeatureResources(e){try{e.geometry&&e.geometry.dispose&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>n.dispose?.()):e.material.dispose&&e.material.dispose()),e instanceof h.Object3D&&e.traverse(n=>{n!==e&&this._disposeFeatureResources(n)})}catch(n){console.error("Error disposing feature resources:",n)}}}class Go extends gt{constructor(t,e){super(t,e)}validateFeature(t){return t._baseType==="Line"}}class Vo extends gt{constructor(t,e){super(t,e)}validateFeature(t){return t._baseType==="Point"}}class Co extends gt{constructor(t,e){super(t,e)}validateFeature(t){return t._baseType==="Surface"}}class ko extends gt{constructor(e,n){super(e,n);x(this,"_clouds",null);const i=["texture"];for(const r of i)$n(n,r);this._createClouds(n.texture)}async _createClouds(e){const n=await Ge._loadTexture(e),i=new bo({texture:n,material:h.MeshBasicMaterial});i.castShadow=!0,i.renderOrder=99999,this._clouds=i}validateFeature(e){return e._type==="Cloud"}animate(e,n){this._clouds&&this._clouds.update(this.map.viewer.camera,n,e)}}class bt extends $e{constructor(e){super(e);x(this,"_baseType","Point");this._threeGeometry=this._createThreeGeometry(),this._style&&this._style.applyTo(this._threeGeometry)}_coordsTransform(){const e=this.getMap(),n=new h.Vector3(this._geometry.coordinates[0],this._geometry.coordinates[1],this._geometry.coordinates[2]||500);return e?e.geo2world(n):n}_toThreeJSGeometry(){}_createThreeGeometry(){return new h.Points(new h.BufferGeometry,new h.PointsMaterial({size:1,color:8947848}))}}const Do={};class ci extends bt{constructor(e){super(e);x(this,"_type","Maker")}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}async _createObject(e){switch(e.config.type){case"basic-point":return ri(e.config,new h.Vector3(0,0,0));case"icon-point":return si(e.config,this._position);case"icon-label-point":return Po(e.config,this.getMap(),this._position);default:throw new Error(`Unsupported style type: ${e.config.type}`)}}}ci.mergeOptions(Do);class ui extends $e{constructor(e){super(e);x(this,"_baseType","Line");x(this,"_vertexPoints");this._threeGeometry=this._createThreeGeometry(),this._vertexPoints=[0,0,0],this._style&&this._style.applyTo(this._threeGeometry)}_coordsTransform(){const e=this.getMap(),n=this._geometry;if(this._geometry.type==="LineString"){let r=n.coordinates.map(a=>{const l=new h.Vector3(a[0],a[1],a[2]||0);return e?e.geo2world(l):l}),s=r.flatMap(a=>[a.x,a.y,a.z]);return{_position:r,_vertexPoints:s}}}_toThreeJSGeometry(){}_createThreeGeometry(){const e=new ut,n=new Je({color:8947848,linewidth:.1,dashed:!1,resolution:new h.Vector2(window.innerWidth,window.innerHeight)});return new Ot(e,n)}}const Fo={};class hi extends ui{constructor(e){super(e);x(this,"_type","LineString")}async _toThreeJSGeometry(){let{_vertexPoints:e}=this._coordsTransform();this._vertexPoints=e,this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}async _createObject(e){switch(e.config.type){case"basic-line":return Qt(e.config,this._vertexPoints);default:throw new Error(`Unsupported style type: ${e.config.type}`)}}_updateGeometry(){if(this._disposeGeometry(),this._threeGeometry){const n=this._threeGeometry.geometry;n.setPositions(this._vertexPoints),n.computeBoundingSphere(),n.computeBoundingBox(),this.add(this._threeGeometry),this.updateMatrixWorld(!0),this._tryProcessQueue()}}}hi.mergeOptions(Fo);class Oo extends $e{constructor(e){super(e);x(this,"_baseType","Surface");x(this,"_vertexPoints");this._threeGeometry=this._createThreeGeometry(),this._vertexPoints=[0,0,0],this._style&&this._style.applyTo(this._threeGeometry)}_coordsTransform(){const e=this.getMap(),n=this._geometry;if(!n)throw new Error("Geometry is not defined");if(this._geometry.type==="Polygon"){const i=n.coordinates;let r=[],s=[];return i.forEach(a=>{const l=a.map(u=>{const d=new h.Vector3(u[0],u[1],u[2]||0);return e?e.geo2world(d):d});r.push(l),s.push(...l.flatMap(u=>[u.x,u.y,u.z]))}),{_positions:r,_vertexPoints:s}}else if(this._geometry.type==="MultiPolygon"){const i=n.coordinates;let r=[],s=[];return i.forEach(a=>{const l=[];a.forEach(u=>{const d=u.map(c=>{const p=new h.Vector3(c[0],c[1],c[2]||0);return e?e.geo2world(p):p});l.push(d),s.push(...d.flatMap(c=>[c.x,c.y,c.z]))}),r.push(l)}),{_positions:r,_vertexPoints:s}}else throw new Error(`Unsupported geometry type: ${n.type}`)}_updateGeometry(){let e=this._style?.config.type;if(this.clear(),!this._threeGeometry||!this._vertexPoints?.length){console.warn("Cannot update geometry: missing geometry or vertex data");return}const n=this._threeGeometry,i=n.geometry;try{if(e==="basic-polygon"){const r=i.getAttribute("position");if(r.count*3!==this._vertexPoints.length)throw new Error(`Vertex count mismatch: ${r.count} expected, got ${this._vertexPoints.length/3}`);r.array.set(this._vertexPoints),r.needsUpdate=!0,this._threeGeometry.renderOrder=999,i.computeBoundingSphere(),i.computeBoundingBox(),this.add(this._threeGeometry),n.updateMatrix(),this.updateMatrixWorld(!0)}else e==="extrude-polygon"?(this._threeGeometry.renderOrder=999,this._threeGeometry.updateMatrix(),this.add(this._threeGeometry)):e?.includes("water")&&(this._threeGeometry.updateMatrix(),this.add(this._threeGeometry))}catch(r){throw console.error("Failed to update polygon positions:",r),r}}_createThreeGeometry(){const e=new ut,n=new Je({color:8947848,linewidth:.1,dashed:!1,resolution:new h.Vector2(window.innerWidth,window.innerHeight)});return new Ot(e,n)}}const zo={};class di extends Oo{constructor(e){super(e);x(this,"_type","Polygon")}async _toThreeJSGeometry(){let{_vertexPoints:e}=this._coordsTransform();this._vertexPoints=e,this._style&&(this._threeGeometry&&this.remove(this._threeGeometry),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}async _createObject(e){switch(e.config.type){case"basic-polygon":return Lo(e.config,this._vertexPoints);case"extrude-polygon":return So(e.config,this._vertexPoints);case"water":return Mo(e.config,this.getMap(),this._vertexPoints);case"base-water":return _o(e.config,this._vertexPoints);default:throw new Error(`Unsupported style type: ${e.config.type}`)}}}di.mergeOptions(zo);const Xo={};class pi extends ui{constructor(e){super(e);x(this,"_type","MultiLineString");x(this,"_lineObjects",[]);x(this,"_linesContainer");this._linesContainer=new h.Group}async _toThreeJSGeometry(){const{_position:e}=this._coordsTransform();if(this.clearLines(),this._disposeGeometry(),this._style){for(const n of e){const i=n.flatMap(s=>[s.x,s.y,s.z]),r=await this._createLineObject(this._style,i);this._lineObjects.push(r),this._linesContainer.add(r),this._threeGeometry=this._linesContainer}this.add(this._threeGeometry),this._updateContainer(),this.updateMatrixWorld(!0),this._tryProcessQueue()}}async _createLineObject(e,n){switch(e.config.type){case"basic-line":return Qt(e.config,n);default:throw new Error(`Unsupported style type: ${e.config.type}`)}}_coordsTransform(){const e=this.getMap(),n=this._geometry;if(this._geometry.type==="MultiLineString")return{_position:n.coordinates.map(r=>r.map(s=>{const a=new h.Vector3(s[0],s[1],s[2]||0);return e?e.geo2world(a):a}))}}_updateContainer(){this._linesContainer.updateMatrixWorld(!0)}clearLines(){this._lineObjects.forEach(e=>{this._linesContainer.remove(e),e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()}),this._lineObjects=[]}_updateGeometry(){this._toThreeJSGeometry()}_disposeObject(){}}pi.mergeOptions(Xo);class Uo extends se.MeshStandardMaterial{constructor(e={}){const{shaderOption:n,...i}=e;super({color:"rgb(58,126,182)",roughness:.7,metalness:.1,transparent:!0,opacity:.9,envMapIntensity:.8,...i});x(this,"shaderOption");x(this,"clock");x(this,"time");x(this,"startTime");this.shaderOption={minY:0,maxY:100,minRate:.3,maxRate:1.5,effects:{diffusion:{enabled:!1,color:new se.Color("#9ECDEC"),width:20,speed:1,maxDistance:100,center:void 0},flow:{enabled:!1,color:new se.Color("#00E4FF"),range:10,speed:20},sweep:{enabled:!1,color:new se.Color("#FFFFFF"),width:1.5,speed:10}},...n},this.clock=new se.Clock,this.time={value:0},this.startTime={value:0},this.animate()}onBeforeCompile(e){const{minY:n,maxY:i,minRate:r,maxRate:s,effects:a}=this.shaderOption,l=i-n;e.uniforms={...e.uniforms,time:this.time,uStartTime:this.startTime,uMinY:{value:n},uMaxY:{value:i},uHeightRange:{value:l},uMinRate:{value:r},uMaxRate:{value:s},uDiffusionEnabled:{value:a?.diffusion?.enabled?1:0},uDiffusionColor:{value:a?.diffusion?.color||new se.Color("#9ECDEC")},uDiffusionWidth:{value:a?.diffusion?.width||20},uDiffusionSpeed:{value:a?.diffusion?.speed||1},uDiffusionMaxDistance:{value:a?.diffusion?.maxDistance||100},uDiffusionCenter:{value:a?.diffusion?.center||new se.Vector3(0,0,0)},uFlowEnabled:{value:a?.flow?.enabled?1:0},uFlowColor:{value:a?.flow?.color||new se.Color("#00E4FF")},uFlowRange:{value:a?.flow?.range||10},uFlowSpeed:{value:a?.flow?.speed||20},uSweepEnabled:{value:a?.sweep?.enabled?1:0},uSweepColor:{value:a?.sweep?.color||new se.Color("#FFFFFF")},uSweepWidth:{value:a?.sweep?.width||1.5},uSweepSpeed:{value:a?.sweep?.speed||10}},e.vertexShader=`
604
+ varying vec3 vWorldPosition;
605
+ varying vec3 vPosition;
606
+ varying float vHeight;
607
+ ${e.vertexShader}
608
+ `.replace("#include <begin_vertex>",`
609
+ #include <begin_vertex>
610
+ vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;
611
+ vPosition = position;
612
+ vHeight = position.y;
613
+ `),e.fragmentShader=`
614
+ #define PI 3.141592653589793
615
+ varying vec3 vWorldPosition;
616
+ varying vec3 vPosition;
617
+ varying float vHeight;
618
+ uniform float uMinY;
619
+ uniform float uMaxY;
620
+ uniform float uHeightRange;
621
+ uniform float uMinRate;
622
+ uniform float uMaxRate;
623
+ uniform float time;
624
+ uniform float uStartTime;
625
+ // 修改后的圆环扩散uniforms
626
+ uniform int uDiffusionEnabled;
627
+ uniform vec3 uDiffusionColor;
628
+ uniform float uDiffusionWidth;
629
+ uniform float uDiffusionSpeed;
630
+ uniform float uDiffusionMaxDistance;
631
+ uniform vec3 uDiffusionCenter;
632
+ // 其他效果uniforms保持不变
633
+ uniform int uFlowEnabled;
634
+ uniform vec3 uFlowColor;
635
+ uniform float uFlowRange;
636
+ uniform float uFlowSpeed;
637
+ uniform int uSweepEnabled;
638
+ uniform vec3 uSweepColor;
639
+ uniform float uSweepWidth;
640
+ uniform float uSweepSpeed;
641
+
642
+ float distanceTo(vec2 src, vec2 dst) {
643
+ return distance(src, dst);
644
+ }
645
+
646
+ ${e.fragmentShader}
647
+ `.replace("#include <color_fragment>",`
648
+ #include <color_fragment>
649
+
650
+ // 保留高度渐变计算
651
+ float normalizedHeight = clamp((vWorldPosition.y - uMinY) / uHeightRange, 0.0, 1.0);
652
+ float heightFactor = smoothstep(0.0, 1.0, normalizedHeight);
653
+ diffuseColor.rgb *= mix(uMinRate, uMaxRate, heightFactor);
654
+
655
+ // ================= 修改为圆环扩散效果 =================
656
+ if (uDiffusionEnabled == 1) {
657
+ vec2 position2D = vec2(vWorldPosition.x, vWorldPosition.z);
658
+ vec2 center2D = vec2(uDiffusionCenter.x, uDiffusionCenter.z);
659
+ float distToCenter = distance(position2D, center2D);
660
+
661
+ float progress = mod(time * uDiffusionSpeed, 1.0);
662
+ float currentRadius = progress * uDiffusionMaxDistance;
663
+
664
+ if (distToCenter > currentRadius - uDiffusionWidth &&
665
+ distToCenter < currentRadius) {
666
+ // 核心亮度增强修改:
667
+ float ringFactor = smoothstep(
668
+ currentRadius - uDiffusionWidth,
669
+ currentRadius,
670
+ distToCenter
671
+ );
672
+
673
+ // 1. 增强亮度:颜色值乘以5倍(可根据需要调整)
674
+ vec3 highBrightnessColor = uDiffusionColor * 5.0;
675
+
676
+ // 2. 改用加法混合模式(更亮)
677
+ diffuseColor.rgb += highBrightnessColor * (1.0 - ringFactor);
678
+
679
+ // 3. 防止过曝(可选)
680
+ diffuseColor.rgb = min(diffuseColor.rgb, vec3(2.0));
681
+ }
682
+ }
683
+
684
+ // ================= 保留原有其他效果 =================
685
+ // 流光效果(保持不变)
686
+ if (uFlowEnabled == 1) {
687
+ float dTime = mod(time * uFlowSpeed, uFlowRange * 2.0);
688
+ if (vPosition.z > dTime - uFlowRange && vPosition.z < dTime) {
689
+ float dIndex = sin((dTime - vPosition.z) / uFlowRange * PI);
690
+ diffuseColor.rgb = mix(uFlowColor, diffuseColor.rgb, 1.0 - dIndex);
691
+ }
692
+ }
693
+
694
+ // 扫光效果(保持不变)
695
+ if (uSweepEnabled == 1) {
696
+ float sweepPos = mod(time * uSweepSpeed, 2.0);
697
+ if (vHeight > sweepPos - uSweepWidth && vHeight < sweepPos) {
698
+ float sweepFactor = smoothstep(sweepPos - uSweepWidth, sweepPos, vHeight);
699
+ diffuseColor.rgb = mix(uSweepColor, diffuseColor.rgb, 1.0 - sweepFactor);
700
+ }
701
+ }
702
+ `)}setDiffusionFromObject(e){if(!this.shaderOption.effects?.diffusion)return;const n=new se.Box3().setFromObject(e);if(n.isEmpty())return;const i=new se.Vector3;n.getCenter(i);const r=[new se.Vector3(n.min.x,n.min.y,n.min.z),new se.Vector3(n.max.x,n.max.y,n.max.z)];let s=0;r.forEach(a=>{const l=i.distanceTo(a);l>s&&(s=l)}),this.shaderOption.effects.diffusion={...this.shaderOption.effects.diffusion,center:i,maxDistance:s},this.needsUpdate=!0}updateBoundingBox(e,n){this.shaderOption.minY=e,this.shaderOption.maxY=n,this.needsUpdate=!0}updateEffects(e){this.shaderOption.effects={...this.shaderOption.effects,...e},this.needsUpdate=!0}animate(){requestAnimationFrame(()=>this.animate()),this.time.value=this.clock.getElapsedTime(),this.startTime.value<1&&(this.startTime.value+=.01)}}const Yo={emissive:!1,emissiveIntensity:1,emissiveColor:"#ffffff"};class fi extends bt{constructor(e){super(e);x(this,"_type","Model");x(this,"_emissive",!1);x(this,"_emissiveIntensity",1);x(this,"_emissiveColor","#ffffff");x(this,"_mixer",null);x(this,"_currentAction",null);x(this,"_animations",[]);x(this,"_clock",new h.Clock);x(this,"_autoUpdate",!0);x(this,"_animationRequestId",null);x(this,"_iscity",!1);this._emissive=e.emissive||!1,this._emissiveIntensity=e.emissiveIntensity||1,this._emissiveColor=e.emissiveColor||"#ffffff",this.castShadow=e.castShadow||!1,this.receiveShadow=e.receiveShadow||!1,this._iscity=e.iscity||!1}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this.modelunino=await this._createObject(this._style),this._threeGeometry=this.modelunino.model,this.modelunino.animations&&this.modelunino.animations.length>0&&(this._animations=this.modelunino.animations,this._mixer=new h.AnimationMixer(this._threeGeometry),this._startAnimationLoop(),this.playAnimation({name:this._animations[0].name,loop:!0,speed:1.5,fadeInDuration:.5,fadeOutDuration:.3})),this._updateGeometry(),this.setShadows({cast:this.castShadow,receive:this.receiveShadow}),this._applyEmissionProperties(),this._iscity&&this._rendercity())}async _createObject(e){switch(e.config.type){case"fbx":case"gltf":return xo(e.config,this._position);default:throw new Error(`不支持的样式类型: ${e.config.type}`)}}_applyEmissionProperties(){this._threeGeometry&&this._threeGeometry.traverse(e=>{if("material"in e){const n=e.material;n&&(n.emissiveIntensity=this._emissive?this._emissiveIntensity:0,n.emissive&&n.emissive.setStyle(this._emissiveColor))}})}get emissive(){return this._emissive}set emissive(e){this._emissive=e,this._applyEmissionProperties()}get emissiveIntensity(){return this._emissiveIntensity}set emissiveIntensity(e){this._emissiveIntensity=e,this._applyEmissionProperties()}get emissiveColor(){return this._emissiveColor}set emissiveColor(e){this._emissiveColor=e,this._applyEmissionProperties()}setEmission(e,n,i){this._emissive=e,n!==void 0&&(this._emissiveIntensity=n),i!==void 0&&(this._emissiveColor=i),this._applyEmissionProperties()}async setShadows(e){this.castShadow=e.cast,this.receiveShadow=e.receive,this._threeGeometry&&this._threeGeometry.traverse(n=>{n.isMesh&&n.material&&(n.castShadow=e.cast,n.receiveShadow=e.receive)})}playAnimation(e){if(!this._mixer||this._animations.length===0){console.warn("模型没有可用的动画");return}this._currentAction&&(e.fadeOutDuration&&e.fadeOutDuration>0?this._currentAction.fadeOut(e.fadeOutDuration):this._currentAction.stop());const n=typeof e.name=="number"?this._animations[e.name]:this._animations.find(i=>i.name===e.name);if(!n){console.warn(`找不到动画: ${e.name}`);return}this._currentAction=this._mixer.clipAction(n),this._currentAction.setLoop(e.loop?h.LoopRepeat:h.LoopOnce,e.loop?1/0:1),this._currentAction.timeScale=e.speed||1,this._currentAction.time=e.startAt||0,this._currentAction.setEffectiveWeight(e.weight||1),e.fadeInDuration&&e.fadeInDuration>0&&this._currentAction.fadeIn(e.fadeInDuration),this._currentAction.play(),this._autoUpdate&&this._animationRequestId===null&&this._startAnimationLoop()}stopAnimation(e={}){this._currentAction&&(e.fadeDuration&&e.fadeDuration>0?(this._currentAction.fadeOut(e.fadeDuration),setTimeout(()=>{this._currentAction&&(this._currentAction.stop(),this._currentAction=null)},e.fadeDuration*1e3)):(this._currentAction.stop(),this._currentAction=null))}setAnimationPaused(e){this._currentAction&&(this._currentAction.paused=e.paused)}setAnimationSpeed(e){this._currentAction&&(this._currentAction.timeScale=e.speed)}updateAnimation(e){this._mixer&&this._mixer.update(e.deltaTime)}getAnimationNames(){return this._animations.map(e=>e.name)}getCurrentAnimationName(){return this._currentAction?this._currentAction.getClip().name:null}getAnimationDuration(e){let n;return typeof e.name=="number"?n=this._animations[e.name]:n=this._animations.find(i=>i.name===e.name),n?n.duration:null}dispose(){this._stopAnimationLoop(),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this._threeGeometry)),super.dispose()}_startAnimationLoop(){if(!this._autoUpdate||this._animationRequestId!==null)return;const e=()=>{if(this._mixer){const n=this._clock.getDelta();this._mixer.update(n)}this._animationRequestId=requestAnimationFrame(e)};this._clock.start(),this._animationRequestId=requestAnimationFrame(e)}_stopAnimationLoop(){this._animationRequestId!==null&&(cancelAnimationFrame(this._animationRequestId),this._animationRequestId=null),this._clock.stop()}setAutoUpdate(e){this._autoUpdate=e,e?this._startAnimationLoop():this._stopAnimationLoop()}_rendercity(){this.traverse(e=>{if(e instanceof h.Mesh&&e.material){if(e.castShadow=!0,e.castShadow=!0,e.name==="building"){const n=new Uo({color:new h.Color("#6BA7EC").multiplyScalar(1.4),opacity:.8,shaderOption:{minY:0,maxY:50,minRate:.3,maxRate:1.5,effects:{diffusion:{enabled:!0,color:new h.Color("#FFFFF"),width:80,speed:.16666666666666666},flow:{enabled:!1,color:new h.Color("#FFFFF"),range:1e3,speed:3e3},sweep:{enabled:!0,color:new h.Color("#ffffff"),width:3,speed:5}}}}),i=new h.Box3().setFromObject(e);n.updateBoundingBox(i.min.y,i.max.y),n.setDiffusionFromObject(e),e.material=n,e.material.needsUpdate=!0}e.name==="grass"&&(e.castShadow=!1,e.material.emissiveIntensity=.1,e.material.emissive=new h.Color("#3FD3BD"),e.material.needsUpdate=!0)}})}}fi.mergeOptions(Yo);const Ko={};class mi extends bt{constructor(e){super(e);x(this,"_type","Cloud")}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}_updateGeometry(){this._disposeGeometry();const e=this.getLayer();this._threeGeometry&&(this._threeGeometry.position.copy(this._position),this._threeGeometry.renderOrder=1e3,e&&(e._clouds.add(this._threeGeometry),e._clouds.updateMatrixWorld()))}async _createObject(e){switch(e.config.type){case"cloud":return Zo(e.config,this._position);default:throw new Error(`不支持的样式类型: ${e.config.type}`)}}}mi.mergeOptions(Ko);const Bo={};class yi extends bt{constructor(e){super(e);x(this,"_type","Label")}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),console.log(this._threeGeometry," this._threeGeometry this._threeGeometry this._threeGeometry this._threeGeometry this._threeGeometry this._threeGeometry this._threeGeometry "),this._updateGeometry())}async _createObject(e){switch(e.config.type){case"canvas-label-fixed":return To(e.config,new h.Vector3(0,0,0),this.getMap());case"canvas-label":return Io(e.config,new h.Vector3(0,0,0));default:throw new Error(`Unsupported style type: ${e.config.type}`)}}}yi.mergeOptions(Bo),console.log("%c✨ terra.gl V"+Zi+" ","color:rgb(255, 255, 255); font-weight: bold; background: linear-gradient(90deg, #ffb6c1, #ff69b4); padding: 5px; border-radius: 5px;"),N.ArcGisDemSource=mo,N.ArcGisSource=fo,N.CloudsLayer=ko,N.EventClass=ei,N.ICloud=mi,N.Label=yi,N.LineLayer=Go,N.LineString=hi,N.Maker=ci,N.Map=ft,N.MapBoxSource=yo,N.Model=fi,N.MultiLineString=pi,N.PointLayer=Vo,N.Polygon=di,N.PolygonLayer=Co,N.TDTQMSource=ho,N.TDTSource=uo,N.Viewer=Cn,N.WMTSSource=po,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})});