@soonspacejs/plugin-gs3d-loader 2.13.8 → 2.13.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3 -7
- package/dist/index.esm.js +1 -1
- package/dist/types.d.ts +6 -4
- package/example/gs/dog.splat +0 -0
- package/example/gs/scene.ply +0 -0
- package/example/index.html +68 -73
- package/package.json +3 -3
- package/src/index.ts +30 -49
- package/src/types.ts +6 -5
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"three";import{Ray as t,Plane as s,MathUtils as n,EventDispatcher as r,Vector3 as i,MOUSE as o,TOUCH as a,Quaternion as l,Spherical as c,Vector2 as h}from"three";class d{static idGen=0;constructor(e,t){let s,n;this.promise=new Promise(((e,t)=>{s=e,n=t}));const r=s.bind(this),i=n.bind(this);e(((...e)=>{r(...e)}).bind(this),(e=>{i(e)}).bind(this)),this.abortHandler=t,this.id=d.idGen++}then(e){return new d(((t,s)=>{this.promise=this.promise.then(((...s)=>{const n=e(...s);n instanceof Promise||n instanceof d?n.then(((...e)=>{t(...e)})):t(n)})).catch((e=>{s(e)}))}),this.abortHandler)}catch(e){return new d((t=>{this.promise=this.promise.then(((...e)=>{t(...e)})).catch(e)}),this.abortHandler)}abort(e){this.abortHandler&&this.abortHandler(e)}}class p extends Error{constructor(e){super(e)}}!function(){const e=new Float32Array(1),t=new Int32Array(e.buffer)}();const u=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),m=function(e,t,s=!0,n){const r=new AbortController,i=r.signal;let o=!1;let a=!1;const l=(e,s,n,r)=>{t&&!a&&(t(e,s,n,r),100===e&&(a=!0))};return new d(((t,r)=>{const a={signal:i};n&&(a.headers=n),fetch(e,a).then((async e=>{if(!e.ok){const t=await e.text();return void r(new Error(`Fetch failed: ${e.status} ${e.statusText} ${t}`))}const n=e.body.getReader();let i=0,a=e.headers.get("Content-Length"),c=a?parseInt(a):void 0;const h=[];for(;!o;)try{const{value:e,done:r}=await n.read();if(r){if(l(100,"100%",e,c),s){const e=new Blob(h).arrayBuffer();t(e)}else t();break}let o,a;i+=e.length,void 0!==c&&(o=i/c*100,a=`${o.toFixed(2)}%`),s&&h.push(e),l(o,a,e,c)}catch(e){return void r(e)}})).catch((e=>{r(new p(e))}))}),(e=>{r.abort(e),o=!0}))},A=function(e,t,s){return Math.max(Math.min(e,s),t)},f=function(){return performance.now()/1e3},g=e=>{if(e.geometry&&(e.geometry.dispose(),e.geometry=null),e.material&&(e.material.dispose(),e.material=null),e.children)for(let t of e.children)g(t)},S=(e,t)=>new Promise((s=>{window.setTimeout((()=>{s(e?e():void 0)}),t?1:50)})),C=(e=0)=>{let t=0;if(1===e)t=9;else if(2===e)t=24;else if(3===e)t=45;else if(e>3)throw new Error("getSphericalHarmonicsComponentCountForDegree() -> Invalid spherical harmonics degree");return t},y=()=>{let e,t;return{promise:new Promise(((s,n)=>{e=s,t=n})),resolve:e,reject:t}},x=e=>{let t,s;e||(e=()=>{});return{promise:new d(((e,n)=>{t=e,s=n}),e),resolve:t,reject:s}};class v{constructor(e,t,s){this.major=e,this.minor=t,this.patch=s}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function I(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function B(){if(I()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new v(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}class w{static OFFSET={X:0,Y:1,Z:2,SCALE0:3,SCALE1:4,SCALE2:5,ROTATION0:6,ROTATION1:7,ROTATION2:8,ROTATION3:9,FDC0:10,FDC1:11,FDC2:12,OPACITY:13,FRC0:14,FRC1:15,FRC2:16,FRC3:17,FRC4:18,FRC5:19,FRC6:20,FRC7:21,FRC8:22,FRC9:23,FRC10:24,FRC11:25,FRC12:26,FRC13:27,FRC14:28,FRC15:29,FRC16:30,FRC17:31,FRC18:32,FRC19:33,FRC20:34,FRC21:35,FRC22:36,FRC23:37};constructor(e=0){this.sphericalHarmonicsDegree=e,this.sphericalHarmonicsCount=C(this.sphericalHarmonicsDegree),this.componentCount=this.sphericalHarmonicsCount+14,this.defaultSphericalHarmonics=new Array(this.sphericalHarmonicsCount).fill(0),this.splats=[],this.splatCount=0}static createSplat(e=0){const t=[0,0,0,1,1,1,1,0,0,0,0,0,0,0];let s=C(e);for(let e=0;e<s;e++)t.push(0);return t}addSplat(e){this.splats.push(e),this.splatCount++}getSplat(e){return this.splats[e]}addDefaultSplat(){const e=w.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(e),e}addSplatFromComonents(e,t,s,n,r,i,o,a,l,c,h,d,p,u,...m){const A=[e,t,s,n,r,i,o,a,l,c,h,d,p,u,...this.defaultSphericalHarmonics];for(let e=0;e<m.length&&e<this.sphericalHarmonicsCount;e++)A[e]=m[e];return this.addSplat(A),A}addSplatFromArray(e,t){const s=e.splats[t],n=w.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<s.length;e++)n[e]=s[e];this.addSplat(n)}}class b{static DefaultSplatSortDistanceMapPrecision=16;static MemoryPageSize=65536;static BytesPerFloat=4;static BytesPerInt=4;static MaxScenes=32;static ProgressiveLoadSectionSize=262144;static ProgressiveLoadSectionDelayDuration=15;static SphericalHarmonics8BitCompressionRange=3}const D=b.SphericalHarmonics8BitCompressionRange/2,T=e.DataUtils.toHalfFloat.bind(e.DataUtils),E=e.DataUtils.fromHalfFloat.bind(e.DataUtils),M=(t,s,n=!1,r,i)=>0===s?t:1===s||2===s&&!n?e.DataUtils.fromHalfFloat(t):2===s?R(t,r,i):void 0,F=(e,t,s)=>{e=A(e,t,s);const n=s-t;return A(Math.floor((e-t)/n*255),0,255)},R=(e,t,s)=>e/255*(s-t)+t,P=(e,t,s)=>F(E(e,t,s)),H=(e,t,s)=>T(R(e,t,s)),k=(e,t,s,n=!1)=>0===s?e.getFloat32(4*t,!0):1===s||2===s&&!n?e.getUint16(2*t,!0):e.getUint8(t,!0),L=function(){const e=e=>e;return function(t,s,n,r=!1){if(s===n)return t;let i=e;return 2===s&&r?1===n?i=H:0==n&&(i=R):2===s||1===s?0===n?i=E:2==n&&(i=r?P:e):0===s&&(1===n?i=T:2==n&&(i=r?F:T)),i(t)}}(),O=(e,t,s,n,r=0)=>{const i=new Uint8Array(e,t),o=new Uint8Array(s,n);for(let e=0;e<r;e++)o[e]=i[e]};class U{static CurrentMajorVersion=0;static CurrentMinorVersion=1;static CenterComponentCount=3;static ScaleComponentCount=3;static RotationComponentCount=4;static ColorComponentCount=4;static CovarianceComponentCount=6;static SplatScaleOffsetFloat=3;static SplatRotationOffsetFloat=6;static CompressionLevels={0:{BytesPerCenter:12,BytesPerScale:12,BytesPerRotation:16,BytesPerColor:4,ScaleOffsetBytes:12,RotationffsetBytes:24,ColorOffsetBytes:40,SphericalHarmonicsOffsetBytes:44,ScaleRange:1,BytesPerSphericalHarmonicsComponent:4,SphericalHarmonicsOffsetFloat:11,SphericalHarmonicsDegrees:{0:{BytesPerSplat:44},1:{BytesPerSplat:80},2:{BytesPerSplat:140}}},1:{BytesPerCenter:6,BytesPerScale:6,BytesPerRotation:8,BytesPerColor:4,ScaleOffsetBytes:6,RotationffsetBytes:12,ColorOffsetBytes:20,SphericalHarmonicsOffsetBytes:24,ScaleRange:32767,BytesPerSphericalHarmonicsComponent:2,SphericalHarmonicsOffsetFloat:12,SphericalHarmonicsDegrees:{0:{BytesPerSplat:24},1:{BytesPerSplat:42},2:{BytesPerSplat:72}}},2:{BytesPerCenter:6,BytesPerScale:6,BytesPerRotation:8,BytesPerColor:4,ScaleOffsetBytes:6,RotationffsetBytes:12,ColorOffsetBytes:20,SphericalHarmonicsOffsetBytes:24,ScaleRange:32767,BytesPerSphericalHarmonicsComponent:1,SphericalHarmonicsOffsetFloat:12,SphericalHarmonicsDegrees:{0:{BytesPerSplat:24},1:{BytesPerSplat:33},2:{BytesPerSplat:48}}}};static CovarianceSizeFloats=6;static HeaderSizeBytes=4096;static SectionHeaderSizeBytes=1024;static BucketStorageSizeBytes=12;static BucketStorageSizeFloats=3;static BucketBlockSize=5;static BucketSize=256;constructor(e,t=!0){this.constructFromBuffer(e,t)}getSplatCount(){return this.splatCount}getMaxSplatCount(){return this.maxSplatCount}getMinSphericalHarmonicsDegree(){let e=0;for(let t=0;t<this.sections.length;t++){const s=this.sections[t];(0===t||s.sphericalHarmonicsDegree<e)&&(e=s.sphericalHarmonicsDegree)}return e}getBucketIndex(e,t){let s;const n=e.fullBucketCount*e.bucketSize;if(t<n)s=Math.floor(t/e.bucketSize);else{let r=n;s=e.fullBucketCount;let i=0;for(;r<e.splatCount;){let n=e.partiallyFilledBucketLengths[i];if(t>=r&&t<r+n)break;r+=n,s++,i++}}return s}getSplatCenter(e,t,s){const n=this.globalSplatIndexToSectionMap[e],r=this.sections[n],i=e-r.splatCountOffset,o=r.bytesPerSplat*i,a=new DataView(this.bufferData,r.dataBase+o),l=k(a,0,this.compressionLevel),c=k(a,1,this.compressionLevel),h=k(a,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(r,i)*U.BucketStorageSizeFloats,s=r.compressionScaleFactor,n=r.compressionScaleRange;t.x=(l-n)*s+r.bucketArray[e],t.y=(c-n)*s+r.bucketArray[e+1],t.z=(h-n)*s+r.bucketArray[e+2]}else t.x=l,t.y=c,t.z=h;s&&t.applyMatrix4(s)}getSplatScaleAndRotation=function(){const t=new e.Matrix4,s=new e.Matrix4,n=new e.Matrix4,r=new e.Vector3,i=new e.Vector3,o=new e.Quaternion;return function(e,a,l,c,h){const d=this.globalSplatIndexToSectionMap[e],p=this.sections[d],u=e-p.splatCountOffset,m=p.bytesPerSplat*u+U.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,A=new DataView(this.bufferData,p.dataBase+m);i.set(M(k(A,0,this.compressionLevel),this.compressionLevel),M(k(A,1,this.compressionLevel),this.compressionLevel),M(k(A,2,this.compressionLevel),this.compressionLevel)),h&&(void 0!==h.x&&(i.x=h.x),void 0!==h.y&&(i.y=h.y),void 0!==h.z&&(i.z=h.z)),o.set(M(k(A,4,this.compressionLevel),this.compressionLevel),M(k(A,5,this.compressionLevel),this.compressionLevel),M(k(A,6,this.compressionLevel),this.compressionLevel),M(k(A,3,this.compressionLevel),this.compressionLevel)),c?(t.makeScale(i.x,i.y,i.z),s.makeRotationFromQuaternion(o),n.copy(t).multiply(s).multiply(c),n.decompose(r,l,a)):(a.copy(i),l.copy(o))}}();getSplatColor(e,t){const s=this.globalSplatIndexToSectionMap[e],n=this.sections[s],r=e-n.splatCountOffset,i=n.bytesPerSplat*r+U.CompressionLevels[this.compressionLevel].ColorOffsetBytes,o=new Uint8Array(this.bufferData,n.dataBase+i,4);t.set(o[0],o[1],o[2],o[3])}fillSplatCenterArray(t,s,n,r,i){const o=this.splatCount;n=n||0,r=r||o-1,void 0===i&&(i=n);const a=new e.Vector3;for(let e=n;e<=r;e++){const r=this.globalSplatIndexToSectionMap[e],o=this.sections[r],l=e-o.splatCountOffset,c=(e-n+i)*U.CenterComponentCount,h=o.bytesPerSplat*l,d=new DataView(this.bufferData,o.dataBase+h),p=k(d,0,this.compressionLevel),u=k(d,1,this.compressionLevel),m=k(d,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(o,l)*U.BucketStorageSizeFloats,t=o.compressionScaleFactor,s=o.compressionScaleRange;a.x=(p-s)*t+o.bucketArray[e],a.y=(u-s)*t+o.bucketArray[e+1],a.z=(m-s)*t+o.bucketArray[e+2]}else a.x=p,a.y=u,a.z=m;s&&a.applyMatrix4(s),t[c]=a.x,t[c+1]=a.y,t[c+2]=a.z}}fillSplatScaleRotationArray=function(){const t=new e.Matrix4,s=new e.Matrix4,n=new e.Matrix4,r=new e.Vector3,i=new e.Quaternion,o=new e.Vector3,a=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(e,l,c,h,d,p,u,m){const A=this.splatCount;h=h||0,d=d||A-1,void 0===p&&(p=h);const f=(e,t)=>(void 0===t&&(t=this.compressionLevel),L(e,t,u));for(let u=h;u<=d;u++){const d=this.globalSplatIndexToSectionMap[u],A=this.sections[d],g=u-A.splatCountOffset,S=A.bytesPerSplat*g+U.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,C=(u-h+p)*U.ScaleComponentCount,y=(u-h+p)*U.RotationComponentCount,x=new DataView(this.bufferData,A.dataBase+S),v=m&&void 0!==m.x?m.x:k(x,0,this.compressionLevel),I=m&&void 0!==m.y?m.y:k(x,1,this.compressionLevel),B=m&&void 0!==m.z?m.z:k(x,2,this.compressionLevel),w=k(x,3,this.compressionLevel),b=k(x,4,this.compressionLevel),D=k(x,5,this.compressionLevel),T=k(x,6,this.compressionLevel);r.set(M(v,this.compressionLevel),M(I,this.compressionLevel),M(B,this.compressionLevel)),i.set(M(b,this.compressionLevel),M(D,this.compressionLevel),M(T,this.compressionLevel),M(w,this.compressionLevel)).normalize(),c&&(o.set(0,0,0),t.makeScale(r.x,r.y,r.z),s.makeRotationFromQuaternion(i),n.identity().premultiply(t).premultiply(s),n.premultiply(c),n.decompose(o,i,r),i.normalize()),a(i),e&&(e[C]=f(r.x,0),e[C+1]=f(r.y,0),e[C+2]=f(r.z,0)),l&&(l[y]=f(i.x,0),l[y+1]=f(i.y,0),l[y+2]=f(i.z,0),l[y+3]=f(i.w,0))}}}();static computeCovariance=function(){const t=new e.Matrix4,s=new e.Matrix3,n=new e.Matrix3,r=new e.Matrix3,i=new e.Matrix3,o=new e.Matrix3,a=new e.Matrix3;return function(e,l,c,h,d=0,p){t.makeScale(e.x,e.y,e.z),s.setFromMatrix4(t),t.makeRotationFromQuaternion(l),n.setFromMatrix4(t),r.copy(n).multiply(s),i.copy(r).transpose().premultiply(r),c&&(o.setFromMatrix4(c),a.copy(o).transpose(),i.multiply(a),i.premultiply(o)),p>=1?(h[d]=T(i.elements[0]),h[d+1]=T(i.elements[3]),h[d+2]=T(i.elements[6]),h[d+3]=T(i.elements[4]),h[d+4]=T(i.elements[7]),h[d+5]=T(i.elements[8])):(h[d]=i.elements[0],h[d+1]=i.elements[3],h[d+2]=i.elements[6],h[d+3]=i.elements[4],h[d+4]=i.elements[7],h[d+5]=i.elements[8])}}();fillSplatCovarianceArray(t,s,n,r,i,o){const a=this.splatCount,l=new e.Vector3,c=new e.Quaternion;n=n||0,r=r||a-1,void 0===i&&(i=n);for(let e=n;e<=r;e++){const r=this.globalSplatIndexToSectionMap[e],a=this.sections[r],h=e-a.splatCountOffset,d=(e-n+i)*U.CovarianceComponentCount,p=a.bytesPerSplat*h+U.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,u=new DataView(this.bufferData,a.dataBase+p);l.set(M(k(u,0,this.compressionLevel),this.compressionLevel),M(k(u,1,this.compressionLevel),this.compressionLevel),M(k(u,2,this.compressionLevel),this.compressionLevel)),c.set(M(k(u,4,this.compressionLevel),this.compressionLevel),M(k(u,5,this.compressionLevel),this.compressionLevel),M(k(u,6,this.compressionLevel),this.compressionLevel),M(k(u,3,this.compressionLevel),this.compressionLevel)),U.computeCovariance(l,c,s,t,d,o)}}fillSplatColorArray(e,t,s,n,r){const i=this.splatCount;s=s||0,n=n||i-1,void 0===r&&(r=s);for(let i=s;i<=n;i++){const n=this.globalSplatIndexToSectionMap[i],o=this.sections[n],a=i-o.splatCountOffset,l=(i-s+r)*U.ColorComponentCount,c=o.bytesPerSplat*a+U.CompressionLevels[this.compressionLevel].ColorOffsetBytes,h=new Uint8Array(this.bufferData,o.dataBase+c);let d=h[3];d=d>=t?d:0,e[l]=h[0],e[l+1]=h[1],e[l+2]=h[2],e[l+3]=d}}fillSphericalHarmonicsArray=function(){for(let t=0;t<15;t++)new e.Vector3;const t=new e.Matrix3,s=new e.Matrix4,n=new e.Vector3,r=new e.Vector3,i=new e.Quaternion,o=[],a=[],l=[],c=[],h=[],d=[],p=[],u=[],m=[],A=[],f=[],g=[],S=[],y=[],x=[],v=[],I=[],B=[],w=e=>e,b=(e,t,s,n)=>{e[0]=t,e[1]=s,e[2]=n},D=(e,t,s,n,r)=>{e[0]=k(t,n,r,!0),e[1]=k(t,n+s,r,!0),e[2]=k(t,n+s+s,r,!0)},R=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},H=(e,t,s,n)=>{t[s]=n(e[0]),t[s+1]=n(e[1]),t[s+2]=n(e[2])},L=(e,t,s,n,r)=>(t[0]=M(e[0],s,!0,n,r),t[1]=M(e[1],s,!0,n,r),t[2]=M(e[2],s,!0,n,r),t);return function(e,M,k,O,z,_,Q){const V=this.splatCount;O=O||0,z=z||V-1,void 0===_&&(_=O),k&&M>=1&&(s.copy(k),s.decompose(n,i,r),i.normalize(),s.makeRotationFromQuaternion(i),t.setFromMatrix4(s),b(o,t.elements[4],-t.elements[7],t.elements[1]),b(a,-t.elements[5],t.elements[8],-t.elements[2]),b(l,t.elements[3],-t.elements[6],t.elements[0]));const N=e=>P(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),G=e=>F(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let t=O;t<=z;t++){const s=this.globalSplatIndexToSectionMap[t],n=this.sections[s];M=Math.min(M,n.sphericalHarmonicsDegree);const r=C(M),i=t-n.splatCountOffset,b=n.bytesPerSplat*i+U.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,F=new DataView(this.bufferData,n.dataBase+b),P=(t-O+_)*r;let z=k?0:this.compressionLevel,V=w;z!==Q&&(1===z?0===Q?V=E:2==Q&&(V=N):0===z&&(1===Q?V=T:2==Q&&(V=G)));const K=this.minSphericalHarmonicsCoeff,q=this.maxSphericalHarmonicsCoeff;M>=1&&(D(m,F,3,0,this.compressionLevel),D(A,F,3,1,this.compressionLevel),D(f,F,3,2,this.compressionLevel),k?(L(m,m,this.compressionLevel,K,q),L(A,A,this.compressionLevel,K,q),L(f,f,this.compressionLevel,K,q),U.rotateSphericalHarmonics3(m,A,f,o,a,l,y,x,v)):(R(m,y),R(A,x),R(f,v)),H(y,e,P,V),H(x,e,P+3,V),H(v,e,P+6,V),M>=2&&(D(m,F,5,9,this.compressionLevel),D(A,F,5,10,this.compressionLevel),D(f,F,5,11,this.compressionLevel),D(g,F,5,12,this.compressionLevel),D(S,F,5,13,this.compressionLevel),k?(L(m,m,this.compressionLevel,K,q),L(A,A,this.compressionLevel,K,q),L(f,f,this.compressionLevel,K,q),L(g,g,this.compressionLevel,K,q),L(S,S,this.compressionLevel,K,q),U.rotateSphericalHarmonics5(m,A,f,g,S,o,a,l,c,h,d,p,u,y,x,v,I,B)):(R(m,y),R(A,x),R(f,v),R(g,I),R(S,B)),H(y,e,P+9,V),H(x,e,P+12,V),H(v,e,P+15,V),H(I,e,P+18,V),H(B,e,P+21,V)))}}}();static dot3=(e,t,s,n,r)=>{r[0]=r[1]=r[2]=0;const i=n[0],o=n[1],a=n[2];U.addInto3(e[0]*i,e[1]*i,e[2]*i,r),U.addInto3(t[0]*o,t[1]*o,t[2]*o,r),U.addInto3(s[0]*a,s[1]*a,s[2]*a,r)};static addInto3=(e,t,s,n)=>{n[0]=n[0]+e,n[1]=n[1]+t,n[2]=n[2]+s};static dot5=(e,t,s,n,r,i,o)=>{o[0]=o[1]=o[2]=0;const a=i[0],l=i[1],c=i[2],h=i[3],d=i[4];U.addInto3(e[0]*a,e[1]*a,e[2]*a,o),U.addInto3(t[0]*l,t[1]*l,t[2]*l,o),U.addInto3(s[0]*c,s[1]*c,s[2]*c,o),U.addInto3(n[0]*h,n[1]*h,n[2]*h,o),U.addInto3(r[0]*d,r[1]*d,r[2]*d,o)};static rotateSphericalHarmonics3=(e,t,s,n,r,i,o,a,l)=>{U.dot3(e,t,s,n,o),U.dot3(e,t,s,r,a),U.dot3(e,t,s,i,l)};static rotateSphericalHarmonics5=(e,t,s,n,r,i,o,a,l,c,h,d,p,u,m,A,f,g)=>{const S=Math.sqrt(1/4),C=Math.sqrt(3/4),y=Math.sqrt(1/3),x=Math.sqrt(4/3),v=Math.sqrt(1/12);l[0]=S*(a[2]*i[0]+a[0]*i[2]+(i[2]*a[0]+i[0]*a[2])),l[1]=a[1]*i[0]+i[1]*a[0],l[2]=C*(a[1]*i[1]+i[1]*a[1]),l[3]=a[1]*i[2]+i[1]*a[2],l[4]=S*(a[2]*i[2]-a[0]*i[0]+(i[2]*a[2]-i[0]*a[0])),U.dot5(e,t,s,n,r,l,u),c[0]=S*(o[2]*i[0]+o[0]*i[2]+(i[2]*o[0]+i[0]*o[2])),c[1]=o[1]*i[0]+i[1]*o[0],c[2]=C*(o[1]*i[1]+i[1]*o[1]),c[3]=o[1]*i[2]+i[1]*o[2],c[4]=S*(o[2]*i[2]-o[0]*i[0]+(i[2]*o[2]-i[0]*o[0])),U.dot5(e,t,s,n,r,c,m),h[0]=y*(o[2]*o[0]+o[0]*o[2])+-v*(a[2]*a[0]+a[0]*a[2]+(i[2]*i[0]+i[0]*i[2])),h[1]=x*o[1]*o[0]+-y*(a[1]*a[0]+i[1]*i[0]),h[2]=o[1]*o[1]+-S*(a[1]*a[1]+i[1]*i[1]),h[3]=x*o[1]*o[2]+-y*(a[1]*a[2]+i[1]*i[2]),h[4]=y*(o[2]*o[2]-o[0]*o[0])+-v*(a[2]*a[2]-a[0]*a[0]+(i[2]*i[2]-i[0]*i[0])),U.dot5(e,t,s,n,r,h,A),d[0]=S*(o[2]*a[0]+o[0]*a[2]+(a[2]*o[0]+a[0]*o[2])),d[1]=o[1]*a[0]+a[1]*o[0],d[2]=C*(o[1]*a[1]+a[1]*o[1]),d[3]=o[1]*a[2]+a[1]*o[2],d[4]=S*(o[2]*a[2]-o[0]*a[0]+(a[2]*o[2]-a[0]*o[0])),U.dot5(e,t,s,n,r,d,f),p[0]=S*(a[2]*a[0]+a[0]*a[2]-(i[2]*i[0]+i[0]*i[2])),p[1]=a[1]*a[0]-i[1]*i[0],p[2]=C*(a[1]*a[1]-i[1]*i[1]),p[3]=a[1]*a[2]-i[1]*i[2],p[4]=S*(a[2]*a[2]-a[0]*a[0]-(i[2]*i[2]-i[0]*i[0])),U.dot5(e,t,s,n,r,p,g)};static parseHeader(t){const s=new Uint8Array(t,0,U.HeaderSizeBytes),n=new Uint16Array(t,0,U.HeaderSizeBytes/2),r=new Uint32Array(t,0,U.HeaderSizeBytes/4),i=new Float32Array(t,0,U.HeaderSizeBytes/4);return{versionMajor:s[0],versionMinor:s[1],maxSectionCount:r[1],sectionCount:r[2],maxSplatCount:r[3],splatCount:r[4],compressionLevel:n[10],sceneCenter:new e.Vector3(i[6],i[7],i[8]),minSphericalHarmonicsCoeff:i[9]||-D,maxSphericalHarmonicsCoeff:i[10]||D}}static writeHeaderCountsToBuffer(e,t,s){const n=new Uint32Array(s,0,U.HeaderSizeBytes/4);n[2]=e,n[4]=t}static writeHeaderToBuffer(e,t){const s=new Uint8Array(t,0,U.HeaderSizeBytes),n=new Uint16Array(t,0,U.HeaderSizeBytes/2),r=new Uint32Array(t,0,U.HeaderSizeBytes/4),i=new Float32Array(t,0,U.HeaderSizeBytes/4);s[0]=e.versionMajor,s[1]=e.versionMinor,s[2]=0,s[3]=0,r[1]=e.maxSectionCount,r[2]=e.sectionCount,r[3]=e.maxSplatCount,r[4]=e.splatCount,n[10]=e.compressionLevel,i[6]=e.sceneCenter.x,i[7]=e.sceneCenter.y,i[8]=e.sceneCenter.z,i[9]=e.minSphericalHarmonicsCoeff||-D,i[10]=e.maxSphericalHarmonicsCoeff||D}static parseSectionHeaders(e,t,s=0,n){const r=e.compressionLevel,i=e.maxSectionCount,o=new Uint16Array(t,s,i*U.SectionHeaderSizeBytes/2),a=new Uint32Array(t,s,i*U.SectionHeaderSizeBytes/4),l=new Float32Array(t,s,i*U.SectionHeaderSizeBytes/4),c=[];let h=0,d=h/2,p=h/4,u=U.HeaderSizeBytes+e.maxSectionCount*U.SectionHeaderSizeBytes,m=0;for(let e=0;e<i;e++){const t=a[p+1],s=a[p+2],i=a[p+3],A=l[p+4],f=A/2,g=o[d+10],S=a[p+6]||U.CompressionLevels[r].ScaleRange,C=a[p+8],y=a[p+9],x=4*y,v=g*i+x,I=o[d+20],{bytesPerSplat:B}=U.calculateComponentStorage(r,I),w=B*t,b=w+v,D={bytesPerSplat:B,splatCountOffset:m,splatCount:n?t:0,maxSplatCount:t,bucketSize:s,bucketCount:i,bucketBlockSize:A,halfBucketBlockSize:f,bucketStorageSizeBytes:g,bucketsStorageSizeBytes:v,splatDataStorageSizeBytes:w,storageSizeBytes:b,compressionScaleRange:S,compressionScaleFactor:f/S,base:u,bucketsBase:u+x,dataBase:u+v,fullBucketCount:C,partiallyFilledBucketCount:y,sphericalHarmonicsDegree:I};c[e]=D,u+=b,h+=U.SectionHeaderSizeBytes,d=h/2,p=h/4,m+=t}return c}static writeSectionHeaderToBuffer(e,t,s,n=0){const r=new Uint16Array(s,n,U.SectionHeaderSizeBytes/2),i=new Uint32Array(s,n,U.SectionHeaderSizeBytes/4),o=new Float32Array(s,n,U.SectionHeaderSizeBytes/4);i[0]=e.splatCount,i[1]=e.maxSplatCount,i[2]=t>=1?e.bucketSize:0,i[3]=t>=1?e.bucketCount:0,o[4]=t>=1?e.bucketBlockSize:0,r[10]=t>=1?U.BucketStorageSizeBytes:0,i[6]=t>=1?e.compressionScaleRange:0,i[7]=e.storageSizeBytes,i[8]=t>=1?e.fullBucketCount:0,i[9]=t>=1?e.partiallyFilledBucketCount:0,r[20]=e.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(e,t,s=0){new Uint32Array(t,s,U.SectionHeaderSizeBytes/4)[0]=e}constructFromBuffer(t,s){this.bufferData=t,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const n=U.parseHeader(this.bufferData);this.versionMajor=n.versionMajor,this.versionMinor=n.versionMinor,this.maxSectionCount=n.maxSectionCount,this.sectionCount=s?n.maxSectionCount:0,this.maxSplatCount=n.maxSplatCount,this.splatCount=s?n.maxSplatCount:0,this.compressionLevel=n.compressionLevel,this.sceneCenter=(new e.Vector3).copy(n.sceneCenter),this.minSphericalHarmonicsCoeff=n.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=n.maxSphericalHarmonicsCoeff,this.sections=U.parseSectionHeaders(n,this.bufferData,U.HeaderSizeBytes,s),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,t){const s=U.CompressionLevels[e].BytesPerCenter,n=U.CompressionLevels[e].BytesPerScale,r=U.CompressionLevels[e].BytesPerRotation,i=U.CompressionLevels[e].BytesPerColor,o=C(t),a=U.CompressionLevels[e].BytesPerSphericalHarmonicsComponent*o;return{bytesPerCenter:s,bytesPerScale:n,bytesPerRotation:r,bytesPerColor:i,sphericalHarmonicsComponentsPerSplat:o,sphericalHarmonicsBytesPerSplat:a,bytesPerSplat:s+n+r+i+a}}linkBufferArrays(){for(let e=0;e<this.maxSectionCount;e++){const t=this.sections[e];t.bucketArray=new Float32Array(this.bufferData,t.bucketsBase,t.bucketCount*U.BucketStorageSizeFloats),t.partiallyFilledBucketCount>0&&(t.partiallyFilledBucketLengths=new Uint32Array(this.bufferData,t.base,t.partiallyFilledBucketCount))}}buildMaps(){let e=0;for(let t=0;t<this.maxSectionCount;t++){const s=this.sections[t];for(let n=0;n<s.maxSplatCount;n++){const s=e+n;this.globalSplatIndexToLocalSplatIndexMap[s]=n,this.globalSplatIndexToSectionMap[s]=t}e+=s.maxSplatCount}}updateLoadedCounts(e,t){U.writeHeaderCountsToBuffer(e,t,this.bufferData),this.sectionCount=e,this.splatCount=t}updateSectionLoadedCounts(e,t){const s=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*e;U.writeSectionHeaderSplatCountToBuffer(t,this.bufferData,s),this.sections[e].splatCount=t}static writeSplatDataToSectionBuffer=function(){const t=new ArrayBuffer(12),s=new ArrayBuffer(12),n=new ArrayBuffer(16),r=new ArrayBuffer(4),i=new ArrayBuffer(256),o=new e.Quaternion,a=new e.Vector3,l=new e.Vector3,{X:c,Y:h,Z:d,SCALE0:p,SCALE1:u,SCALE2:m,ROTATION0:f,ROTATION1:g,ROTATION2:S,ROTATION3:y,FDC0:x,FDC1:v,FDC2:I,OPACITY:B,FRC0:b,FRC9:E}=w.OFFSET,M=(e,t,s)=>{const n=2*s+1;return e=Math.round(e*t)+s,A(e,0,n)};return function(e,A,w,R,P,H,k,L,z=-D,_=D){const Q=C(P),V=w,N=V+U.CompressionLevels[R].BytesPerCenter,G=N+U.CompressionLevels[R].BytesPerScale,K=G+U.CompressionLevels[R].BytesPerRotation,q=K+U.CompressionLevels[R].BytesPerColor;if(void 0!==e[f]?(o.set(e[f],e[g],e[S],e[y]),o.normalize()):o.set(1,0,0,0),void 0!==e[p]?a.set(e[p]||0,e[u]||0,e[m]||0):a.set(0,0,0),0===R){const t=new Float32Array(A,V,U.CenterComponentCount),s=new Float32Array(A,G,U.RotationComponentCount),n=new Float32Array(A,N,U.ScaleComponentCount);if(s.set([o.x,o.y,o.z,o.w]),n.set([a.x,a.y,a.z]),t.set([e[c],e[h],e[d]]),P>0){const t=new Float32Array(A,q,Q);if(P>=1){for(let s=0;s<9;s++)t[s]=e[b+s]||0;if(P>=2)for(let s=0;s<15;s++)t[s+9]=e[E+s]||0}}}else{const r=new Uint16Array(t,0,U.CenterComponentCount),p=new Uint16Array(n,0,U.RotationComponentCount),u=new Uint16Array(s,0,U.ScaleComponentCount);if(p.set([T(o.x),T(o.y),T(o.z),T(o.w)]),u.set([T(a.x),T(a.y),T(a.z)]),l.set(e[c],e[h],e[d]).sub(H),l.x=M(l.x,k,L),l.y=M(l.y,k,L),l.z=M(l.z,k,L),r.set([l.x,l.y,l.z]),P>0){const t=1===R?2:1,s=new(1===R?Uint16Array:Uint8Array)(i,0,Q);if(P>=1){for(let t=0;t<9;t++){const n=e[b+t]||0;s[t]=1===R?T(n):F(n,z,_)}const n=9*t;if(O(s.buffer,0,A,q,n),P>=2){for(let t=0;t<15;t++){const n=e[E+t]||0;s[t+9]=1===R?T(n):F(n,z,_)}O(s.buffer,n,A,q+n,15*t)}}}O(r.buffer,0,A,V,6),O(u.buffer,0,A,N,6),O(p.buffer,0,A,G,8)}const W=new Uint8ClampedArray(r,0,4);W.set([e[x]||0,e[v]||0,e[I]||0]),W[3]=e[B]||0,O(W.buffer,0,A,K,4)}}();static generateFromUncompressedSplatArrays(t,s,n,r,i,o,a=[]){let l,c,h=0;for(let e=0;e<t.length;e++){const s=t[e];h=Math.max(s.sphericalHarmonicsDegree,h)}for(let e=0;e<t.length;e++){const s=t[e];for(let e=0;e<s.splats.length;e++){const t=s.splats[e];for(let e=w.OFFSET.FRC0;e<w.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-D,c=c||D;const{bytesPerSplat:d}=U.calculateComponentStorage(n,h),p=U.CompressionLevels[n].ScaleRange,u=[],m=[];let A=0;for(let r=0;r<t.length;r++){const f=t[r],g=new w(h);for(let e=0;e<f.splatCount;e++){const t=f.splats[e];(t[w.OFFSET.OPACITY]||0)>=s&&g.addSplat(t)}const S=a[r]||{},C=(S.blockSizeFactor||1)*(i||U.BucketBlockSize),y=Math.ceil((S.bucketSizeFactor||1)*(o||U.BucketSize)),x=U.computeBucketsForUncompressedSplatArray(g,C,y),v=x.fullBuckets.length,I=x.partiallyFullBuckets.map((e=>e.splats.length)),B=I.length,b=[...x.fullBuckets,...x.partiallyFullBuckets],D=g.splats.length*d,T=4*B,E=n>=1?b.length*U.BucketStorageSizeBytes+T:0,M=D+E,F=new ArrayBuffer(M),R=p/(.5*C),P=new e.Vector3;let H=0;for(let e=0;e<b.length;e++){const t=b[e];P.fromArray(t.center);for(let e=0;e<t.splats.length;e++){let s=t.splats[e];const r=g.splats[s],i=E+H*d;U.writeSplatDataToSectionBuffer(r,F,i,n,h,P,R,p,l,c),H++}}if(A+=H,n>=1){const e=new Uint32Array(F,0,4*I.length);for(let t=0;t<I.length;t++)e[t]=I[t];const t=new Float32Array(F,T,b.length*U.BucketStorageSizeFloats);for(let e=0;e<b.length;e++){const s=b[e],n=3*e;t[n]=s.center[0],t[n+1]=s.center[1],t[n+2]=s.center[2]}}u.push(F);const k=new ArrayBuffer(U.SectionHeaderSizeBytes);U.writeSectionHeaderToBuffer({maxSplatCount:H,splatCount:H,bucketSize:y,bucketCount:b.length,bucketBlockSize:C,compressionScaleRange:p,storageSizeBytes:M,fullBucketCount:v,partiallyFilledBucketCount:B,sphericalHarmonicsDegree:h},n,k,0),m.push(k)}let f=0;for(let e of u)f+=e.byteLength;const g=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*u.length+f,S=new ArrayBuffer(g);U.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:u.length,sectionCount:u.length,maxSplatCount:A,splatCount:A,compressionLevel:n,sceneCenter:r,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},S);let C=U.HeaderSizeBytes;for(let e of m)new Uint8Array(S,C,U.SectionHeaderSizeBytes).set(new Uint8Array(e)),C+=U.SectionHeaderSizeBytes;for(let e of u)new Uint8Array(S,C,e.byteLength).set(new Uint8Array(e)),C+=e.byteLength;return new U(S)}static computeBucketsForUncompressedSplatArray(t,s,n){let r=t.splatCount;const i=s/2,o=new e.Vector3,a=new e.Vector3;for(let e=0;e<r;e++){const s=t.splats[e],n=[s[w.OFFSET.X],s[w.OFFSET.Y],s[w.OFFSET.Z]];(0===e||n[0]<o.x)&&(o.x=n[0]),(0===e||n[0]>a.x)&&(a.x=n[0]),(0===e||n[1]<o.y)&&(o.y=n[1]),(0===e||n[1]>a.y)&&(a.y=n[1]),(0===e||n[2]<o.z)&&(o.z=n[2]),(0===e||n[2]>a.z)&&(a.z=n[2])}const l=(new e.Vector3).copy(a).sub(o),c=Math.ceil(l.y/s),h=Math.ceil(l.z/s),d=new e.Vector3,p=[],u={};for(let e=0;e<r;e++){const r=t.splats[e],a=[r[w.OFFSET.X],r[w.OFFSET.Y],r[w.OFFSET.Z]],l=Math.floor((a[0]-o.x)/s),m=Math.floor((a[1]-o.y)/s),A=Math.floor((a[2]-o.z)/s);d.x=l*s+o.x+i,d.y=m*s+o.y+i,d.z=A*s+o.z+i;const f=l*(c*h)+m*h+A;let g=u[f];g||(u[f]=g={splats:[],center:d.toArray()}),g.splats.push(e),g.splats.length>=n&&(p.push(g),u[f]=null)}const m=[];for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];t&&m.push(t)}return{fullBuckets:p,partiallyFullBuckets:m}}static preallocateUncompressed(t,s){const n=U.CompressionLevels[0].SphericalHarmonicsDegrees[s],r=U.HeaderSizeBytes+U.SectionHeaderSizeBytes,i=r+n.BytesPerSplat*t,o=new ArrayBuffer(i);return U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:t,splatCount:t,compressionLevel:0,sceneCenter:new e.Vector3},o),U.writeSectionHeaderToBuffer({maxSplatCount:t,splatCount:t,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:s},0,o,U.HeaderSizeBytes),{splatBuffer:new U(o,!0),splatBufferDataOffsetBytes:r}}}const z=new Uint8Array([112,108,121,10]),_=new Uint8Array([10,101,110,100,95,104,101,97,100,101,114,10]),Q="end_header",V=new Map([["char",Int8Array],["uchar",Uint8Array],["short",Int16Array],["ushort",Uint16Array],["int",Int32Array],["uint",Uint32Array],["float",Float32Array],["double",Float64Array]]),N=(e,t)=>{const s=(1<<t)-1;return(e&s)/s},G=(e,t)=>{e.x=N(t>>>21,11),e.y=N(t>>>11,10),e.z=N(t,11)},K=(e,t,s)=>e*(1-s)+t*s,q=(e,t)=>e.properties.find((e=>e.name===t&&e.storage))?.storage;class W{static decodeHeaderText(e){let t,s,n,r;const i=e.split("\n").filter((e=>!e.startsWith("comment ")));let o=0,a=!1;for(let e=1;e<i.length;++e){const l=i[e].split(" ");switch(l[0]){case"format":if("binary_little_endian"!==l[1])throw new Error("Unsupported ply format");break;case"element":t={name:l[1],count:parseInt(l[2],10),properties:[],storageSizeBytes:0},"chunk"===t.name?s=t:"vertex"===t.name?n=t:"sh"===t.name&&(r=t);break;case"property":{if(!V.has(l[1]))throw new Error(`Unrecognized property data type '${l[1]}' in ply header`);const e=V.get(l[1]),s=e.BYTES_PER_ELEMENT*t.count;"vertex"===t.name&&(o+=e.BYTES_PER_ELEMENT),t.properties.push({type:l[1],name:l[2],storage:null,byteSize:e.BYTES_PER_ELEMENT,storageSizeByes:s}),t.storageSizeBytes+=s;break}case Q:a=!0;break;default:throw new Error(`Unrecognized header value '${l[0]}' in ply header`)}if(a)break}let l=0,c=0;return r&&(c=r.properties.length,r.properties.length>=45?l=3:r.properties.length>=24?l=2:r.properties.length>=9&&(l=1)),{chunkElement:s,vertexElement:n,shElement:r,bytesPerSplat:o,headerSizeBytes:e.indexOf(Q)+10+1,sphericalHarmonicsDegree:l,sphericalHarmonicsPerSplat:c}}static decodeHeader(e){let t,s=new Uint8Array(e);if(s.length>=z.length&&!((e,t)=>{if(e.length<t.length)return!1;for(let s=0;s<t.length;++s)if(e[s]!==t[s])return!1;return!0})(s,z))throw new Error("Invalid PLY header");if(t=((e,t)=>{const s=e.length-t.length;let n,r;for(n=0;n<=s;++n){for(r=0;r<t.length&&e[n+r]===t[r];++r);if(r===t.length)return n}return-1})(s,_),-1===t)throw new Error("End of PLY header not found");const n=new TextDecoder("ascii").decode(s.slice(0,t)),{chunkElement:r,vertexElement:i,shElement:o,sphericalHarmonicsDegree:a,sphericalHarmonicsPerSplat:l,bytesPerSplat:c}=W.decodeHeaderText(n);return{headerSizeBytes:t+_.length,bytesPerSplat:c,chunkElement:r,vertexElement:i,shElement:o,sphericalHarmonicsDegree:a,sphericalHarmonicsPerSplat:l}}static readElementData(e,t,s,n,r,i=null){let o=t instanceof DataView?t:new DataView(t);n=n||0,r=r||e.count-1;for(let t=n;t<=r;++t)for(let n=0;n<e.properties.length;++n){const r=e.properties[n],a=V.get(r.type),l=a.BYTES_PER_ELEMENT*e.count;if(r.storage&&!(r.storage.byteLength<l)||i&&!i(r.name)||(r.storage=new a(e.count)),r.storage)switch(r.type){case"char":r.storage[t]=o.getInt8(s);break;case"uchar":r.storage[t]=o.getUint8(s);break;case"short":r.storage[t]=o.getInt16(s,!0);break;case"ushort":r.storage[t]=o.getUint16(s,!0);break;case"int":r.storage[t]=o.getInt32(s,!0);break;case"uint":r.storage[t]=o.getUint32(s,!0);break;case"float":r.storage[t]=o.getFloat32(s,!0);break;case"double":r.storage[t]=o.getFloat64(s,!0)}s+=r.byteSize}return s}static readPly(e,t=null){const s=W.decodeHeader(e);let n=W.readElementData(s.chunkElement,e,s.headerSizeBytes,null,null,t);return n=W.readElementData(s.vertexElement,e,n,null,null,t),W.readElementData(s.shElement,e,n,null,null,t),{chunkElement:s.chunkElement,vertexElement:s.vertexElement,shElement:s.shElement,sphericalHarmonicsDegree:s.sphericalHarmonicsDegree,sphericalHarmonicsPerSplat:s.sphericalHarmonicsPerSplat}}static getElementStorageArrays(e,t,s){const n={};if(t){const s=q(e,"min_r"),r=q(e,"min_g"),i=q(e,"min_b"),o=q(e,"max_r"),a=q(e,"max_g"),l=q(e,"max_b"),c=q(e,"min_x"),h=q(e,"min_y"),d=q(e,"min_z"),p=q(e,"max_x"),u=q(e,"max_y"),m=q(e,"max_z"),A=q(e,"min_scale_x"),f=q(e,"min_scale_y"),g=q(e,"min_scale_z"),S=q(e,"max_scale_x"),C=q(e,"max_scale_y"),y=q(e,"max_scale_z"),x=q(t,"packed_position"),v=q(t,"packed_rotation"),I=q(t,"packed_scale"),B=q(t,"packed_color");n.colorExtremes={minR:s,maxR:o,minG:r,maxG:a,minB:i,maxB:l},n.positionExtremes={minX:c,maxX:p,minY:h,maxY:u,minZ:d,maxZ:m},n.scaleExtremes={minScaleX:A,maxScaleX:S,minScaleY:f,maxScaleY:C,minScaleZ:g,maxScaleZ:y},n.position=x,n.rotation=v,n.scale=I,n.color=B}if(s){const e={};for(let t=0;t<45;t++){const n=`f_rest_${t}`,r=q(s,n);if(!r)break;e[n]=r}n.sh=e}return n}static decompressBaseSplat=function(){const t=new e.Vector3,s=new e.Quaternion,n=new e.Vector3,r=new e.Vector4,i=w.OFFSET;return function(e,o,a,l,c,h,d,p,u,m){m=m||w.createSplat();const f=Math.floor((o+e)/256);var g,S;return G(t,a[e]),((e,t)=>{const s=1/(.5*Math.sqrt(2)),n=(N(t>>>20,10)-.5)*s,r=(N(t>>>10,10)-.5)*s,i=(N(t,10)-.5)*s,o=Math.sqrt(1-(n*n+r*r+i*i));switch(t>>>30){case 0:e.set(o,n,r,i);break;case 1:e.set(n,o,r,i);break;case 2:e.set(n,r,o,i);break;case 3:e.set(n,r,i,o)}})(s,d[e]),G(n,c[e]),g=r,S=u[e],g.x=N(S>>>24,8),g.y=N(S>>>16,8),g.z=N(S>>>8,8),g.w=N(S,8),m[i.X]=K(l.minX[f],l.maxX[f],t.x),m[i.Y]=K(l.minY[f],l.maxY[f],t.y),m[i.Z]=K(l.minZ[f],l.maxZ[f],t.z),m[i.ROTATION0]=s.x,m[i.ROTATION1]=s.y,m[i.ROTATION2]=s.z,m[i.ROTATION3]=s.w,m[i.SCALE0]=Math.exp(K(h.minScaleX[f],h.maxScaleX[f],n.x)),m[i.SCALE1]=Math.exp(K(h.minScaleY[f],h.maxScaleY[f],n.y)),m[i.SCALE2]=Math.exp(K(h.minScaleZ[f],h.maxScaleZ[f],n.z)),p.minR&&p.maxR?m[i.FDC0]=A(Math.round(255*K(p.minR[f],p.maxR[f],r.x)),0,255):m[i.FDC0]=A(Math.floor(255*r.x),0,255),p.minG&&p.maxG?m[i.FDC1]=A(Math.round(255*K(p.minG[f],p.maxG[f],r.y)),0,255):m[i.FDC1]=A(Math.floor(255*r.y),0,255),p.minB&&p.maxB?m[i.FDC2]=A(Math.round(255*K(p.minB[f],p.maxB[f],r.z)),0,255):m[i.FDC2]=A(Math.floor(255*r.z),0,255),m[i.OPACITY]=A(Math.floor(255*r.w),0,255),m}}();static decompressSphericalHarmonics=function(){const e=[0,3,8,15],t=[0,1,2,9,10,11,12,13,24,25,26,27,28,29,30,3,4,5,14,15,16,17,18,31,32,33,34,35,36,37,6,7,8,19,20,21,22,23,38,39,40,41,42,43,44];return function(s,n,r,i,o){o=o||w.createSplat();let a=e[r],l=e[i];for(let e=0;e<3;++e)for(let r=0;r<15;++r){const i=t[15*e+r];r<a&&r<l&&(o[w.OFFSET.FRC0+i]=n[e*l+r][s]*(8/255)-4)}return o}}();static parseToUncompressedSplatBufferSection(e,t,s,n,r,i,o,a,l=null){W.readElementData(t,i,0,s,n,l);const c=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat,{positionExtremes:h,scaleExtremes:d,colorExtremes:p,position:u,rotation:m,scale:A,color:f}=W.getElementStorageArrays(e,t),g=w.createSplat();for(let e=s;e<=n;++e){W.decompressBaseSplat(e,r,u,h,A,d,m,p,f,g);const t=e*c+a;U.writeSplatDataToSectionBuffer(g,o,t,0,0)}}static parseToUncompressedSplatArraySection(e,t,s,n,r,i,o,a=null){W.readElementData(t,i,0,s,n,a);const{positionExtremes:l,scaleExtremes:c,colorExtremes:h,position:d,rotation:p,scale:u,color:m}=W.getElementStorageArrays(e,t);for(let e=s;e<=n;++e){const t=w.createSplat();W.decompressBaseSplat(e,r,d,l,u,c,p,h,m,t),o.addSplat(t)}}static parseSphericalHarmonicsToUncompressedSplatArraySection(e,t,s,n,r,i,o,a,l,c=null){W.readElementData(t,r,i,s,n,c);const{sh:h}=W.getElementStorageArrays(e,void 0,t),d=Object.values(h);for(let e=s;e<=n;++e)W.decompressSphericalHarmonics(e,d,o,a,l.splats[e])}static parseToUncompressedSplatArray(e,t){const{chunkElement:s,vertexElement:n,shElement:r,sphericalHarmonicsDegree:i}=W.readPly(e);t=Math.min(t,i);const o=new w(t),{positionExtremes:a,scaleExtremes:l,colorExtremes:c,position:h,rotation:d,scale:p,color:u}=W.getElementStorageArrays(s,n);let m;if(t>0){const{sh:e}=W.getElementStorageArrays(s,void 0,r);m=Object.values(e)}for(let e=0;e<n.count;++e){o.addDefaultSplat();const s=o.getSplat(o.splatCount-1);W.decompressBaseSplat(e,0,h,a,p,l,d,c,u,s),t>0&&W.decompressSphericalHarmonics(e,m,t,i,s)}return o}static parseToUncompressedSplatBuffer(e,t){const{chunkElement:s,vertexElement:n,shElement:r,sphericalHarmonicsDegree:i}=W.readPly(e);t=Math.min(t,i);const{splatBuffer:o,splatBufferDataOffsetBytes:a}=U.preallocateUncompressed(n.count,t),{positionExtremes:l,scaleExtremes:c,colorExtremes:h,position:d,rotation:p,scale:u,color:m}=W.getElementStorageArrays(s,n);let A;if(t>0){const{sh:e}=W.getElementStorageArrays(s,void 0,r);A=Object.values(e)}const f=U.CompressionLevels[0].SphericalHarmonicsDegrees[t].BytesPerSplat,g=w.createSplat(t);for(let e=0;e<n.count;++e){W.decompressBaseSplat(e,0,d,l,u,c,p,h,m,g),t>0&&W.decompressSphericalHarmonics(e,A,t,i,g);const s=e*f+a;U.writeSplatDataToSectionBuffer(g,o.bufferData,s,0,t)}return o}}const j=0,Y=1,X=2,[J,Z,$,ee,te,se,ne]=[0,1,2,3,4,5,6],re={double:J,int:Z,uint:$,float:ee,short:te,ushort:se,uchar:ne},ie={[J]:8,[Z]:4,[$]:4,[ee]:4,[te]:2,[se]:2,[ne]:1};class oe{static HeaderEndToken="end_header";static decodeSectionHeader(e,t,s=0){const n=[];let r=!1,i=-1,o=0,a=!1,l=null;const c=[],h=[],d=[],p={};for(let u=s;u<e.length;u++){const m=e[u].trim();if(m.startsWith("element")){if(r){i--;break}{r=!0,s=u,i=u;const e=m.split(" ");let t=0;for(let s of e){const e=s.trim();e.length>0&&(t++,2===t?l=e:3===t&&(o=parseInt(e)))}}}else if(m.startsWith("property")){const e=m.match(/(\w+)\s+(\w+)\s+(\w+)/);if(e){const s=e[2],n=e[3];d.push(n);const r=t[n];p[n]=s;const i=re[s];void 0!==r&&(c.push(r),h[r]=i)}}if(m===oe.HeaderEndToken){a=!0;break}r&&(n.push(m),i++)}const u=[];let m=0;for(let e of d){const s=p[e];if(p.hasOwnProperty(e)){const s=t[e];void 0!==s&&(u[s]=m)}m+=ie[re[s]]}const A=oe.decodeSphericalHarmonicsFromSectionHeader(d,t);return{headerLines:n,headerStartLine:s,headerEndLine:i,fieldTypes:h,fieldIds:c,fieldOffsets:u,bytesPerVertex:m,vertexCount:o,dataSizeBytes:m*o,endOfHeader:a,sectionName:l,sphericalHarmonicsDegree:A.degree,sphericalHarmonicsCoefficientsPerChannel:A.coefficientsPerChannel,sphericalHarmonicsDegree1Fields:A.degree1Fields,sphericalHarmonicsDegree2Fields:A.degree2Fields}}static decodeSphericalHarmonicsFromSectionHeader(e,t){let s=0,n=0;for(let t of e)t.startsWith("f_rest")&&s++;n=s/3;let r=0;n>=3&&(r=1),n>=8&&(r=2);let i=[],o=[];for(let e=0;e<3;e++){if(r>=1)for(let s=0;s<3;s++)i.push(t["f_rest_"+(s+n*e)]);if(r>=2)for(let s=0;s<5;s++)o.push(t["f_rest_"+(s+n*e+3)])}return{degree:r,coefficientsPerChannel:n,degree1Fields:i,degree2Fields:o}}static getHeaderSectionNames(e){const t=[];for(let s of e)if(s.startsWith("element")){const e=s.split(" ");let n=0;for(let s of e){const e=s.trim();e.length>0&&(n++,2===n&&t.push(e))}}return t}static checkTextForEndHeader(e){return!!e.includes(oe.HeaderEndToken)}static checkBufferForEndHeader(e,t,s,n){const r=new Uint8Array(e,Math.max(0,t-s),s),i=n.decode(r);return oe.checkTextForEndHeader(i)}static extractHeaderFromBufferToText(e){const t=new TextDecoder;let s=0,n="";const r=100;for(;;){if(s+r>=e.byteLength)throw new Error("End of file reached while searching for end of header");const i=new Uint8Array(e,s,r);if(n+=t.decode(i),s+=r,oe.checkBufferForEndHeader(e,s,200,t))break}return n}static readHeaderFromBuffer(e){const t=new TextDecoder;let s=0,n="";const r=100;for(;;){if(s+r>=e.byteLength)throw new Error("End of file reached while searching for end of header");const i=new Uint8Array(e,s,r);if(n+=t.decode(i),s+=r,oe.checkBufferForEndHeader(e,s,200,t))break}return n}static convertHeaderTextToLines(e){const t=e.split("\n"),s=[];for(let e=0;e<t.length;e++){const n=t[e].trim();if(s.push(n),n===oe.HeaderEndToken)break}return s}static determineHeaderFormatFromHeaderText(e){const t=oe.convertHeaderTextToLines(e);let s=j;for(let e=0;e<t.length;e++){const n=t[e].trim();if(n.startsWith("element chunk")||n.match(/[A-Za-z]*packed_[A-Za-z]*/))s=X;else if(n.startsWith("element codebook_centers"))s=Y;else if(n===oe.HeaderEndToken)break}return s}static determineHeaderFormatFromPlyBuffer(e){const t=oe.extractHeaderFromBufferToText(e);return oe.determineHeaderFormatFromHeaderText(t)}static readVertex(e,t,s,n,r,i,o=!0){const a=s*t.bytesPerVertex+n,l=t.fieldOffsets,c=t.fieldTypes;for(let t of r){const s=c[t];s===ee?i[t]=e.getFloat32(a+l[t],!0):s===te?i[t]=e.getInt16(a+l[t],!0):s===se?i[t]=e.getUint16(a+l[t],!0):s===Z?i[t]=e.getInt32(a+l[t],!0):s===$?i[t]=e.getUint32(a+l[t],!0):s===ne&&(i[t]=o?e.getUint8(a+l[t])/255:e.getUint8(a+l[t]))}}}const ae=["scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","red","green","blue","f_rest_0"],le=ae.map(((e,t)=>t)),[ce,he,de,pe,ue,me,Ae,fe,ge,Se,Ce,ye,xe,ve,Ie,Be,we,be]=le;class De{static decodeHeaderLines(e){let t=0;e.forEach((e=>{e.includes("f_rest_")&&t++}));let s=0;t>=45?s=45:t>=24?s=24:t>=9&&(s=9);let n=Array.from(Array(Math.max(s-1,0))).map(((e,t)=>`f_rest_${t+1}`));const r=[...ae,...n],i=r.map(((e,t)=>t)),o=i.reduce(((e,t)=>(e[r[t]]=t,e)),{}),a=oe.decodeSectionHeader(e,o,0);return a.splatCount=a.vertexCount,a.bytesPerSplat=a.bytesPerVertex,a.fieldsToReadIndexes=i,a}static decodeHeaderText(e){const t=oe.convertHeaderTextToLines(e),s=De.decodeHeaderLines(t);return s.headerText=e,s.headerSizeBytes=e.indexOf(oe.HeaderEndToken)+oe.HeaderEndToken.length+1,s}static decodeHeaderFromBuffer(e){const t=oe.readHeaderFromBuffer(e);return De.decodeHeaderText(t)}static findSplatData(e,t){return new DataView(e,t.headerSizeBytes)}static parseToUncompressedSplatBufferSection(e,t,s,n,r,i,o,a=0){a=Math.min(a,e.sphericalHarmonicsDegree);const l=U.CompressionLevels[0].SphericalHarmonicsDegrees[a].BytesPerSplat;for(let c=t;c<=s;c++){const t=De.parseToUncompressedSplat(n,c,e,r,a),s=c*l+o;U.writeSplatDataToSectionBuffer(t,i,s,0,a)}}static parseToUncompressedSplatArraySection(e,t,s,n,r,i,o=0){o=Math.min(o,e.sphericalHarmonicsDegree);for(let a=t;a<=s;a++){const t=De.parseToUncompressedSplat(n,a,e,r,o);i.addSplat(t)}}static decodeSectionSplatData(e,t,s,n,r=!0){if(n=Math.min(n,s.sphericalHarmonicsDegree),r){const r=new w(n);for(let i=0;i<t;i++){const t=De.parseToUncompressedSplat(e,i,s,0,n);r.addSplat(t)}return r}{const{splatBuffer:r,splatBufferDataOffsetBytes:i}=U.preallocateUncompressed(t,n);return De.parseToUncompressedSplatBufferSection(s,0,t-1,e,0,r.bufferData,i,n),r}}static parseToUncompressedSplat=function(){let t=[];const s=new e.Quaternion,n=w.OFFSET.X,r=w.OFFSET.Y,i=w.OFFSET.Z,o=w.OFFSET.SCALE0,a=w.OFFSET.SCALE1,l=w.OFFSET.SCALE2,c=w.OFFSET.ROTATION0,h=w.OFFSET.ROTATION1,d=w.OFFSET.ROTATION2,p=w.OFFSET.ROTATION3,u=w.OFFSET.FDC0,m=w.OFFSET.FDC1,f=w.OFFSET.FDC2,g=w.OFFSET.OPACITY,S=[];for(let e=0;e<45;e++)S[e]=w.OFFSET.FRC0+e;return function(e,C,y,x=0,v=0){v=Math.min(v,y.sphericalHarmonicsDegree),De.readSplat(e,y,C,x,t);const I=w.createSplat(v);if(void 0!==t[ce]?(I[o]=Math.exp(t[ce]),I[a]=Math.exp(t[he]),I[l]=Math.exp(t[de])):(I[o]=.01,I[a]=.01,I[l]=.01),void 0!==t[Ce]){const e=.28209479177387814;I[u]=255*(.5+e*t[Ce]),I[m]=255*(.5+e*t[ye]),I[f]=255*(.5+e*t[xe])}else void 0!==t[Ie]?(I[u]=255*t[Ie],I[m]=255*t[Be],I[f]=255*t[we]):(I[u]=0,I[m]=0,I[f]=0);if(void 0!==t[ve]&&(I[g]=1/(1+Math.exp(-t[ve]))*255),I[u]=A(Math.floor(I[u]),0,255),I[m]=A(Math.floor(I[m]),0,255),I[f]=A(Math.floor(I[f]),0,255),I[g]=A(Math.floor(I[g]),0,255),v>=1&&void 0!==t[be]){for(let e=0;e<9;e++)I[S[e]]=t[y.sphericalHarmonicsDegree1Fields[e]];if(v>=2)for(let e=0;e<15;e++)I[S[9+e]]=t[y.sphericalHarmonicsDegree2Fields[e]]}return s.set(t[pe],t[ue],t[me],t[Ae]),s.normalize(),I[c]=s.x,I[h]=s.y,I[d]=s.z,I[p]=s.w,I[n]=t[fe],I[r]=t[ge],I[i]=t[Se],I}}();static readSplat(e,t,s,n,r){return oe.readVertex(e,t,s,n,t.fieldsToReadIndexes,r,!0)}static parseToUncompressedSplatArray(e,t=0){const{header:s,splatCount:n,splatData:r}=Te(e);return De.decodeSectionSplatData(r,n,s,t,!0)}static parseToUncompressedSplatBuffer(e,t=0){const{header:s,splatCount:n,splatData:r}=Te(e);return De.decodeSectionSplatData(r,n,s,t,!1)}}function Te(e){const t=De.decodeHeaderFromBuffer(e);return{header:t,splatCount:t.splatCount,splatData:De.findSplatData(e,t)}}const Ee=["features_dc","features_rest_0","features_rest_1","features_rest_2","features_rest_3","features_rest_4","features_rest_5","features_rest_6","features_rest_7","features_rest_8","features_rest_9","features_rest_10","features_rest_11","features_rest_12","features_rest_13","features_rest_14","opacity","scaling","rotation_re","rotation_im"],Me=Ee.map(((e,t)=>t)),[Fe,Re,Pe,He,ke,Le,Oe]=[0,1,4,16,17,18,19],Ue=["scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","red","green","blue","f_rest_0","f_rest_1","f_rest_2","f_rest_3","f_rest_4","f_rest_5","f_rest_6","f_rest_7","f_rest_8","f_rest_9","f_rest_10","f_rest_11","f_rest_12","f_rest_13","f_rest_14","f_rest_15","f_rest_16","f_rest_17","f_rest_18","f_rest_19","f_rest_20","f_rest_21","f_rest_22","f_rest_23","f_rest_24","f_rest_25","f_rest_26","f_rest_27","f_rest_28","f_rest_29","f_rest_30","f_rest_31","f_rest_32","f_rest_33","f_rest_34","f_rest_35","f_rest_36","f_rest_37","f_rest_38","f_rest_39","f_rest_40","f_rest_41","f_rest_42","f_rest_43","f_rest_44","f_rest_45"],ze=Ue.map(((e,t)=>t)),[_e,Qe,Ve,Ne,Ge,Ke,qe,We,je,Ye,Xe,Je,Ze,$e]=ze,et=Xe,tt=Je,st=Ze,nt=e=>{const t=(31744&e)>>10,s=1023&e;return(e>>15?-1:1)*(t?31===t?s?NaN:1/0:Math.pow(2,t-15)*(1+s/1024):s/1024*6103515625e-14)};class rt{static decodeSectionHeadersFromHeaderLines(e){const t=ze.reduce(((e,t)=>(e[Ue[t]]=t,e)),{}),s=Me.reduce(((e,t)=>(e[Ee[t]]=t,e)),{}),n=oe.getHeaderSectionNames(e);let r;for(let e=0;e<n.length;e++){"codebook_centers"===n[e]&&(r=e)}let i=0,o=!1;const a=[];let l=0;for(;!o;){let n;n=l===r?oe.decodeSectionHeader(e,s,i):oe.decodeSectionHeader(e,t,i),o=n.endOfHeader,i=n.headerEndLine+1,o||(n.splatCount=n.vertexCount,n.bytesPerSplat=n.bytesPerVertex),a.push(n),l++}return a}static decodeSectionHeadersFromHeaderText(e){const t=oe.convertHeaderTextToLines(e);return rt.decodeSectionHeadersFromHeaderLines(t)}static getSplatCountFromSectionHeaders(e){let t=0;for(let s of e)"codebook_centers"!==s.sectionName&&(t+=s.vertexCount);return t}static decodeHeaderFromHeaderText(e){const t=e.indexOf(oe.HeaderEndToken)+oe.HeaderEndToken.length+1,s=rt.decodeSectionHeadersFromHeaderText(e);return{headerSizeBytes:t,sectionHeaders:s,splatCount:rt.getSplatCountFromSectionHeaders(s)}}static decodeHeaderFromBuffer(e){const t=oe.readHeaderFromBuffer(e);return rt.decodeHeaderFromHeaderText(t)}static findVertexData(e,t,s){let n=t.headerSizeBytes;for(let e=0;e<s&&e<t.sectionHeaders.length;e++){n+=t.sectionHeaders[e].dataSizeBytes}return new DataView(e,n,t.sectionHeaders[s].dataSizeBytes)}static decodeCodeBook(e,t){const s=[],n=[];for(let r=0;r<t.vertexCount;r++){oe.readVertex(e,t,r,0,Me,s);for(let e of Me){const t=Me[e];let r=n[t];r||(n[t]=r=[]),r.push(s[e])}}for(let e=0;e<n.length;e++){const t=n[e],s=.28209479177387814;for(let n=0;n<t.length;n++){const r=nt(t[n]);t[n]=e===He?Math.round(1/(1+Math.exp(-r))*255):e===Fe?Math.round(255*(.5+s*r)):e===ke?Math.exp(r):r}}return n}static decodeSectionSplatData(e,t,s,n,r){r=Math.min(r,s.sphericalHarmonicsDegree);const i=new w(r);for(let o=0;o<t;o++){const t=rt.parseToUncompressedSplat(e,o,s,n,0,r);i.addSplat(t)}return i}static parseToUncompressedSplat=function(){let t=[];const s=new e.Quaternion,n=w.OFFSET.X,r=w.OFFSET.Y,i=w.OFFSET.Z,o=w.OFFSET.SCALE0,a=w.OFFSET.SCALE1,l=w.OFFSET.SCALE2,c=w.OFFSET.ROTATION0,h=w.OFFSET.ROTATION1,d=w.OFFSET.ROTATION2,p=w.OFFSET.ROTATION3,u=w.OFFSET.FDC0,m=w.OFFSET.FDC1,f=w.OFFSET.FDC2,g=w.OFFSET.OPACITY,S=[];for(let e=0;e<45;e++)S[e]=w.OFFSET.FRC0+e;return function(e,C,y,x,v=0,I=0){I=Math.min(I,y.sphericalHarmonicsDegree),rt.readSplat(e,y,C,v,t);const B=w.createSplat(I);if(void 0!==t[_e]?(B[o]=x[ke][t[_e]],B[a]=x[ke][t[Qe]],B[l]=x[ke][t[Ve]]):(B[o]=.01,B[a]=.01,B[l]=.01),void 0!==t[Xe]?(B[u]=x[Fe][t[Xe]],B[m]=x[Fe][t[Je]],B[f]=x[Fe][t[Ze]]):void 0!==t[et]?(B[u]=255*t[et],B[m]=255*t[tt],B[f]=255*t[st]):(B[u]=0,B[m]=0,B[f]=0),void 0!==t[$e]&&(B[g]=x[He][t[$e]]),B[u]=A(Math.floor(B[u]),0,255),B[m]=A(Math.floor(B[m]),0,255),B[f]=A(Math.floor(B[f]),0,255),B[g]=A(Math.floor(B[g]),0,255),I>=1&&y.sphericalHarmonicsDegree>=1){for(let e=0;e<9;e++){const s=x[Re+e%3];B[S[e]]=s[t[y.sphericalHarmonicsDegree1Fields[e]]]}if(I>=2&&y.sphericalHarmonicsDegree>=2)for(let e=0;e<15;e++){const s=x[Pe+e%5];B[S[9+e]]=s[t[y.sphericalHarmonicsDegree2Fields[e]]]}}const b=x[Le][t[Ne]],D=x[Oe][t[Ge]],T=x[Oe][t[Ke]],E=x[Oe][t[qe]];return s.set(b,D,T,E),s.normalize(),B[c]=s.x,B[h]=s.y,B[d]=s.z,B[p]=s.w,B[n]=nt(t[We]),B[r]=nt(t[je]),B[i]=nt(t[Ye]),B}}();static readSplat(e,t,s,n,r){return oe.readVertex(e,t,s,n,ze,r,!1)}static parseToUncompressedSplatArray(e,t=0){const s=[],n=rt.decodeHeaderFromBuffer(e,t);let r;for(let t=0;t<n.sectionHeaders.length;t++){const s=n.sectionHeaders[t];if("codebook_centers"===s.sectionName){const i=rt.findVertexData(e,n,t);r=rt.decodeCodeBook(i,s)}}for(let i=0;i<n.sectionHeaders.length;i++){const o=n.sectionHeaders[i];if("codebook_centers"!==o.sectionName){const a=o.vertexCount,l=rt.findVertexData(e,n,i),c=rt.decodeSectionSplatData(l,a,o,r,t);s.push(c)}}const i=new w(t);for(let e of s)for(let t of e.splats)i.addSplat(t);return i}}class it{static parseToUncompressedSplatArray(e,t=0){const s=oe.determineHeaderFormatFromPlyBuffer(e);return s===X?W.parseToUncompressedSplatArray(e,t):s===j?De.parseToUncompressedSplatArray(e,t):s===Y?rt.parseToUncompressedSplatArray(e,t):void 0}static parseToUncompressedSplatBuffer(e,t=0){const s=oe.determineHeaderFormatFromPlyBuffer(e);if(s===X)return W.parseToUncompressedSplatBuffer(e,t);if(s===j)return De.parseToUncompressedSplatBuffer(e,t);if(s===Y)throw new Error("parseToUncompressedSplatBuffer() is not implemented for INRIA V2 PLY files")}}class ot{constructor(e,t,s,n){this.sectionCount=e,this.sectionFilters=t,this.groupingParameters=s,this.partitionGenerator=n}partitionUncompressedSplatArray(e){let t,s,n;if(this.partitionGenerator){const r=this.partitionGenerator(e);t=r.groupingParameters,s=r.sectionCount,n=r.sectionFilters}else t=this.groupingParameters,s=this.sectionCount,n=this.sectionFilters;const r=[];for(let t=0;t<s;t++){const s=new w(e.sphericalHarmonicsDegree),i=n[t];for(let t=0;t<e.splatCount;t++)i(t)&&s.addSplat(e.splats[t]);r.push(s)}return{splatArrays:r,parameters:t}}static getStandardPartitioner(t=0,s=new e.Vector3,n=U.BucketBlockSize,r=U.BucketSize){return new ot(void 0,void 0,void 0,(i=>{const o=w.OFFSET.X,a=w.OFFSET.Y,l=w.OFFSET.Z;t<=0&&(t=i.splatCount);const c=new e.Vector3,h=.5;i.splats.forEach((e=>{var t;c.set(e[o],e[a],e[l]).sub(s),(t=c).x=Math.floor(t.x/h)*h,t.y=Math.floor(t.y/h)*h,t.z=Math.floor(t.z/h)*h,e.centerDist=c.lengthSq()})),i.splats.sort(((e,t)=>e.centerDist>t.centerDist?1:-1));const d=[],p=[];t=Math.min(i.splatCount,t);const u=Math.ceil(i.splatCount/t);let m=0;for(let e=0;e<u;e++){let e=m;d.push((s=>s>=e&&s<e+t)),p.push({blocksSize:n,bucketSize:r}),m+=t}return{sectionCount:d.length,sectionFilters:d,groupingParameters:p}}))}}class at{constructor(t,s,n,r,i,o,a){this.splatPartitioner=t,this.alphaRemovalThreshold=s,this.compressionLevel=n,this.sectionSize=r,this.sceneCenter=i?(new e.Vector3).copy(i):void 0,this.blockSize=o,this.bucketSize=a}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return U.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(t=1,s=1,n=0,r=new e.Vector3,i=U.BucketBlockSize,o=U.BucketSize){const a=ot.getStandardPartitioner(n,r,i,o);return new at(a,t,s,n,r,i,o)}}const lt=0,ct=1,ht=2;class dt extends Error{constructor(e){super(e)}}const pt=0,ut=1,mt=2;function At(e,t){let s=0;for(let t of e)s+=t.sizeBytes;(!t||t.byteLength<s)&&(t=new ArrayBuffer(s));let n=0;for(let s of e)new Uint8Array(t,n,s.sizeBytes).set(s.data),n+=s.sizeBytes;return t}function ft(t,s,n,r,i,o,a,l){if(s){return at.getStandardGenerator(n,r,i,o,a,l).generateFromUncompressedSplatArray(t)}return U.generateFromUncompressedSplatArrays([t],n,0,new e.Vector3)}class gt{static loadFromURL(t,s,n,r,i,o,a=!0,l=0,c,h,d,p,u){let A;A=n||a?a?ut:pt:mt;const f=b.ProgressiveLoadSectionSize,g=U.HeaderSizeBytes+U.SectionHeaderSizeBytes;let C,x,v,I,B,D=0,T=0,E=0,M=!1,F=!1,R=!1;const P=y();let H,k=0,L=0,O=0,z=0,_="",Q=null,V=[];const N=new TextDecoder;return s&&s(0,"0%",lt),m(t,((t,n,i)=>{const o=t>=100;if(i&&(V.push({data:i,sizeBytes:i.byteLength,startBytes:O,endBytes:O+i.byteLength}),O+=i.byteLength),A===mt)o&&P.resolve(V);else{if(M){if(C===X&&!F){const e=Q.headerSizeBytes+Q.chunkElement.storageSizeBytes;B=At(V,B),B.byteLength>=e&&(W.readElementData(Q.chunkElement,B,Q.headerSizeBytes),k=e,L=e,F=!0)}}else if(_+=N.decode(i),oe.checkTextForEndHeader(_)){if(C=oe.determineHeaderFormatFromHeaderText(_),C===j)Q=De.decodeHeaderText(_),l=Math.min(l,Q.sphericalHarmonicsDegree),D=Q.splatCount,F=!0,z=Q.headerSizeBytes+Q.bytesPerSplat*D;else{if(C!==X){if(A===pt)throw new dt("PlyLoader.loadFromURL() -> Selected PLY format cannot be progressively loaded.");return void(A=mt)}if(Q=W.decodeHeaderText(_),l=Math.min(l,Q.sphericalHarmonicsDegree),A===pt&&l>0)throw new dt("PlyLoader.loadFromURL() -> Selected PLY format has spherical harmonics data that cannot be progressively loaded.");D=Q.vertexElement.count,z=Q.headerSizeBytes+Q.bytesPerSplat*D+Q.chunkElement.storageSizeBytes}if(A===pt){const t=U.CompressionLevels[0].SphericalHarmonicsDegrees[l],s=g+t.BytesPerSplat*D;v=new ArrayBuffer(s),U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:D,splatCount:0,compressionLevel:0,sceneCenter:new e.Vector3},v)}else H=new w(l);k=Q.headerSizeBytes,L=Q.headerSizeBytes,M=!0}if(M&&F&&V.length>0){x=At(V,x);if(O-k>f||O>=z&&!R||o){const e=R?Q.sphericalHarmonicsPerSplat:Q.bytesPerSplat,t=(R?O:Math.min(z,O))-L,s=Math.floor(t/e),n=s*e,r=O-L-n,i=L-V[0].startBytes,o=new DataView(x,i,n);if(R)C===X&&A===ut&&(W.parseSphericalHarmonicsToUncompressedSplatArraySection(Q.chunkElement,Q.shElement,E,E+s-1,o,0,l,Q.sphericalHarmonicsDegree,H),E+=s);else{if(A===pt){const e=U.CompressionLevels[0].SphericalHarmonicsDegrees[l],t=T*e.BytesPerSplat+g;C===X?W.parseToUncompressedSplatBufferSection(Q.chunkElement,Q.vertexElement,0,s-1,T,o,v,t):De.parseToUncompressedSplatBufferSection(Q,0,s-1,o,0,v,t,l)}else C===X?W.parseToUncompressedSplatArraySection(Q.chunkElement,Q.vertexElement,0,s-1,T,o,H):De.parseToUncompressedSplatArraySection(Q,0,s-1,o,0,H,l);T+=s,A===pt&&(I||(U.writeSectionHeaderToBuffer({maxSplatCount:D,splatCount:T,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:l},0,v,U.HeaderSizeBytes),I=new U(v,!1)),I.updateLoadedCounts(1,T)),O>=z&&(R=!0)}if(0===r)V=[];else{let e=[],t=0;for(let s=V.length-1;s>=0;s--){const n=V[s];if(t+=n.sizeBytes,e.unshift(n),t>=r)break}V=e}k+=f,L+=n}}r&&I&&r(I,o),o&&(A===pt?P.resolve(I):P.resolve(H))}s&&s(t,n,lt)}),!1,c).then((()=>(s&&s(0,"0%",ct),P.promise.then((e=>{if(s&&s(100,"100%",ht),A===mt){const e=V.map((e=>e.data));return new Blob(e).arrayBuffer().then((e=>gt.loadFromFileData(e,i,o,a,l,h,d,p,u)))}return A===pt?e:S((()=>ft(e,a,i,o,h,d,p,u)))})))))}static loadFromFileData(e,t,s,n,r=0,i,o,a,l){return n?S((()=>it.parseToUncompressedSplatArray(e,r))).then((e=>ft(e,n,t,s,i,o,a,l))):S((()=>it.parseToUncompressedSplatBuffer(e,r)))}}const St=e=>new ReadableStream({async start(t){t.enqueue(e),t.close()}});async function Ct(e){try{const t=St(e);if(!t)throw new Error("Failed to create stream from data");return await async function(e){const t=e.pipeThrough(new DecompressionStream("gzip")),s=new Response(t),n=await s.arrayBuffer();return new Uint8Array(n)}(t)}catch(e){throw console.error("Error decompressing gzipped data:",e),e}}const yt=1347635022,xt=1;function vt(e){const t=e>>10&31,s=1023&e,n=1===(e>>15&1)?-1:1;return 0===t?n*Math.pow(2,-14)*s/1024:31===t?0!==s?NaN:n*(1/0):n*Math.pow(2,t-15)*(1+s/1024)}function It(e){switch(e){case 0:return 0;case 1:return 3;case 2:return 8;case 3:return 15;default:return console.error(`[SPZ: ERROR] Unsupported SH degree: ${e}`),0}}const Bt=function(){let t=[];const s=new e.Quaternion,n=w.OFFSET.X,r=w.OFFSET.Y,i=w.OFFSET.Z,o=w.OFFSET.SCALE0,a=w.OFFSET.SCALE1,l=w.OFFSET.SCALE2,c=w.OFFSET.ROTATION0,h=w.OFFSET.ROTATION1,d=w.OFFSET.ROTATION2,p=w.OFFSET.ROTATION3,u=w.OFFSET.FDC0,m=w.OFFSET.FDC1,f=w.OFFSET.FDC2,g=w.OFFSET.OPACITY,S=[It(0),It(1),It(2),It(3)],C=[0,1,2,9,10,11,12,13,24,25,26,27,28,29,30,3,4,5,14,15,16,17,18,31,32,33,34,35,36,37,6,7,8,19,20,21,22,23,38,39,40,41,42,43,44];return function(e,y,x){x=Math.min(y,x);const v=w.createSplat(x);void 0!==e.scale[0]?(v[o]=e.scale[0],v[a]=e.scale[1],v[l]=e.scale[2]):(v[o]=.01,v[a]=.01,v[l]=.01),void 0!==e.color[0]?(v[u]=e.color[0],v[m]=e.color[1],v[f]=e.color[2]):void 0!==t[RED]?(v[u]=255*t[RED],v[m]=255*t[GREEN],v[f]=255*t[BLUE]):(v[u]=0,v[m]=0,v[f]=0),void 0!==e.alpha&&(v[g]=e.alpha),v[u]=A(Math.floor(v[u]),0,255),v[m]=A(Math.floor(v[m]),0,255),v[f]=A(Math.floor(v[f]),0,255),v[g]=A(Math.floor(v[g]),0,255);let I=S[x],B=S[y];for(let t=0;t<3;++t)for(let s=0;s<15;++s){const n=C[15*t+s];s<I&&s<B&&(v[w.OFFSET.FRC0+n]=e.sh[t*B+s])}return s.set(e.rotation[3],e.rotation[0],e.rotation[1],e.rotation[2]),s.normalize(),v[c]=s.x,v[h]=s.y,v[d]=s.z,v[p]=s.w,v[n]=e.position[0],v[r]=e.position[1],v[i]=e.position[2],v}}();function wt(e,t,s,n,r){t=Math.min(t,e.shDegree);const i=e.numPoints,o=It(e.shDegree),a=e.positions.length===3*i*2;if(!function(e,t,s,n){return e.positions.length===3*t*(n?2:3)&&e.scales.length===3*t&&e.rotations.length===3*t&&e.alphas.length===t&&e.colors.length===3*t&&e.sh.length===t*s*3}(e,i,o,a))return null;const l={position:[],scale:[],rotation:[],alpha:void 0,color:[],sh:[]};let c;a&&(c=new Uint16Array(e.positions.buffer,e.positions.byteOffset,3*i));const h=1/(1<<e.fractionalBits),d=It(e.shDegree);for(let o=0;o<i;o++){if(a)for(let e=0;e<3;e++)l.position[e]=vt(c[3*o+e]);else for(let t=0;t<3;t++){const s=9*o+3*t;let n=e.positions[s];n|=e.positions[s+1]<<8,n|=e.positions[s+2]<<16,n|=8388608&n?4278190080:0,l.position[t]=n*h}for(let t=0;t<3;t++)l.scale[t]=Math.exp(e.scales[3*o+t]/16-10);const i=e.rotations.subarray(3*o,3*o+3),p=[i[0]/127.5-1,i[1]/127.5-1,i[2]/127.5-1];l.rotation[0]=p[0],l.rotation[1]=p[1],l.rotation[2]=p[2];const u=p[0]*p[0]+p[1]*p[1]+p[2]*p[2];l.rotation[3]=Math.sqrt(Math.max(0,1-u)),l.alpha=Math.floor(e.alphas[o]);for(let t=0;t<3;t++)l.color[t]=Math.floor(255*((e.colors[3*o+t]/255-.5)/.15*.28209479177387814+.5));for(let t=0;t<3;t++)for(let s=0;s<d;s++)l.sh[t*d+s]=(e.sh[3*d*o+3*s+t]-128)/128;const m=Bt(l,e.shDegree,t);if(s){const e=o*U.CompressionLevels[0].SphericalHarmonicsDegrees[t].BytesPerSplat+r;U.writeSplatDataToSectionBuffer(m,n,e,0,t)}else n.addSplat(m)}}const bt=16,Dt=1e7;async function Tt(e){try{return function(e){const t=new DataView(e);let s=0;const n={magic:t.getUint32(s,!0),version:t.getUint32(s+4,!0),numPoints:t.getUint32(s+8,!0),shDegree:t.getUint8(s+12),fractionalBits:t.getUint8(s+13),flags:t.getUint8(s+14),reserved:t.getUint8(s+15)};if(s+=bt,n.magic!==yt)return console.error("[SPZ ERROR] deserializePackedGaussians: header not found"),null;if(n.version<1||n.version>2)return console.error(`[SPZ ERROR] deserializePackedGaussians: version not supported: ${n.version}`),null;if(n.numPoints>Dt)return console.error(`[SPZ ERROR] deserializePackedGaussians: Too many points: ${n.numPoints}`),null;if(n.shDegree>3)return console.error(`[SPZ ERROR] deserializePackedGaussians: Unsupported SH degree: ${n.shDegree}`),null;const r=n.numPoints,i=It(n.shDegree),o={numPoints:r,shDegree:n.shDegree,fractionalBits:n.fractionalBits,antialiased:0!=(n.flags&xt),positions:new Uint8Array(3*r*(1===n.version?2:3)),scales:new Uint8Array(3*r),rotations:new Uint8Array(3*r),alphas:new Uint8Array(r),colors:new Uint8Array(3*r),sh:new Uint8Array(r*i*3)};try{const t=new Uint8Array(e);let n=o.positions.length,r=s;if(o.positions.set(t.slice(r,r+n)),r+=n,o.alphas.set(t.slice(r,r+o.alphas.length)),r+=o.alphas.length,o.colors.set(t.slice(r,r+o.colors.length)),r+=o.colors.length,o.scales.set(t.slice(r,r+o.scales.length)),r+=o.scales.length,o.rotations.set(t.slice(r,r+o.rotations.length)),r+=o.rotations.length,o.sh.set(t.slice(r,r+o.sh.length)),r+o.sh.length!==e.byteLength)return console.error("[SPZ ERROR] deserializePackedGaussians: incorrect buffer size"),null}catch(e){return console.error("[SPZ ERROR] deserializePackedGaussians: read error",e),null}return o}((await Ct(e)).buffer)}catch(e){return console.error("[SPZ ERROR] loadSpzPacked: decompression error",e),null}}class Et{static loadFromURL(e,t,s,n,r=!0,i=0,o,a,l,c,h){return t&&t(0,"0%",lt),m(e,t,!0,o).then((e=>(t&&t(0,"0%",ct),Et.loadFromFileData(e,s,n,r,i,a,l,c,h))))}static async loadFromFileData(e,t,s,n,r=0,i,o,a,l){await S();const c=await Tt(e);r=Math.min(c.shDegree,r);const h=new w(r);if(n){wt(c,r,!1,h,0);return at.getStandardGenerator(t,s,i,o,a,l).generateFromUncompressedSplatArray(h)}{const{splatBuffer:e,splatBufferDataOffsetBytes:t}=U.preallocateUncompressed(c.numPoints,r);return wt(c,r,!0,e.bufferData,t),e}}}class Mt{static RowSizeBytes=32;static CenterSizeBytes=12;static ScaleSizeBytes=12;static RotationSizeBytes=4;static ColorSizeBytes=4;static parseToUncompressedSplatBufferSection(t,s,n,r,i,o){const a=U.CompressionLevels[0].BytesPerCenter,l=U.CompressionLevels[0].BytesPerScale,c=U.CompressionLevels[0].BytesPerRotation,h=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;for(let d=t;d<=s;d++){const t=d*Mt.RowSizeBytes+r,s=new Float32Array(n,t,3),p=new Float32Array(n,t+Mt.CenterSizeBytes,3),u=new Uint8Array(n,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes,4),m=new Uint8Array(n,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes+Mt.RotationSizeBytes,4),A=new e.Quaternion((m[1]-128)/128,(m[2]-128)/128,(m[3]-128)/128,(m[0]-128)/128);A.normalize();const f=d*h+o,g=new Float32Array(i,f,3),S=new Float32Array(i,f+a,3),C=new Float32Array(i,f+a+l,4),y=new Uint8Array(i,f+a+l+c,4);g[0]=s[0],g[1]=s[1],g[2]=s[2],S[0]=p[0],S[1]=p[1],S[2]=p[2],C[0]=A.w,C[1]=A.x,C[2]=A.y,C[3]=A.z,y[0]=u[0],y[1]=u[1],y[2]=u[2],y[3]=u[3]}}static parseToUncompressedSplatArraySection(t,s,n,r,i){for(let o=t;o<=s;o++){const t=o*Mt.RowSizeBytes+r,s=new Float32Array(n,t,3),a=new Float32Array(n,t+Mt.CenterSizeBytes,3),l=new Uint8Array(n,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes,4),c=new Uint8Array(n,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes+Mt.RotationSizeBytes,4),h=new e.Quaternion((c[1]-128)/128,(c[2]-128)/128,(c[3]-128)/128,(c[0]-128)/128);h.normalize(),i.addSplatFromComonents(s[0],s[1],s[2],a[0],a[1],a[2],h.w,h.x,h.y,h.z,l[0],l[1],l[2],l[3])}}static parseStandardSplatToUncompressedSplatArray(t){const s=t.byteLength/Mt.RowSizeBytes,n=new w;for(let r=0;r<s;r++){const s=r*Mt.RowSizeBytes,i=new Float32Array(t,s,3),o=new Float32Array(t,s+Mt.CenterSizeBytes,3),a=new Uint8Array(t,s+Mt.CenterSizeBytes+Mt.ScaleSizeBytes,4),l=new Uint8Array(t,s+Mt.CenterSizeBytes+Mt.ScaleSizeBytes+Mt.ColorSizeBytes,4),c=new e.Quaternion((l[1]-128)/128,(l[2]-128)/128,(l[3]-128)/128,(l[0]-128)/128);c.normalize(),n.addSplatFromComonents(i[0],i[1],i[2],o[0],o[1],o[2],c.w,c.x,c.y,c.z,a[0],a[1],a[2],a[3])}return n}}function Ft(t,s,n,r,i,o,a,l){if(s){return at.getStandardGenerator(n,r,i,o,a,l).generateFromUncompressedSplatArray(t)}return U.generateFromUncompressedSplatArrays([t],n,0,new e.Vector3)}class Rt{static loadFromURL(t,s,n,r,i,o,a=!0,l,c,h,d,p){let u=n?pt:ut;a&&(u=ut);const A=U.HeaderSizeBytes+U.SectionHeaderSizeBytes,f=b.ProgressiveLoadSectionSize;let g,C,x,v,I=0,B=0;const D=y();let T=0,E=0,M=[];return s&&s(0,"0%",lt),m(t,((t,i,o,a)=>{const l=t>=100;if(o&&M.push(o),u!==mt)if(a){if(!g){I=a/Mt.RowSizeBytes,g=new ArrayBuffer(a);const t=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;u===pt?(C=new ArrayBuffer(A+t*I),U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:I,splatCount:B,compressionLevel:0,sceneCenter:new e.Vector3},C)):v=new w(0)}if(o){new Uint8Array(g,E,o.byteLength).set(new Uint8Array(o)),E+=o.byteLength;const e=E-T;if(e>f||l){const t=(l?e:f)/Mt.RowSizeBytes,s=B+t;u===pt?Mt.parseToUncompressedSplatBufferSection(B,s-1,g,0,C,A):Mt.parseToUncompressedSplatArraySection(B,s-1,g,0,v),B=s,u===pt&&(x||(U.writeSectionHeaderToBuffer({maxSplatCount:I,splatCount:B,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0},0,C,U.HeaderSizeBytes),x=new U(C,!1)),x.updateLoadedCounts(1,B),r&&r(x,l)),T+=f}}l&&(u===pt?D.resolve(x):D.resolve(v)),s&&s(t,i,lt)}else{if(n)throw new dt("Cannon directly load .splat because no file size info is available.");u=mt}else l&&D.resolve(M)}),!1,l).then((()=>(s&&s(0,"0%",ct),D.promise.then((e=>(s&&s(100,"100%",ht),u===mt?new Blob(M).arrayBuffer().then((e=>Rt.loadFromFileData(e,i,o,a,c,h,d,p))):u===pt?e:S((()=>Ft(e,a,i,o,c,h,d,p)))))))))}static loadFromFileData(e,t,s,n,r,i,o,a){return S((()=>Ft(Mt.parseStandardSplatToUncompressedSplatArray(e),n,t,s,r,i,o,a)))}}class Pt{static checkVersion(e){const t=U.CurrentMajorVersion,s=U.CurrentMinorVersion,n=U.parseHeader(e);if(n.versionMajor===t&&n.versionMinor>=s||n.versionMajor>t)return!0;throw new Error(`KSplat version not supported: v${n.versionMajor}.${n.versionMinor}. Minimum required: v${t}.${s}`)}static loadFromURL(e,t,s,n,r){let i,o,a,l,c,h=!1,d=!1,p=[],u=!1,A=!1,f=0,g=0,S=0,C=!1,x=!1,v=!1,I=[];const B=y();let w=0;const D=()=>{const e=()=>{A=!0;new Blob(I).arrayBuffer().then((e=>{A=!1,u=!0,c=new ArrayBuffer(l.maxSectionCount*U.SectionHeaderSizeBytes),new Uint8Array(c).set(new Uint8Array(e,U.HeaderSizeBytes,l.maxSectionCount*U.SectionHeaderSizeBytes)),p=U.parseSectionHeaders(l,c,0,!1);let t=0;for(let e=0;e<l.maxSectionCount;e++)t+=p[e].storageSizeBytes;const s=U.HeaderSizeBytes+l.maxSectionCount*U.SectionHeaderSizeBytes+t;if(!i){i=new ArrayBuffer(s);let e=0;for(let t=0;t<I.length;t++){const s=I[t];new Uint8Array(i,e,s.byteLength).set(new Uint8Array(s)),e+=s.byteLength}}S=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*l.maxSectionCount;for(let e=0;e<=p.length&&e<l.maxSectionCount;e++)S+=p[e].storageSizeBytes;0===w&&(w++,window.setTimeout((()=>{w--,T()}),1))}))};!A&&!u&&h&&f>=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*l.maxSectionCount&&e()},T=()=>{if(v)return;v=!0;window.setTimeout((()=>{if(v=!1,u){if(x)return;if(C=f>=S,f-g>b.ProgressiveLoadSectionSize||C){g+=b.ProgressiveLoadSectionSize,x=g>=S,o||(o=new U(i,!1));const e=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*l.maxSectionCount;let s=0,r=0,a=0;for(let t=0;t<l.maxSectionCount;t++){const n=p[t],i=e+(s+4*n.partiallyFilledBucketCount+n.bucketStorageSizeBytes*n.bucketCount);if(!(g>=i))break;{r++;const e=g-i,s=U.CompressionLevels[l.compressionLevel].SphericalHarmonicsDegrees[n.sphericalHarmonicsDegree].BytesPerSplat;let c=Math.floor(e/s);c=Math.min(c,n.maxSplatCount),a+=c,o.updateLoadedCounts(r,a),o.updateSectionLoadedCounts(t,c)}s+=n.storageSizeBytes}n(o,x);const c=g/S*100,h=c.toFixed(2)+"%";t&&t(c,h,lt),x?B.resolve(o):T()}}}),b.ProgressiveLoadSectionDelayDuration)};return m(e,((e,n,r)=>{r&&(I.push(r),i&&new Uint8Array(i,f,r.byteLength).set(new Uint8Array(r)),f+=r.byteLength),s?(!h&&!d&&f>=U.HeaderSizeBytes&&(d=!0,new Blob(I).arrayBuffer().then((e=>{a=new ArrayBuffer(U.HeaderSizeBytes),new Uint8Array(a).set(new Uint8Array(e,0,U.HeaderSizeBytes)),Pt.checkVersion(a),d=!1,h=!0,l=U.parseHeader(a),window.setTimeout((()=>{D()}),1)}))),D(),T()):t&&t(e,n,lt)}),!s,r).then((e=>{t&&t(0,"0%",ct);return(s?B.promise:Pt.loadFromFileData(e)).then((e=>(t&&t(100,"100%",ht),e)))}))}static loadFromFileData(e){return S((()=>(Pt.checkVersion(e),new U(e))))}static downloadFile=function(){let e;return function(t,s){const n=new Blob([t.bufferData],{type:"application/octet-stream"});e||(e=document.createElement("a"),document.body.appendChild(e)),e.download=s,e.href=URL.createObjectURL(n),e.click()}}()}const Ht=0,kt=1,Lt=2,Ot=3,Ut=e=>e.endsWith(".ply")?Lt:e.endsWith(".splat")?Ht:e.endsWith(".ksplat")?kt:e.endsWith(".spz")?Ot:null,zt={type:"change"},_t={type:"start"},Qt={type:"end"},Vt=new t,Nt=new s,Gt=Math.cos(70*n.DEG2RAD);class Kt extends r{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new i,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"KeyA",UP:"KeyW",RIGHT:"KeyD",BOTTOM:"KeyS"},this.mouseButtons={LEFT:o.ROTATE,MIDDLE:o.DOLLY,RIGHT:o.PAN},this.touches={ONE:a.ROTATE,TWO:a.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return p.phi},this.getAzimuthalAngle=function(){return p.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(e){e.addEventListener("keydown",Z),this._domElementKeyEvents=e},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Z),this._domElementKeyEvents=null},this.saveState=function(){s.target0.copy(s.target),s.position0.copy(s.object.position),s.zoom0=s.object.zoom},this.reset=function(){s.target.copy(s.target0),s.object.position.copy(s.position0),s.object.zoom=s.zoom0,this.clearDampedRotation(),this.clearDampedPan(),s.object.updateProjectionMatrix(),s.dispatchEvent(zt),s.update(),r=n.NONE},this.clearDampedRotation=function(){u.theta=0,u.phi=0},this.clearDampedPan=function(){A.set(0,0,0)},this.update=function(){const t=new i,o=(new l).setFromUnitVectors(e.up,new i(0,1,0)),a=o.clone().invert(),c=new i,h=new l,f=new i,g=2*Math.PI;return function(){o.setFromUnitVectors(e.up,new i(0,1,0)),a.copy(o).invert();const l=s.object.position;t.copy(l).sub(s.target),t.applyQuaternion(o),p.setFromVector3(t),s.autoRotate&&r===n.NONE&&F(2*Math.PI/60/60*s.autoRotateSpeed),s.enableDamping?(p.theta+=u.theta*s.dampingFactor,p.phi+=u.phi*s.dampingFactor):(p.theta+=u.theta,p.phi+=u.phi);let S=s.minAzimuthAngle,C=s.maxAzimuthAngle;isFinite(S)&&isFinite(C)&&(S<-Math.PI?S+=g:S>Math.PI&&(S-=g),C<-Math.PI?C+=g:C>Math.PI&&(C-=g),p.theta=S<=C?Math.max(S,Math.min(C,p.theta)):p.theta>(S+C)/2?Math.max(S,p.theta):Math.min(C,p.theta)),p.phi=Math.max(s.minPolarAngle,Math.min(s.maxPolarAngle,p.phi)),p.makeSafe(),!0===s.enableDamping?s.target.addScaledVector(A,s.dampingFactor):s.target.add(A),s.zoomToCursor&&D||s.object.isOrthographicCamera?p.radius=z(p.radius):p.radius=z(p.radius*m),t.setFromSpherical(p),t.applyQuaternion(a),l.copy(s.target).add(t),s.object.lookAt(s.target),!0===s.enableDamping?(u.theta*=1-s.dampingFactor,u.phi*=1-s.dampingFactor,A.multiplyScalar(1-s.dampingFactor)):(u.set(0,0,0),A.set(0,0,0));let y=!1;if(s.zoomToCursor&&D){let n=null;if(s.object.isPerspectiveCamera){const e=t.length();n=z(e*m);const r=e-n;s.object.position.addScaledVector(w,r),s.object.updateMatrixWorld()}else if(s.object.isOrthographicCamera){const e=new i(b.x,b.y,0);e.unproject(s.object),s.object.zoom=Math.max(s.minZoom,Math.min(s.maxZoom,s.object.zoom/m)),s.object.updateProjectionMatrix(),y=!0;const r=new i(b.x,b.y,0);r.unproject(s.object),s.object.position.sub(r).add(e),s.object.updateMatrixWorld(),n=t.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),s.zoomToCursor=!1;null!==n&&(this.screenSpacePanning?s.target.set(0,0,-1).transformDirection(s.object.matrix).multiplyScalar(n).add(s.object.position):(Vt.origin.copy(s.object.position),Vt.direction.set(0,0,-1).transformDirection(s.object.matrix),Math.abs(s.object.up.dot(Vt.direction))<Gt?e.lookAt(s.target):(Nt.setFromNormalAndCoplanarPoint(s.object.up,s.target),Vt.intersectPlane(Nt,s.target))))}else s.object.isOrthographicCamera&&(s.object.zoom=Math.max(s.minZoom,Math.min(s.maxZoom,s.object.zoom/m)),s.object.updateProjectionMatrix(),y=!0);return m=1,D=!1,!!(y||c.distanceToSquared(s.object.position)>d||8*(1-h.dot(s.object.quaternion))>d||f.distanceToSquared(s.target)>0)&&(s.dispatchEvent(zt),c.copy(s.object.position),h.copy(s.object.quaternion),f.copy(s.target),y=!1,!0)}}(),this.dispose=function(){s.domElement.removeEventListener("contextmenu",$),s.domElement.removeEventListener("pointerdown",j),s.domElement.removeEventListener("pointercancel",X),s.domElement.removeEventListener("wheel",J),s.domElement.removeEventListener("pointermove",Y),s.domElement.removeEventListener("pointerup",X),null!==s._domElementKeyEvents&&(s._domElementKeyEvents.removeEventListener("keydown",Z),s._domElementKeyEvents=null)};const s=this,n={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=n.NONE;const d=1e-6,p=new c,u=new c;let m=1;const A=new i,f=new h,g=new h,S=new h,C=new h,y=new h,x=new h,v=new h,I=new h,B=new h,w=new i,b=new h;let D=!1;const T=[],E={};function M(){return Math.pow(.95,s.zoomSpeed)}function F(e){u.theta-=e}function R(e){u.phi-=e}const P=function(){const e=new i;return function(t,s){e.setFromMatrixColumn(s,0),e.multiplyScalar(-t),A.add(e)}}(),H=function(){const e=new i;return function(t,n){!0===s.screenSpacePanning?e.setFromMatrixColumn(n,1):(e.setFromMatrixColumn(n,0),e.crossVectors(s.object.up,e)),e.multiplyScalar(t),A.add(e)}}(),k=function(){const e=new i;return function(t,n){const r=s.domElement;if(s.object.isPerspectiveCamera){const i=s.object.position;e.copy(i).sub(s.target);let o=e.length();o*=Math.tan(s.object.fov/2*Math.PI/180),P(2*t*o/r.clientHeight,s.object.matrix),H(2*n*o/r.clientHeight,s.object.matrix)}else s.object.isOrthographicCamera?(P(t*(s.object.right-s.object.left)/s.object.zoom/r.clientWidth,s.object.matrix),H(n*(s.object.top-s.object.bottom)/s.object.zoom/r.clientHeight,s.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),s.enablePan=!1)}}();function L(e){s.object.isPerspectiveCamera||s.object.isOrthographicCamera?m/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),s.enableZoom=!1)}function O(e){s.object.isPerspectiveCamera||s.object.isOrthographicCamera?m*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),s.enableZoom=!1)}function U(t){if(!s.zoomToCursor)return;D=!0;const n=s.domElement.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,o=n.width,a=n.height;b.x=r/o*2-1,b.y=-i/a*2+1,w.set(b.x,b.y,1).unproject(e).sub(e.position).normalize()}function z(e){return Math.max(s.minDistance,Math.min(s.maxDistance,e))}function _(e){f.set(e.clientX,e.clientY)}function Q(e){C.set(e.clientX,e.clientY)}function V(){if(1===T.length)f.set(T[0].pageX,T[0].pageY);else{const e=.5*(T[0].pageX+T[1].pageX),t=.5*(T[0].pageY+T[1].pageY);f.set(e,t)}}function N(){if(1===T.length)C.set(T[0].pageX,T[0].pageY);else{const e=.5*(T[0].pageX+T[1].pageX),t=.5*(T[0].pageY+T[1].pageY);C.set(e,t)}}function G(){const e=T[0].pageX-T[1].pageX,t=T[0].pageY-T[1].pageY,s=Math.sqrt(e*e+t*t);v.set(0,s)}function K(e){if(1==T.length)g.set(e.pageX,e.pageY);else{const t=te(e),s=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);g.set(s,n)}S.subVectors(g,f).multiplyScalar(s.rotateSpeed);const t=s.domElement;F(2*Math.PI*S.x/t.clientHeight),R(2*Math.PI*S.y/t.clientHeight),f.copy(g)}function q(e){if(1===T.length)y.set(e.pageX,e.pageY);else{const t=te(e),s=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);y.set(s,n)}x.subVectors(y,C).multiplyScalar(s.panSpeed),k(x.x,x.y),C.copy(y)}function W(e){const t=te(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);I.set(0,i),B.set(0,Math.pow(I.y/v.y,s.zoomSpeed)),L(B.y),v.copy(I)}function j(e){!1!==s.enabled&&(0===T.length&&(s.domElement.setPointerCapture(e.pointerId),s.domElement.addEventListener("pointermove",Y),s.domElement.addEventListener("pointerup",X)),function(e){T.push(e)}(e),"touch"===e.pointerType?function(e){switch(ee(e),T.length){case 1:switch(s.touches.ONE){case a.ROTATE:if(!1===s.enableRotate)return;V(),r=n.TOUCH_ROTATE;break;case a.PAN:if(!1===s.enablePan)return;N(),r=n.TOUCH_PAN;break;default:r=n.NONE}break;case 2:switch(s.touches.TWO){case a.DOLLY_PAN:if(!1===s.enableZoom&&!1===s.enablePan)return;s.enableZoom&&G(),s.enablePan&&N(),r=n.TOUCH_DOLLY_PAN;break;case a.DOLLY_ROTATE:if(!1===s.enableZoom&&!1===s.enableRotate)return;s.enableZoom&&G(),s.enableRotate&&V(),r=n.TOUCH_DOLLY_ROTATE;break;default:r=n.NONE}break;default:r=n.NONE}r!==n.NONE&&s.dispatchEvent(_t)}(e):function(e){let t;switch(e.button){case 0:t=s.mouseButtons.LEFT;break;case 1:t=s.mouseButtons.MIDDLE;break;case 2:t=s.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o.DOLLY:if(!1===s.enableZoom)return;!function(e){U(e),v.set(e.clientX,e.clientY)}(e),r=n.DOLLY;break;case o.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===s.enablePan)return;Q(e),r=n.PAN}else{if(!1===s.enableRotate)return;_(e),r=n.ROTATE}break;case o.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===s.enableRotate)return;_(e),r=n.ROTATE}else{if(!1===s.enablePan)return;Q(e),r=n.PAN}break;default:r=n.NONE}r!==n.NONE&&s.dispatchEvent(_t)}(e))}function Y(e){!1!==s.enabled&&("touch"===e.pointerType?function(e){switch(ee(e),r){case n.TOUCH_ROTATE:if(!1===s.enableRotate)return;K(e),s.update();break;case n.TOUCH_PAN:if(!1===s.enablePan)return;q(e),s.update();break;case n.TOUCH_DOLLY_PAN:if(!1===s.enableZoom&&!1===s.enablePan)return;!function(e){s.enableZoom&&W(e),s.enablePan&&q(e)}(e),s.update();break;case n.TOUCH_DOLLY_ROTATE:if(!1===s.enableZoom&&!1===s.enableRotate)return;!function(e){s.enableZoom&&W(e),s.enableRotate&&K(e)}(e),s.update();break;default:r=n.NONE}}(e):function(e){switch(r){case n.ROTATE:if(!1===s.enableRotate)return;!function(e){g.set(e.clientX,e.clientY),S.subVectors(g,f).multiplyScalar(s.rotateSpeed);const t=s.domElement;F(2*Math.PI*S.x/t.clientHeight),R(2*Math.PI*S.y/t.clientHeight),f.copy(g),s.update()}(e);break;case n.DOLLY:if(!1===s.enableZoom)return;!function(e){I.set(e.clientX,e.clientY),B.subVectors(I,v),B.y>0?L(M()):B.y<0&&O(M()),v.copy(I),s.update()}(e);break;case n.PAN:if(!1===s.enablePan)return;!function(e){y.set(e.clientX,e.clientY),x.subVectors(y,C).multiplyScalar(s.panSpeed),k(x.x,x.y),C.copy(y),s.update()}(e)}}(e))}function X(e){!function(e){delete E[e.pointerId];for(let t=0;t<T.length;t++)if(T[t].pointerId==e.pointerId)return void T.splice(t,1)}(e),0===T.length&&(s.domElement.releasePointerCapture(e.pointerId),s.domElement.removeEventListener("pointermove",Y),s.domElement.removeEventListener("pointerup",X)),s.dispatchEvent(Qt),r=n.NONE}function J(e){!1!==s.enabled&&!1!==s.enableZoom&&r===n.NONE&&(e.preventDefault(),s.dispatchEvent(_t),function(e){U(e),e.deltaY<0?O(M()):e.deltaY>0&&L(M()),s.update()}(e),s.dispatchEvent(Qt))}function Z(e){!1!==s.enabled&&!1!==s.enablePan&&function(e){let t=!1;switch(e.code){case s.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?R(2*Math.PI*s.rotateSpeed/s.domElement.clientHeight):k(0,s.keyPanSpeed),t=!0;break;case s.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?R(-2*Math.PI*s.rotateSpeed/s.domElement.clientHeight):k(0,-s.keyPanSpeed),t=!0;break;case s.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?F(2*Math.PI*s.rotateSpeed/s.domElement.clientHeight):k(s.keyPanSpeed,0),t=!0;break;case s.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?F(-2*Math.PI*s.rotateSpeed/s.domElement.clientHeight):k(-s.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),s.update())}(e)}function $(e){!1!==s.enabled&&e.preventDefault()}function ee(e){let t=E[e.pointerId];void 0===t&&(t=new h,E[e.pointerId]=t),t.set(e.pageX,e.pageY)}function te(e){const t=e.pointerId===T[0].pointerId?T[1]:T[0];return E[t.pointerId]}s.domElement.addEventListener("contextmenu",$),s.domElement.addEventListener("pointerdown",j),s.domElement.addEventListener("pointercancel",X),s.domElement.addEventListener("wheel",J,{passive:!1}),this.update()}}class qt{static elementIDGen=0;constructor(e,t){this.taskIDGen=0,this.elementID=qt.elementIDGen++,this.tasks=[],this.message=e||"Loading...",this.container=t||document.body,this.spinnerContainerOuter=document.createElement("div"),this.spinnerContainerOuter.className=`spinnerOuterContainer${this.elementID}`,this.spinnerContainerOuter.style.display="none",this.spinnerContainerPrimary=document.createElement("div"),this.spinnerContainerPrimary.className=`spinnerContainerPrimary${this.elementID}`,this.spinnerPrimary=document.createElement("div"),this.spinnerPrimary.classList.add(`spinner${this.elementID}`,`spinnerPrimary${this.elementID}`),this.messageContainerPrimary=document.createElement("div"),this.messageContainerPrimary.classList.add(`messageContainer${this.elementID}`,`messageContainerPrimary${this.elementID}`),this.messageContainerPrimary.innerHTML=this.message,this.spinnerContainerMin=document.createElement("div"),this.spinnerContainerMin.className=`spinnerContainerMin${this.elementID}`,this.spinnerMin=document.createElement("div"),this.spinnerMin.classList.add(`spinner${this.elementID}`,`spinnerMin${this.elementID}`),this.messageContainerMin=document.createElement("div"),this.messageContainerMin.classList.add(`messageContainer${this.elementID}`,`messageContainerMin${this.elementID}`),this.messageContainerMin.innerHTML=this.message,this.spinnerContainerPrimary.appendChild(this.spinnerPrimary),this.spinnerContainerPrimary.appendChild(this.messageContainerPrimary),this.spinnerContainerOuter.appendChild(this.spinnerContainerPrimary),this.spinnerContainerMin.appendChild(this.spinnerMin),this.spinnerContainerMin.appendChild(this.messageContainerMin),this.spinnerContainerOuter.appendChild(this.spinnerContainerMin);const s=document.createElement("style");s.innerHTML=`\n\n .spinnerOuterContainer${this.elementID} {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .messageContainer${this.elementID} {\n height: 20px;\n font-family: arial;\n font-size: 12pt;\n color: #ffffff;\n text-align: center;\n vertical-align: middle;\n }\n\n .spinner${this.elementID} {\n padding: 15px;\n background: #07e8d6;\n z-index:99999;\n \n aspect-ratio: 1;\n border-radius: 50%;\n --_m: \n conic-gradient(#0000,#000),\n linear-gradient(#000 0 0) content-box;\n -webkit-mask: var(--_m);\n mask: var(--_m);\n -webkit-mask-composite: source-out;\n mask-composite: subtract;\n box-sizing: border-box;\n animation: load 1s linear infinite;\n }\n\n .spinnerContainerPrimary${this.elementID} {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 10px;\n margin: 0;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-80px, -80px);\n width: 180px;\n pointer-events: auto;\n }\n\n .spinnerPrimary${this.elementID} {\n width: 120px;\n margin-left: 30px;\n }\n\n .messageContainerPrimary${this.elementID} {\n padding-top: 15px;\n }\n\n .spinnerContainerMin${this.elementID} {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n display: flex;\n flex-direction: left;\n pointer-events: auto;\n min-width: 250px;\n }\n\n .messageContainerMin${this.elementID} {\n margin-right: 15px;\n }\n\n .spinnerMin${this.elementID} {\n width: 50px;\n height: 50px;\n margin-left: 15px;\n margin-right: 25px;\n }\n\n .messageContainerMin${this.elementID} {\n padding-top: 15px;\n }\n \n @keyframes load {\n to{transform: rotate(1turn)}\n }\n\n `,this.spinnerContainerOuter.appendChild(s),this.container.appendChild(this.spinnerContainerOuter),this.setMinimized(!1,!0),this.fadeTransitions=[]}addTask(e){const t={message:e,id:this.taskIDGen++};return this.tasks.push(t),this.update(),t.id}removeTask(e){let t=0;for(let s of this.tasks){if(s.id===e){this.tasks.splice(t,1);break}t++}this.update()}removeAllTasks(){this.tasks=[],this.update()}setMessageForTask(e,t){for(let s of this.tasks)if(s.id===e){s.message=t;break}this.update()}update(){this.tasks.length>0?(this.show(),this.setMessage(this.tasks[this.tasks.length-1].message)):this.hide()}show(){this.spinnerContainerOuter.style.display="block",this.visible=!0}hide(){this.spinnerContainerOuter.style.display="none",this.visible=!1}setContainer(e){this.container&&this.spinnerContainerOuter.parentElement===this.container&&this.container.removeChild(this.spinnerContainerOuter),e&&(this.container=e,this.container.appendChild(this.spinnerContainerOuter),this.spinnerContainerOuter.style.zIndex=this.container.style.zIndex+1)}setMinimized(e,t){const s=(e,t,s,n,r)=>{s?e.style.display=t?n:"none":this.fadeTransitions[r]=((e,t,s,n,r)=>{const i=performance.now();let o="none"===e.style.display?0:parseFloat(e.style.opacity);isNaN(o)&&(o=1);const a=window.setInterval((()=>{const l=performance.now()-i;let c,h=Math.min(l/n,1);h>.999&&(h=1),t?(c=(1-h)*o,c<1e-4&&(c=0)):c=(1-o)*h+o,c>0?(e.style.display=s,e.style.opacity=c):e.style.display="none",h>=1&&(r&&r(),window.clearInterval(a))}),16);return a})(e,!t,n,500,(()=>{this.fadeTransitions[r]=null}))};s(this.spinnerContainerPrimary,!e,t,"block",0),s(this.spinnerContainerMin,e,t,"flex",1),this.minimized=e}setMessage(e){this.messageContainerPrimary.innerHTML=e,this.messageContainerMin.innerHTML=e}}class Wt{constructor(e){this.idGen=0,this.tasks=[],this.container=e||document.body,this.progressBarContainerOuter=document.createElement("div"),this.progressBarContainerOuter.className="progressBarOuterContainer",this.progressBarContainerOuter.style.display="none",this.progressBarBox=document.createElement("div"),this.progressBarBox.className="progressBarBox",this.progressBarBackground=document.createElement("div"),this.progressBarBackground.className="progressBarBackground",this.progressBar=document.createElement("div"),this.progressBar.className="progressBar",this.progressBarBackground.appendChild(this.progressBar),this.progressBarBox.appendChild(this.progressBarBackground),this.progressBarContainerOuter.appendChild(this.progressBarBox);const t=document.createElement("style");t.innerHTML="\n\n .progressBarOuterContainer {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .progressBarBox {\n z-index:99999;\n padding: 7px 9px 5px 7px;\n background-color: rgba(190, 190, 190, 0.75);\n border: #555555 1px solid;\n border-radius: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n width: 180px;\n height: 30px;\n pointer-events: auto;\n }\n\n .progressBarBackground {\n width: 100%;\n height: 25px;\n border-radius:10px;\n background-color: rgba(128, 128, 128, 0.75);\n border: #444444 1px solid;\n box-shadow: inset 0 0 10px #333333;\n }\n\n .progressBar {\n height: 25px;\n width: 0px;\n border-radius:10px;\n background-color: rgba(0, 200, 0, 0.75);\n box-shadow: inset 0 0 10px #003300;\n }\n\n ",this.progressBarContainerOuter.appendChild(t),this.container.appendChild(this.progressBarContainerOuter)}show(){this.progressBarContainerOuter.style.display="block"}hide(){this.progressBarContainerOuter.style.display="none"}setProgress(e){this.progressBar.style.width=e+"%"}setContainer(e){this.container&&this.progressBarContainerOuter.parentElement===this.container&&this.container.removeChild(this.progressBarContainerOuter),e&&(this.container=e,this.container.appendChild(this.progressBarContainerOuter),this.progressBarContainerOuter.style.zIndex=this.container.style.zIndex+1)}}class jt{constructor(e){this.container=e||document.body,this.infoCells={};const t=[["Camera position","cameraPosition"],["Camera look-at","cameraLookAt"],["Camera up","cameraUp"],["Camera mode","orthographicCamera"],["Cursor position","cursorPosition"],["FPS","fps"],["Rendering:","renderSplatCount"],["Sort time","sortTime"],["Render window","renderWindow"],["Focal adjustment","focalAdjustment"],["Splat scale","splatScale"],["Point cloud mode","pointCloudMode"]];this.infoPanelContainer=document.createElement("div");const s=document.createElement("style");s.innerHTML="\n\n .infoPanel {\n width: 430px;\n padding: 10px;\n background-color: rgba(50, 50, 50, 0.85);\n border: #555555 2px solid;\n color: #dddddd;\n border-radius: 10px;\n z-index: 9999;\n font-family: arial;\n font-size: 11pt;\n text-align: left;\n margin: 0;\n top: 10px;\n left:10px;\n position: absolute;\n pointer-events: auto;\n }\n\n .info-panel-cell {\n margin-bottom: 5px;\n padding-bottom: 2px;\n }\n\n .label-cell {\n font-weight: bold;\n font-size: 12pt;\n width: 140px;\n }\n\n ",this.infoPanelContainer.append(s),this.infoPanel=document.createElement("div"),this.infoPanel.className="infoPanel";const n=document.createElement("div");n.style.display="table";for(let e of t){const t=document.createElement("div");t.style.display="table-row",t.className="info-panel-row";const s=document.createElement("div");s.style.display="table-cell",s.innerHTML=`${e[0]}: `,s.classList.add("info-panel-cell","label-cell");const r=document.createElement("div");r.style.display="table-cell",r.style.width="10px",r.innerHTML=" ",r.className="info-panel-cell";const i=document.createElement("div");i.style.display="table-cell",i.innerHTML="",i.className="info-panel-cell",this.infoCells[e[1]]=i,t.appendChild(s),t.appendChild(r),t.appendChild(i),n.appendChild(t)}this.infoPanel.appendChild(n),this.infoPanelContainer.append(this.infoPanel),this.infoPanelContainer.style.display="none",this.container.appendChild(this.infoPanelContainer),this.visible=!1}update=function(e,t,s,n,r,i,o,a,l,c,h,d,p,u){const m=`${t.x.toFixed(5)}, ${t.y.toFixed(5)}, ${t.z.toFixed(5)}`;if(this.infoCells.cameraPosition.innerHTML!==m&&(this.infoCells.cameraPosition.innerHTML=m),s){const e=s,t=`${e.x.toFixed(5)}, ${e.y.toFixed(5)}, ${e.z.toFixed(5)}`;this.infoCells.cameraLookAt.innerHTML!==t&&(this.infoCells.cameraLookAt.innerHTML=t)}const A=`${n.x.toFixed(5)}, ${n.y.toFixed(5)}, ${n.z.toFixed(5)}`;if(this.infoCells.cameraUp.innerHTML!==A&&(this.infoCells.cameraUp.innerHTML=A),this.infoCells.orthographicCamera.innerHTML=r?"Orthographic":"Perspective",i){const e=i,t=`${e.x.toFixed(5)}, ${e.y.toFixed(5)}, ${e.z.toFixed(5)}`;this.infoCells.cursorPosition.innerHTML=t}else this.infoCells.cursorPosition.innerHTML="N/A";this.infoCells.fps.innerHTML=o,this.infoCells.renderWindow.innerHTML=`${e.x} x ${e.y}`,this.infoCells.renderSplatCount.innerHTML=`${l} splats out of ${a} (${c.toFixed(2)}%)`,this.infoCells.sortTime.innerHTML=`${h.toFixed(3)} ms`,this.infoCells.focalAdjustment.innerHTML=`${d.toFixed(3)}`,this.infoCells.splatScale.innerHTML=`${p.toFixed(3)}`,this.infoCells.pointCloudMode.innerHTML=`${u}`};setContainer(e){this.container&&this.infoPanelContainer.parentElement===this.container&&this.container.removeChild(this.infoPanelContainer),e&&(this.container=e,this.container.appendChild(this.infoPanelContainer),this.infoPanelContainer.style.zIndex=this.container.style.zIndex+1)}show(){this.infoPanelContainer.style.display="block",this.visible=!0}hide(){this.infoPanelContainer.style.display="none",this.visible=!1}}const Yt=new e.Vector3;class Xt extends e.Object3D{constructor(t=new e.Vector3(0,0,1),s=new e.Vector3(0,0,0),n=1,r=.1,i=16776960,o=.2*n,a=.2*o){super(),this.type="ArrowHelper";const l=new e.CylinderGeometry(r,r,n,32);l.translate(0,n/2,0);const c=new e.CylinderGeometry(0,a,o,32);c.translate(0,n,0),this.position.copy(s),this.line=new e.Mesh(l,new e.MeshBasicMaterial({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new e.Mesh(c,new e.MeshBasicMaterial({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Yt.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Yt,t)}}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class Jt{constructor(e){this.threeScene=e,this.splatRenderTarget=null,this.renderTargetCopyQuad=null,this.renderTargetCopyCamera=null,this.meshCursor=null,this.focusMarker=null,this.controlPlane=null,this.debugRoot=null,this.secondaryDebugRoot=null}updateSplatRenderTargetForRenderDimensions(t,s){this.destroySplatRendertarget(),this.splatRenderTarget=new e.WebGLRenderTarget(t,s,{format:e.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}),this.splatRenderTarget.depthTexture=new e.DepthTexture(t,s),this.splatRenderTarget.depthTexture.format=e.DepthFormat,this.splatRenderTarget.depthTexture.type=e.UnsignedIntType}destroySplatRendertarget(){this.splatRenderTarget&&(this.splatRenderTarget=null)}setupRenderTargetCopyObjects(){const t=new e.ShaderMaterial({vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = vec4( position.xy, 0.0, 1.0 ); \n }\n ",fragmentShader:"\n #include <common>\n #include <packing>\n varying vec2 vUv;\n uniform sampler2D sourceColorTexture;\n uniform sampler2D sourceDepthTexture;\n void main() {\n vec4 color = texture2D(sourceColorTexture, vUv);\n float fragDepth = texture2D(sourceDepthTexture, vUv).x;\n gl_FragDepth = fragDepth;\n gl_FragColor = vec4(color.rgb, color.a * 2.0);\n }\n ",uniforms:{sourceColorTexture:{type:"t",value:null},sourceDepthTexture:{type:"t",value:null}},depthWrite:!1,depthTest:!1,transparent:!0,blending:e.CustomBlending,blendSrc:e.SrcAlphaFactor,blendSrcAlpha:e.SrcAlphaFactor,blendDst:e.OneMinusSrcAlphaFactor,blendDstAlpha:e.OneMinusSrcAlphaFactor});t.extensions.fragDepth=!0,this.renderTargetCopyQuad=new e.Mesh(new e.PlaneGeometry(2,2),t),this.renderTargetCopyCamera=new e.OrthographicCamera(-1,1,1,-1,0,1)}destroyRenderTargetCopyObjects(){this.renderTargetCopyQuad&&(g(this.renderTargetCopyQuad),this.renderTargetCopyQuad=null)}setupMeshCursor(){if(!this.meshCursor){const t=new e.ConeGeometry(.5,1.5,32),s=new e.MeshBasicMaterial({color:16777215}),n=new e.Mesh(t,s);n.rotation.set(0,0,Math.PI),n.position.set(0,1,0);const r=new e.Mesh(t,s);r.position.set(0,-1,0);const i=new e.Mesh(t,s);i.rotation.set(0,0,Math.PI/2),i.position.set(1,0,0);const o=new e.Mesh(t,s);o.rotation.set(0,0,-Math.PI/2),o.position.set(-1,0,0),this.meshCursor=new e.Object3D,this.meshCursor.add(n),this.meshCursor.add(r),this.meshCursor.add(i),this.meshCursor.add(o),this.meshCursor.scale.set(.1,.1,.1),this.threeScene.add(this.meshCursor),this.meshCursor.visible=!1}}destroyMeshCursor(){this.meshCursor&&(g(this.meshCursor),this.threeScene.remove(this.meshCursor),this.meshCursor=null)}setMeshCursorVisibility(e){this.meshCursor.visible=e}getMeschCursorVisibility(){return this.meshCursor.visible}setMeshCursorPosition(e){this.meshCursor.position.copy(e)}positionAndOrientMeshCursor(e,t){this.meshCursor.position.copy(e),this.meshCursor.up.copy(t.up),this.meshCursor.lookAt(t.position)}setupFocusMarker(){if(!this.focusMarker){const t=new e.SphereGeometry(.5,32,32),s=Jt.buildFocusMarkerMaterial();s.depthTest=!1,s.depthWrite=!1,s.transparent=!0,this.focusMarker=new e.Mesh(t,s)}}destroyFocusMarker(){this.focusMarker&&(g(this.focusMarker),this.focusMarker=null)}updateFocusMarker=function(){const t=new e.Vector3,s=new e.Matrix4,n=new e.Vector3;return function(e,r,i){s.copy(r.matrixWorld).invert(),t.copy(e).applyMatrix4(s),t.normalize().multiplyScalar(10),t.applyMatrix4(r.matrixWorld),n.copy(r.position).sub(e);const o=n.length();this.focusMarker.position.copy(e),this.focusMarker.scale.set(o,o,o),this.focusMarker.material.uniforms.realFocusPosition.value.copy(e),this.focusMarker.material.uniforms.viewport.value.copy(i),this.focusMarker.material.uniformsNeedUpdate=!0}}();setFocusMarkerVisibility(e){this.focusMarker.visible=e}setFocusMarkerOpacity(e){this.focusMarker.material.uniforms.opacity.value=e,this.focusMarker.material.uniformsNeedUpdate=!0}getFocusMarkerOpacity(){return this.focusMarker.material.uniforms.opacity.value}setupControlPlane(){if(!this.controlPlane){const t=new e.PlaneGeometry(1,1);t.rotateX(-Math.PI/2);const s=new e.MeshBasicMaterial({color:16777215});s.transparent=!0,s.opacity=.6,s.depthTest=!1,s.depthWrite=!1,s.side=e.DoubleSide;const n=new e.Mesh(t,s),r=new e.Vector3(0,1,0);r.normalize();const i=new e.Vector3(0,0,0),o=new Xt(r,i,.5,.01,56576,.1,.03);this.controlPlane=new e.Object3D,this.controlPlane.add(n),this.controlPlane.add(o)}}destroyControlPlane(){this.controlPlane&&(g(this.controlPlane),this.controlPlane=null)}setControlPlaneVisibility(e){this.controlPlane.visible=e}positionAndOrientControlPlane=function(){const t=new e.Quaternion,s=new e.Vector3(0,1,0);return function(e,n){t.setFromUnitVectors(s,n),this.controlPlane.position.copy(e),this.controlPlane.quaternion.copy(t)}}();addDebugMeshes(){this.debugRoot=this.createDebugMeshes(),this.secondaryDebugRoot=this.createSecondaryDebugMeshes(),this.threeScene.add(this.debugRoot),this.threeScene.add(this.secondaryDebugRoot)}destroyDebugMeshes(){for(let e of[this.debugRoot,this.secondaryDebugRoot])e&&(g(e),this.threeScene.remove(e));this.debugRoot=null,this.secondaryDebugRoot=null}createDebugMeshes(t){const s=new e.SphereGeometry(1,32,32),n=new e.Object3D,r=(r,i)=>{let o=new e.Mesh(s,Jt.buildDebugMaterial(r));o.renderOrder=t,n.add(o),o.position.fromArray(i)};return r(16711680,[-50,0,0]),r(16711680,[50,0,0]),r(65280,[0,0,-50]),r(65280,[0,0,50]),r(16755200,[5,0,5]),n}createSecondaryDebugMeshes(t){const s=new e.BoxGeometry(3,3,3),n=new e.Object3D;const r=r=>{let i=new e.Mesh(s,Jt.buildDebugMaterial(12303291));i.renderOrder=t,n.add(i),i.position.fromArray(r)};let i=10;return r([-10,0,-10]),r([-10,0,i]),r([i,0,-10]),r([i,0,i]),n}static buildDebugMaterial(t){const s={color:{type:"v3",value:new e.Color(t)}},n=new e.ShaderMaterial({uniforms:s,vertexShader:"\n #include <common>\n varying float ndcDepth;\n\n void main() {\n gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position.xyz, 1.0);\n ndcDepth = gl_Position.z / gl_Position.w;\n gl_Position.x = gl_Position.x / gl_Position.w;\n gl_Position.y = gl_Position.y / gl_Position.w;\n gl_Position.z = 0.0;\n gl_Position.w = 1.0;\n \n }\n ",fragmentShader:"\n #include <common>\n uniform vec3 color;\n varying float ndcDepth;\n void main() {\n gl_FragDepth = (ndcDepth + 1.0) / 2.0;\n gl_FragColor = vec4(color.rgb, 0.0);\n }\n ",transparent:!1,depthTest:!0,depthWrite:!0,side:e.FrontSide});return n.extensions.fragDepth=!0,n}static buildFocusMarkerMaterial(t){const s={color:{type:"v3",value:new e.Color(t)},realFocusPosition:{type:"v3",value:new e.Vector3},viewport:{type:"v2",value:new e.Vector2},opacity:{value:0}};return new e.ShaderMaterial({uniforms:s,vertexShader:"\n #include <common>\n\n uniform vec2 viewport;\n uniform vec3 realFocusPosition;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n float radius = 0.01;\n\n vec4 viewPosition = modelViewMatrix * vec4(position.xyz, 1.0);\n vec4 viewCenter = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);\n\n vec4 viewFocusPosition = modelViewMatrix * vec4(realFocusPosition, 1.0);\n\n ndcPosition = projectionMatrix * viewPosition;\n ndcPosition = ndcPosition * vec4(1.0 / ndcPosition.w);\n ndcCenter = projectionMatrix * viewCenter;\n ndcCenter = ndcCenter * vec4(1.0 / ndcCenter.w);\n\n ndcFocusPosition = projectionMatrix * viewFocusPosition;\n ndcFocusPosition = ndcFocusPosition * vec4(1.0 / ndcFocusPosition.w);\n\n gl_Position = projectionMatrix * viewPosition;\n\n }\n ",fragmentShader:"\n #include <common>\n uniform vec3 color;\n uniform vec2 viewport;\n uniform float opacity;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n vec2 screenPosition = vec2(ndcPosition) * viewport;\n vec2 screenCenter = vec2(ndcCenter) * viewport;\n\n vec2 screenVec = screenPosition - screenCenter;\n\n float projectedRadius = length(screenVec);\n\n float lineWidth = 0.0005 * viewport.y;\n float aaRange = 0.0025 * viewport.y;\n float radius = 0.06 * viewport.y;\n float radDiff = abs(projectedRadius - radius) - lineWidth;\n float alpha = 1.0 - clamp(radDiff / 5.0, 0.0, 1.0); \n\n gl_FragColor = vec4(color.rgb, alpha * opacity);\n }\n ",transparent:!0,depthTest:!1,depthWrite:!1,side:e.FrontSide})}dispose(){this.destroyMeshCursor(),this.destroyFocusMarker(),this.destroyDebugMeshes(),this.destroyControlPlane(),this.destroyRenderTargetCopyObjects(),this.destroySplatRendertarget()}}const Zt=new e.Vector3(1,0,0),$t=new e.Vector3(0,1,0),es=new e.Vector3(0,0,1);class ts{constructor(t=new e.Vector3,s=new e.Vector3){this.origin=new e.Vector3,this.direction=new e.Vector3,this.setParameters(t,s)}setParameters(e,t){this.origin.copy(e),this.direction.copy(t).normalize()}boxContainsPoint(e,t,s){return!(t.x<e.min.x-s||t.x>e.max.x+s||t.y<e.min.y-s||t.y>e.max.y+s||t.z<e.min.z-s||t.z>e.max.z+s)}intersectBox=function(){const t=new e.Vector3,s=[],n=[],r=[];return function(e,i){if(n[0]=this.origin.x,n[1]=this.origin.y,n[2]=this.origin.z,r[0]=this.direction.x,r[1]=this.direction.y,r[2]=this.direction.z,this.boxContainsPoint(e,this.origin,1e-4))return i&&(i.origin.copy(this.origin),i.normal.set(0,0,0),i.distance=-1),!0;for(let o=0;o<3;o++){if(0==r[o])continue;const a=0==o?Zt:1==o?$t:es,l=r[o]<0?e.max:e.min;let c=-Math.sign(r[o]);s[0]=0==o?l.x:1==o?l.y:l.z;let h=s[0]-n[o];if(h*c<0){const l=(o+1)%3,d=(o+2)%3;if(s[2]=r[l]/r[o]*h+n[l],s[1]=r[d]/r[o]*h+n[d],t.set(s[o],s[d],s[l]),this.boxContainsPoint(e,t,1e-4))return i&&(i.origin.copy(t),i.normal.copy(a).multiplyScalar(c),i.distance=t.sub(this.origin).length()),!0}}return!1}}();intersectSphere=function(){const t=new e.Vector3;return function(e,s,n){t.copy(e).sub(this.origin);const r=t.dot(this.direction),i=r*r,o=t.dot(t)-i,a=s*s;if(o>a)return!1;const l=Math.sqrt(a-o),c=r-l,h=r+l;if(h<0)return!1;let d=c<0?h:c;return n&&(n.origin.copy(this.origin).addScaledVector(this.direction,d),n.normal.copy(n.origin).sub(e).normalize(),n.distance=d),!0}}()}class ss{constructor(){this.origin=new e.Vector3,this.normal=new e.Vector3,this.distance=0,this.splatIndex=0}set(e,t,s,n){this.origin.copy(e),this.normal.copy(t),this.distance=s,this.splatIndex=n}clone(){const e=new ss;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}const ns=0,rs=1;class is{constructor(e,t,s=!1){this.ray=new ts(e,t),this.raycastAgainstTrueSplatEllipsoid=s}setFromCameraAndScreenPosition=function(){const t=new e.Vector2;return function(e,s,n){if(t.x=s.x/n.x*2-1,t.y=(n.y-s.y)/n.y*2-1,e.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e;else{if(!e.isOrthographicCamera)throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type");this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e}}}();intersectSplatMesh=function(){const t=new e.Matrix4,s=new e.Matrix4,n=new e.Matrix4,r=new ts,i=new e.Vector3;return function(e,o=[]){const a=e.getSplatTree();if(a){for(let l=0;l<a.subTrees.length;l++){const c=a.subTrees[l];s.copy(e.matrixWorld),e.dynamicMode&&(e.getSceneTransform(l,n),s.multiply(n)),t.copy(s).invert(),r.origin.copy(this.ray.origin).applyMatrix4(t),r.direction.copy(this.ray.origin).add(this.ray.direction),r.direction.applyMatrix4(t).sub(r.origin).normalize();const h=[];c.rootNode&&this.castRayAtSplatTreeNode(r,a,c.rootNode,h),h.forEach((e=>{e.origin.applyMatrix4(s),e.normal.applyMatrix4(s).normalize(),e.distance=i.copy(e.origin).sub(this.ray.origin).length()})),o.push(...h)}return o.sort(((e,t)=>e.distance>t.distance?1:-1)),o}}}();castRayAtSplatTreeNode=function(){const t=new e.Vector4,s=new e.Vector3,n=new e.Vector3,r=new e.Quaternion,i=new ss,o=1e-7,a=new e.Vector3(0,0,0),l=new e.Matrix4,c=new e.Matrix4,h=new e.Matrix4,d=new e.Matrix4,p=new e.Matrix4,u=new ts;return function(e,m,A,f=[]){if(e.intersectBox(A.boundingBox)){if(A.data&&A.data.indexes&&A.data.indexes.length>0)for(let g=0;g<A.data.indexes.length;g++){const S=A.data.indexes[g],C=m.splatMesh.getSceneIndexForSplat(S);if(m.splatMesh.getScene(C).visible&&(m.splatMesh.getSplatColor(S,t),m.splatMesh.getSplatCenter(S,s),m.splatMesh.getSplatScaleAndRotation(S,n,r),!(n.x<=o||n.y<=o||m.splatMesh.splatRenderMode===ns&&n.z<=o)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(n.x,n.y,n.z),h.makeRotationFromQuaternion(r);const o=2*Math.log10(t.w);if(l.makeScale(o,o,o),p.copy(l).multiply(h).multiply(c),d.copy(p).invert(),u.origin.copy(e.origin).sub(s).applyMatrix4(d),u.direction.copy(e.origin).add(e.direction).sub(s),u.direction.applyMatrix4(d).sub(u.origin).normalize(),u.intersectSphere(a,1,i)){const e=i.clone();e.splatIndex=S,e.origin.applyMatrix4(p).add(s),f.push(e)}}else{let t=n.x+n.y,r=2;if(m.splatMesh.splatRenderMode===ns&&(t+=n.z,r=3),t/=r,e.intersectSphere(s,t,i)){const e=i.clone();e.splatIndex=S,f.push(e)}}}if(A.children&&A.children.length>0)for(let t of A.children)this.castRayAtSplatTreeNode(e,m,t,f);return f}}}()}class os{static buildVertexShaderBase(e=!1,t=!1,s=0,n=""){let r="\n precision highp float;\n #include <common>\n\n attribute uint splatIndex;\n uniform highp usampler2D centersColorsTexture;\n uniform highp sampler2D sphericalHarmonicsTexture;\n uniform highp sampler2D sphericalHarmonicsTextureR;\n uniform highp sampler2D sphericalHarmonicsTextureG;\n uniform highp sampler2D sphericalHarmonicsTextureB;\n\n uniform highp usampler2D sceneIndexesTexture;\n uniform vec2 sceneIndexesTextureSize;\n uniform int sceneCount;\n ";return t&&(r+=`\n uniform float sceneOpacity[${b.MaxScenes}];\n uniform int sceneVisibility[${b.MaxScenes}];\n `),e&&(r+=`\n uniform highp mat4 transforms[${b.MaxScenes}];\n `),r+=`\n ${n}\n uniform vec2 focal;\n uniform float orthoZoom;\n uniform int orthographicMode;\n uniform int pointCloudModeEnabled;\n uniform float inverseFocalAdjustment;\n uniform vec2 viewport;\n uniform vec2 basisViewport;\n uniform vec2 centersColorsTextureSize;\n uniform int sphericalHarmonicsDegree;\n uniform vec2 sphericalHarmonicsTextureSize;\n uniform int sphericalHarmonics8BitMode;\n uniform int sphericalHarmonicsMultiTextureMode;\n uniform float visibleRegionRadius;\n uniform float visibleRegionFadeStartRadius;\n uniform float firstRenderTime;\n uniform float currentTime;\n uniform int fadeInComplete;\n uniform vec3 sceneCenter;\n uniform float splatScale;\n uniform float sphericalHarmonics8BitCompressionRangeMin[${b.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${b.MaxScenes}];\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n\n mat3 quaternionToRotationMatrix(float x, float y, float z, float w) {\n float s = 1.0 / sqrt(w * w + x * x + y * y + z * z);\n \n return mat3(\n 1. - 2. * (y * y + z * z),\n 2. * (x * y + w * z),\n 2. * (x * z - w * y),\n 2. * (x * y - w * z),\n 1. - 2. * (x * x + z * z),\n 2. * (y * z + w * x),\n 2. * (x * z + w * y),\n 2. * (y * z - w * x),\n 1. - 2. * (x * x + y * y)\n );\n }\n\n const float sqrt8 = sqrt(8.0);\n const float minAlpha = 1.0 / 255.0;\n\n const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));\n const uvec4 shift4 = uvec4(0, 8, 16, 24);\n vec4 uintToRGBAVec (uint u) {\n uvec4 urgba = mask4 & u;\n urgba = urgba >> shift4;\n vec4 rgba = vec4(urgba) * encodeNorm4;\n return rgba;\n }\n\n vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(float(sIndex) * stride) + offset) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n const float SH_C1 = 0.4886025119029199f;\n const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);\n\n void main () {\n\n uint oddOffset = splatIndex & uint(0x00000001);\n uint doubleOddOffset = oddOffset * uint(2);\n bool isEven = oddOffset == uint(0);\n uint nearestEvenIndex = splatIndex - oddOffset;\n float fOddOffset = float(oddOffset);\n\n uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));\n vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));\n\n uint sceneIndex = uint(0);\n if (sceneCount > 1) {\n sceneIndex = texture(sceneIndexesTexture, getDataUV(1, 0, sceneIndexesTextureSize)).r;\n }\n `,t&&(r+="\n float splatOpacityFromScene = sceneOpacity[sceneIndex];\n int sceneVisible = sceneVisibility[sceneIndex];\n if (splatOpacityFromScene <= 0.01 || sceneVisible == 0) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n "),r+=e?"\n mat4 transform = transforms[sceneIndex];\n mat4 transformModelViewMatrix = viewMatrix * transform;\n ":"mat4 transformModelViewMatrix = modelViewMatrix;",r+="\n float sh8BitCompressionRangeMinForScene = sphericalHarmonics8BitCompressionRangeMin[sceneIndex];\n float sh8BitCompressionRangeMaxForScene = sphericalHarmonics8BitCompressionRangeMax[sceneIndex];\n float sh8BitCompressionRangeForScene = sh8BitCompressionRangeMaxForScene - sh8BitCompressionRangeMinForScene;\n float sh8BitCompressionHalfRangeForScene = sh8BitCompressionRangeForScene / 2.0;\n vec3 vec8BitSHShift = vec3(sh8BitCompressionRangeMinForScene);\n\n vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);\n\n vec4 clipCenter = projectionMatrix * viewCenter;\n\n float clip = 1.2 * clipCenter.w;\n if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n\n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n vPosition = position.xy;\n vColor = uintToRGBAVec(sampledCenterColor.r);\n ",s>=1&&(r+=" \n if (sphericalHarmonicsDegree >= 1) {\n ",r+=e?"\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));\n ":"\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n ",r+="\n vec3 sh1;\n vec3 sh2;\n vec3 sh3;\n ",s>=2&&(r+="\n vec3 sh4;\n vec3 sh5;\n vec3 sh6;\n vec3 sh7;\n vec3 sh8;\n "),1===s?r+="\n if (sphericalHarmonicsMultiTextureMode == 0) {\n vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);\n sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;\n sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;\n sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;\n } else {\n vec2 sampledSH01R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH01G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH01B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n sh1 = vec3(sampledSH01R.rg, sampledSH23R.r);\n sh2 = vec3(sampledSH01G.rg, sampledSH23G.r);\n sh3 = vec3(sampledSH01B.rg, sampledSH23B.r);\n }\n ":2===s&&(r+="\n vec4 sampledSH0123;\n vec4 sampledSH4567;\n vec4 sampledSH891011;\n\n vec4 sampledSH0123R;\n vec4 sampledSH0123G;\n vec4 sampledSH0123B;\n\n if (sphericalHarmonicsMultiTextureMode == 0) {\n sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));\n sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));\n sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));\n sh1 = sampledSH0123.rgb;\n sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);\n sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);\n } else {\n sampledSH0123R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sampledSH0123G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sampledSH0123B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sh1 = vec3(sampledSH0123R.rgb);\n sh2 = vec3(sampledSH0123G.rgb);\n sh3 = vec3(sampledSH0123B.rgb);\n }\n "),r+="\n if (sphericalHarmonics8BitMode == 1) {\n sh1 = sh1 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh2 = sh2 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh3 = sh3 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n }\n float x = worldViewDir.x;\n float y = worldViewDir.y;\n float z = worldViewDir.z;\n vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);\n ",s>=2&&(r+="\n if (sphericalHarmonicsDegree >= 2) {\n float xx = x * x;\n float yy = y * y;\n float zz = z * z;\n float xy = x * y;\n float yz = y * z;\n float xz = x * z;\n ",2===s&&(r+="\n if (sphericalHarmonicsMultiTextureMode == 0) {\n vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));\n vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));\n vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));\n sh4 = sampledSH891011.gba;\n sh5 = sampledSH12131415.rgb;\n sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);\n sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);\n sh8 = sampledSH20212223.gba;\n } else {\n vec4 sampledSH4567R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n sh4 = vec3(sampledSH0123R.a, sampledSH4567R.rg);\n sh5 = vec3(sampledSH4567R.ba, sampledSH0123G.a);\n sh6 = vec3(sampledSH4567G.rgb);\n sh7 = vec3(sampledSH4567G.a, sampledSH0123B.a, sampledSH4567B.r);\n sh8 = vec3(sampledSH4567B.gba);\n }\n "),r+="\n if (sphericalHarmonics8BitMode == 1) {\n sh4 = sh4 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh5 = sh5 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh6 = sh6 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh7 = sh7 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh8 = sh8 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n }\n\n vColor.rgb +=\n (SH_C2[0] * xy) * sh4 +\n (SH_C2[1] * yz) * sh5 +\n (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +\n (SH_C2[3] * xz) * sh7 +\n (SH_C2[4] * (xx - yy)) * sh8;\n }\n "),r+="\n\n vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));\n\n }\n\n "),r}static getVertexShaderFadeIn(){return"\n if (fadeInComplete == 0) {\n float opacityAdjust = 1.0;\n float centerDist = length(splatCenter - sceneCenter);\n float renderTime = max(currentTime - firstRenderTime, 0.0);\n\n float fadeDistance = 0.75;\n float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);\n distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +\n (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *\n distanceLoadFadeInFactor;\n opacityAdjust *= distanceLoadFadeInFactor;\n vColor.a *= opacityAdjust;\n }\n "}static getUniforms(t=!1,s=!1,n=0,r=1,i=!1){const o={sceneCenter:{type:"v3",value:new e.Vector3},fadeInComplete:{type:"i",value:0},orthographicMode:{type:"i",value:0},visibleRegionFadeStartRadius:{type:"f",value:0},visibleRegionRadius:{type:"f",value:0},currentTime:{type:"f",value:0},firstRenderTime:{type:"f",value:0},centersColorsTexture:{type:"t",value:null},sphericalHarmonicsTexture:{type:"t",value:null},sphericalHarmonicsTextureR:{type:"t",value:null},sphericalHarmonicsTextureG:{type:"t",value:null},sphericalHarmonicsTextureB:{type:"t",value:null},sphericalHarmonics8BitCompressionRangeMin:{type:"f",value:[]},sphericalHarmonics8BitCompressionRangeMax:{type:"f",value:[]},focal:{type:"v2",value:new e.Vector2},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new e.Vector2},basisViewport:{type:"v2",value:new e.Vector2},debugColor:{type:"v3",value:new e.Color},centersColorsTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sphericalHarmonicsDegree:{type:"i",value:n},sphericalHarmonicsTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:r},pointCloudModeEnabled:{type:"i",value:i?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sceneCount:{type:"i",value:1}};for(let e=0;e<b.MaxScenes;e++)o.sphericalHarmonics8BitCompressionRangeMin.value.push(-b.SphericalHarmonics8BitCompressionRange/2),o.sphericalHarmonics8BitCompressionRangeMax.value.push(b.SphericalHarmonics8BitCompressionRange/2);if(s){const e=[];for(let t=0;t<b.MaxScenes;t++)e.push(1);o.sceneOpacity={type:"f",value:e};const t=[];for(let e=0;e<b.MaxScenes;e++)t.push(1);o.sceneVisibility={type:"i",value:t}}if(t){const t=[];for(let s=0;s<b.MaxScenes;s++)t.push(new e.Matrix4);o.transforms={type:"mat4",value:t}}return o}}class as{static build(t=!1,s=!1,n=!1,r=2048,i=1,o=!1,a=0,l=.3){let c=os.buildVertexShaderBase(t,s,a,"\n uniform vec2 covariancesTextureSize;\n uniform highp sampler2D covariancesTexture;\n uniform highp usampler2D covariancesTextureHalfFloat;\n uniform int covariancesAreHalfFloat;\n\n void fromCovarianceHalfFloatV4(uvec4 val, out vec4 first, out vec4 second) {\n vec2 r = unpackHalf2x16(val.r);\n vec2 g = unpackHalf2x16(val.g);\n vec2 b = unpackHalf2x16(val.b);\n\n first = vec4(r.x, r.y, g.x, g.y);\n second = vec4(b.x, b.y, 0.0, 0.0);\n }\n ");c+=as.buildVertexShaderProjection(n,s,r,l);const h=as.buildFragmentShader(),d=os.getUniforms(t,s,a,i,o);d.covariancesTextureSize={type:"v2",value:new e.Vector2(1024,1024)},d.covariancesTexture={type:"t",value:null},d.covariancesTextureHalfFloat={type:"t",value:null},d.covariancesAreHalfFloat={type:"i",value:0};return new e.ShaderMaterial({uniforms:d,vertexShader:c,fragmentShader:h,transparent:!0,alphaTest:1,blending:e.NormalBlending,depthTest:!0,depthWrite:!1,side:e.DoubleSide})}static buildVertexShaderProjection(e,t,s,n){let r="\n\n vec4 sampledCovarianceA;\n vec4 sampledCovarianceB;\n vec3 cov3D_M11_M12_M13;\n vec3 cov3D_M22_M23_M33;\n if (covariancesAreHalfFloat == 0) {\n sampledCovarianceA = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset,\n covariancesTextureSize));\n sampledCovarianceB = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1),\n covariancesTextureSize));\n\n cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;\n cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceB.gba) * fOddOffset;\n } else {\n uvec4 sampledCovarianceU = texture(covariancesTextureHalfFloat, getDataUV(1, 0, covariancesTextureSize));\n fromCovarianceHalfFloatV4(sampledCovarianceU, sampledCovarianceA, sampledCovarianceB);\n cov3D_M11_M12_M13 = sampledCovarianceA.rgb;\n cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg);\n }\n \n // Construct the 3D covariance matrix\n mat3 Vrk = mat3(\n cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,\n cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,\n cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z\n );\n\n mat3 J;\n if (orthographicMode == 1) {\n // Since the projection is linear, we don't need an approximation\n J = transpose(mat3(orthoZoom, 0.0, 0.0,\n 0.0, orthoZoom, 0.0,\n 0.0, 0.0, 0.0));\n } else {\n // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result.\n float s = 1.0 / (viewCenter.z * viewCenter.z);\n J = mat3(\n focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,\n 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,\n 0., 0., 0.\n );\n }\n\n // Concatenate the projection approximation with the model-view transformation\n mat3 W = transpose(mat3(transformModelViewMatrix));\n mat3 T = W * J;\n\n // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix\n mat3 cov2Dm = transpose(T) * Vrk * T;\n ";return r+=e?`\n float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n cov2Dm[0][0] += ${n};\n cov2Dm[1][1] += ${n};\n float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n vColor.a *= sqrt(max(detOrig / detBlur, 0.0));\n if (vColor.a < minAlpha) return;\n `:`\n cov2Dm[0][0] += ${n};\n cov2Dm[1][1] += ${n};\n `,r+=`\n\n // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because\n // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],\n // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't\n // need cov2Dm[1][0] because it is a symetric matrix.\n vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);\n\n // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix\n // so that we can determine the 2D basis for the splat. This is done using the method described\n // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html\n // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat\n // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * sqrt(eigen-value)), which is\n // equal to scaling them by sqrt(8) standard deviations.\n //\n // This is a different approach than in the original work at INRIA. In that work they compute the\n // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle\n // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0\n // times the square root of the maximum eigen-value, or 3 standard deviations. They then use the inverse\n // 2D covariance matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by\n // calculating the full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity\n float a = cov2Dv.x;\n float d = cov2Dv.z;\n float b = cov2Dv.y;\n float D = a * d - b * b;\n float trace = a + d;\n float traceOver2 = 0.5 * trace;\n float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));\n float eigenValue1 = traceOver2 + term2;\n float eigenValue2 = traceOver2 - term2;\n\n if (pointCloudModeEnabled == 1) {\n eigenValue1 = eigenValue2 = 0.2;\n }\n\n if (eigenValue2 <= 0.0) return;\n\n vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));\n // since the eigen vectors are orthogonal, we derive the second one from the first\n vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);\n\n // We use sqrt(8) standard deviations instead of 3 to eliminate more of the splat with a very low opacity.\n vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ${parseInt(s)}.0);\n vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ${parseInt(s)}.0);\n `,t&&(r+="\n vColor.a *= splatOpacityFromScene;\n "),r+="\n vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *\n basisViewport * 2.0 * inverseFocalAdjustment;\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n // Scale the position data we send to the fragment shader\n vPosition *= sqrt8;\n ",r+=os.getVertexShaderFadeIn(),r+="}",r}static buildFragmentShader(){let e="\n precision highp float;\n #include <common>\n \n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n ";return e+="\n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n if (A > 8.0) discard;\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp(-0.5 * A) * vColor.a;\n\n gl_FragColor = vec4(color.rgb, opacity);\n }\n ","\n precision highp float;\n #include <common>\n \n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n \n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n if (A > 8.0) discard;\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp(-0.5 * A) * vColor.a;\n\n gl_FragColor = vec4(color.rgb, opacity);\n }\n "}}class ls{static build(t=!1,s=!1,n=1,r=!1,i=0){let o=os.buildVertexShaderBase(t,s,i,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");o+=ls.buildVertexShaderProjection();const a=ls.buildFragmentShader(),l=os.getUniforms(t,s,i,n,r);l.scaleRotationsTexture={type:"t",value:null},l.scaleRotationsTextureSize={type:"v2",value:new e.Vector2(1024,1024)};return new e.ShaderMaterial({uniforms:l,vertexShader:o,fragmentShader:a,transparent:!0,alphaTest:1,blending:e.NormalBlending,depthTest:!0,depthWrite:!1,side:e.DoubleSide})}static buildVertexShaderProjection(){let e="\n\n vec4 scaleRotationA = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,\n oddOffset, scaleRotationsTextureSize));\n vec4 scaleRotationB = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,\n oddOffset + uint(1), scaleRotationsTextureSize));\n\n vec3 scaleRotation123 = vec3(scaleRotationA.rgb) * (1.0 - fOddOffset) +\n vec3(scaleRotationA.ba, scaleRotationB.r) * fOddOffset;\n vec3 scaleRotation456 = vec3(scaleRotationA.a, scaleRotationB.rg) * (1.0 - fOddOffset) +\n vec3(scaleRotationB.gba) * fOddOffset;\n\n float missingW = sqrt(1.0 - scaleRotation456.x * scaleRotation456.x - scaleRotation456.y *\n scaleRotation456.y - scaleRotation456.z * scaleRotation456.z);\n mat3 R = quaternionToRotationMatrix(scaleRotation456.r, scaleRotation456.g, scaleRotation456.b, missingW);\n mat3 S = mat3(scaleRotation123.r, 0.0, 0.0,\n 0.0, scaleRotation123.g, 0.0,\n 0.0, 0.0, scaleRotation123.b);\n \n mat3 L = R * S;\n\n mat3x4 splat2World = mat3x4(vec4(L[0], 0.0),\n vec4(L[1], 0.0),\n vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));\n\n mat4 world2ndc = transpose(projectionMatrix * transformModelViewMatrix);\n\n mat3x4 ndc2pix = mat3x4(vec4(viewport.x / 2.0, 0.0, 0.0, (viewport.x - 1.0) / 2.0),\n vec4(0.0, viewport.y / 2.0, 0.0, (viewport.y - 1.0) / 2.0),\n vec4(0.0, 0.0, 0.0, 1.0));\n\n mat3 T = transpose(splat2World) * world2ndc * ndc2pix;\n vec3 normal = vec3(viewMatrix * vec4(L[0][2], L[1][2], L[2][2], 0.0));\n ";return e+="\n\n mat4 splat2World4 = mat4(vec4(L[0], 0.0),\n vec4(L[1], 0.0),\n vec4(L[2], 0.0),\n vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));\n\n mat4 Tt = transpose(transpose(splat2World4) * world2ndc);\n\n vec4 tempPoint1 = Tt * vec4(1.0, 0.0, 0.0, 1.0);\n tempPoint1 /= tempPoint1.w;\n\n vec4 tempPoint2 = Tt * vec4(0.0, 1.0, 0.0, 1.0);\n tempPoint2 /= tempPoint2.w;\n\n vec4 center = Tt * vec4(0.0, 0.0, 0.0, 1.0);\n center /= center.w;\n\n vec2 basisVector1 = tempPoint1.xy - center.xy;\n vec2 basisVector2 = tempPoint2.xy - center.xy;\n\n vec2 basisVector1Screen = basisVector1 * 0.5 * viewport;\n vec2 basisVector2Screen = basisVector2 * 0.5 * viewport;\n\n const float minPix = 1.;\n if (length(basisVector1Screen) < minPix || length(basisVector2Screen) < minPix) {\n \n vec3 T0 = vec3(T[0][0], T[0][1], T[0][2]);\n vec3 T1 = vec3(T[1][0], T[1][1], T[1][2]);\n vec3 T3 = vec3(T[2][0], T[2][1], T[2][2]);\n\n vec3 tempPoint = vec3(1.0, 1.0, -1.0);\n float distance = (T3.x * T3.x * tempPoint.x) + (T3.y * T3.y * tempPoint.y) + (T3.z * T3.z * tempPoint.z);\n vec3 f = (1.0 / distance) * tempPoint;\n if (abs(distance) < 0.00001) return;\n\n float pointImageX = (T0.x * T3.x * f.x) + (T0.y * T3.y * f.y) + (T0.z * T3.z * f.z);\n float pointImageY = (T1.x * T3.x * f.x) + (T1.y * T3.y * f.y) + (T1.z * T3.z * f.z);\n vec2 pointImage = vec2(pointImageX, pointImageY);\n\n float tempX = (T0.x * T0.x * f.x) + (T0.y * T0.y * f.y) + (T0.z * T0.z * f.z);\n float tempY = (T1.x * T1.x * f.x) + (T1.y * T1.y * f.y) + (T1.z * T1.z * f.z);\n vec2 temp = vec2(tempX, tempY);\n\n vec2 halfExtend = pointImage * pointImage - temp;\n vec2 extent = sqrt(max(vec2(0.0001), halfExtend));\n float radius = max(extent.x, extent.y);\n\n vec2 ndcOffset = ((position.xy * radius * 3.0) * basisViewport * 2.0);\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n vT = T;\n vQuadCenter = pointImage;\n vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;\n \n } else {\n vec2 ndcOffset = vec2(position.x * basisVector1 + position.y * basisVector2) * 3.0 * inverseFocalAdjustment;\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n vT = T;\n vQuadCenter = center.xy;\n vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;\n }\n ",e+=os.getVertexShaderFadeIn(),e+="}",e}static buildFragmentShader(){return"\n precision highp float;\n #include <common>\n\n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n\n void main () {\n\n const float FilterInvSquare = 2.0;\n const float near_n = 0.2;\n const float T = 1.0;\n\n vec2 xy = vQuadCenter;\n vec3 Tu = vT[0];\n vec3 Tv = vT[1];\n vec3 Tw = vT[2];\n vec3 k = vFragCoord.x * Tw - Tu;\n vec3 l = vFragCoord.y * Tw - Tv;\n vec3 p = cross(k, l);\n if (p.z == 0.0) discard;\n vec2 s = vec2(p.x / p.z, p.y / p.z);\n float rho3d = (s.x * s.x + s.y * s.y); \n vec2 d = vec2(xy.x - vFragCoord.x, xy.y - vFragCoord.y);\n float rho2d = FilterInvSquare * (d.x * d.x + d.y * d.y); \n\n // compute intersection and depth\n float rho = min(rho3d, rho2d);\n float depth = (rho3d <= rho2d) ? (s.x * Tw.x + s.y * Tw.y) + Tw.z : Tw.z; \n if (depth < near_n) discard;\n // vec4 nor_o = collected_normal_opacity[j];\n // float normal[3] = {nor_o.x, nor_o.y, nor_o.z};\n float opa = vColor.a;\n\n float power = -0.5f * rho;\n if (power > 0.0f) discard;\n\n // Eq. (2) from 3D Gaussian splatting paper.\n // Obtain alpha by multiplying with Gaussian opacity\n // and its exponential falloff from mean.\n // Avoid numerical instabilities (see paper appendix). \n float alpha = min(0.99f, opa * exp(power));\n if (alpha < 1.0f / 255.0f) discard;\n float test_T = T * (1.0 - alpha);\n if (test_T < 0.0001)discard;\n\n float w = alpha * T;\n gl_FragColor = vec4(vColor.rgb, w);\n }\n "}}class cs{static build(t){const s=new e.BufferGeometry;s.setIndex([0,1,2,0,2,3]);const n=new Float32Array(12),r=new e.BufferAttribute(n,3);s.setAttribute("position",r),r.setXYZ(0,-1,-1,0),r.setXYZ(1,-1,1,0),r.setXYZ(2,1,1,0),r.setXYZ(3,1,-1,0),r.needsUpdate=!0;const i=(new e.InstancedBufferGeometry).copy(s),o=new Uint32Array(t),a=new e.InstancedBufferAttribute(o,1,!1);return a.setUsage(e.DynamicDrawUsage),i.setAttribute("splatIndex",a),i.instanceCount=0,i}}class hs extends e.Object3D{constructor(t,s=new e.Vector3,n=new e.Quaternion,r=new e.Vector3(1,1,1),i=1,o=1,a=!0){super(),this.splatBuffer=t,this.position.copy(s),this.quaternion.copy(n),this.scale.copy(r),this.transform=new e.Matrix4,this.minimumAlpha=i,this.opacity=o,this.visible=a}copyTransformData(e){this.position.copy(e.position),this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.transform.copy(e.transform)}updateTransform(e){e?(this.matrixWorldAutoUpdate&&this.updateWorldMatrix(!0,!1),this.transform.copy(this.matrixWorld)):(this.matrixAutoUpdate&&this.updateMatrix(),this.transform.copy(this.matrix))}}class ds{static idGen=0;constructor(t,s,n,r){this.min=(new e.Vector3).copy(t),this.max=(new e.Vector3).copy(s),this.boundingBox=new e.Box3(this.min,this.max),this.center=(new e.Vector3).copy(this.max).sub(this.min).multiplyScalar(.5).add(this.min),this.depth=n,this.children=[],this.data=null,this.id=r||ds.idGen++}}class ps{constructor(t,s){this.maxDepth=t,this.maxCentersPerNode=s,this.sceneDimensions=new e.Vector3,this.sceneMin=new e.Vector3,this.sceneMax=new e.Vector3,this.rootNode=null,this.nodesWithIndexes=[],this.splatMesh=null}static convertWorkerSubTreeNode(t){const s=(new e.Vector3).fromArray(t.min),n=(new e.Vector3).fromArray(t.max),r=new ds(s,n,t.depth,t.id);if(t.data.indexes){r.data={indexes:[]};for(let e of t.data.indexes)r.data.indexes.push(e)}if(t.children)for(let e of t.children)r.children.push(ps.convertWorkerSubTreeNode(e));return r}static convertWorkerSubTree(t,s){const n=new ps(t.maxDepth,t.maxCentersPerNode);n.sceneMin=(new e.Vector3).fromArray(t.sceneMin),n.sceneMax=(new e.Vector3).fromArray(t.sceneMax),n.splatMesh=s,n.rootNode=ps.convertWorkerSubTreeNode(t.rootNode);const r=(e,t)=>{0===e.children.length&&t(e);for(let s of e.children)r(s,t)};return n.nodesWithIndexes=[],r(n.rootNode,(e=>{e.data&&e.data.indexes&&e.data.indexes.length>0&&n.nodesWithIndexes.push(e)})),n}}function us(e){let t=0;class s{constructor(e,t){this.min=[e[0],e[1],e[2]],this.max=[t[0],t[1],t[2]]}containsPoint(e){return e[0]>=this.min[0]&&e[0]<=this.max[0]&&e[1]>=this.min[1]&&e[1]<=this.max[1]&&e[2]>=this.min[2]&&e[2]<=this.max[2]}}class n{constructor(e,t){this.maxDepth=e,this.maxCentersPerNode=t,this.sceneDimensions=[],this.sceneMin=[],this.sceneMax=[],this.rootNode=null,this.addedIndexes={},this.nodesWithIndexes=[],this.splatMesh=null,this.disposed=!1}}class r{constructor(e,s,n,r){this.min=[e[0],e[1],e[2]],this.max=[s[0],s[1],s[2]],this.center=[.5*(s[0]-e[0])+e[0],.5*(s[1]-e[1])+e[1],.5*(s[2]-e[2])+e[2]],this.depth=n,this.children=[],this.data=null,this.id=r||t++}}processSplatTreeNode=function(e,t,n,i){const o=t.data.indexes.length;if(o<e.maxCentersPerNode||t.depth>e.maxDepth){const s=[];for(let n=0;n<t.data.indexes.length;n++)e.addedIndexes[t.data.indexes[n]]||(s.push(t.data.indexes[n]),e.addedIndexes[t.data.indexes[n]]=!0);return t.data.indexes=s,t.data.indexes.sort(((e,t)=>e>t?1:-1)),void e.nodesWithIndexes.push(t)}const a=[t.max[0]-t.min[0],t.max[1]-t.min[1],t.max[2]-t.min[2]],l=[.5*a[0],.5*a[1],.5*a[2]],c=[t.min[0]+l[0],t.min[1]+l[1],t.min[2]+l[2]],h=[new s([c[0]-l[0],c[1],c[2]-l[2]],[c[0],c[1]+l[1],c[2]]),new s([c[0],c[1],c[2]-l[2]],[c[0]+l[0],c[1]+l[1],c[2]]),new s([c[0],c[1],c[2]],[c[0]+l[0],c[1]+l[1],c[2]+l[2]]),new s([c[0]-l[0],c[1],c[2]],[c[0],c[1]+l[1],c[2]+l[2]]),new s([c[0]-l[0],c[1]-l[1],c[2]-l[2]],[c[0],c[1],c[2]]),new s([c[0],c[1]-l[1],c[2]-l[2]],[c[0]+l[0],c[1],c[2]]),new s([c[0],c[1]-l[1],c[2]],[c[0]+l[0],c[1],c[2]+l[2]]),new s([c[0]-l[0],c[1]-l[1],c[2]],[c[0],c[1],c[2]+l[2]])],d=[];for(let e=0;e<h.length;e++)d[e]=[];const p=[0,0,0];for(let e=0;e<o;e++){const s=t.data.indexes[e],r=n[s];p[0]=i[r],p[1]=i[r+1],p[2]=i[r+2];for(let e=0;e<h.length;e++)h[e].containsPoint(p)&&d[e].push(s)}for(let e=0;e<h.length;e++){const s=new r(h[e].min,h[e].max,t.depth+1);s.data={indexes:d[e]},t.children.push(s)}t.data={};for(let s of t.children)processSplatTreeNode(e,s,n,i)};const i=(e,t,s)=>{const i=[0,0,0],o=[0,0,0],a=[],l=Math.floor(e.length/4);for(let t=0;t<l;t++){const s=4*t,n=e[s],r=e[s+1],l=e[s+2],c=Math.round(e[s+3]);(0===t||n<i[0])&&(i[0]=n),(0===t||n>o[0])&&(o[0]=n),(0===t||r<i[1])&&(i[1]=r),(0===t||r>o[1])&&(o[1]=r),(0===t||l<i[2])&&(i[2]=l),(0===t||l>o[2])&&(o[2]=l),a.push(c)}const c=new n(t,s);return c.sceneMin=i,c.sceneMax=o,c.rootNode=new r(c.sceneMin,c.sceneMax,0),c.rootNode.data={indexes:a},c};e.onmessage=t=>{t.data.process&&function(t,s,n){const r=[];for(let e of t){const t=Math.floor(e.length/4);for(let s=0;s<t;s++){const t=4*s;r[Math.round(e[t+3])]=t}}const o=[];for(let e of t){const t=i(e,s,n);o.push(t),processSplatTreeNode(t,t.rootNode,r,e)}e.postMessage({subTrees:o})}(t.data.process.centers,t.data.process.maxDepth,t.data.process.maxCentersPerNode)}}class ms{constructor(e,t){this.maxDepth=e,this.maxCentersPerNode=t,this.subTrees=[],this.splatMesh=null}dispose(){this.diposeSplatTreeWorker(),this.disposed=!0}diposeSplatTreeWorker(){this.splatTreeWorker&&this.splatTreeWorker.terminate(),this.splatTreeWorker=null}processSplatMesh=function(t,s=(()=>!0),n,r){this.splatTreeWorker||(this.splatTreeWorker=new Worker(URL.createObjectURL(new Blob(["(",us.toString(),")(self)"],{type:"application/javascript"})))),this.splatMesh=t,this.subTrees=[];const i=new e.Vector3,o=(e,n)=>{const r=new Float32Array(4*n);let o=0;for(let a=0;a<n;a++){const n=a+e;if(s(n)){t.getSplatCenter(n,i);const e=4*o;r[e]=i.x,r[e+1]=i.y,r[e+2]=i.z,r[e+3]=n,o++}}return r};return new Promise((e=>{const s=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),e(),!0);n&&n(!1),S((()=>{if(s())return;const i=[];if(t.dynamicMode){let e=0;for(let s=0;s<t.scenes.length;s++){const n=t.getScene(s).splatBuffer.getSplatCount(),r=o(e,n);i.push(r),e+=n}}else{const e=o(0,t.getSplatCount());i.push(e)}this.splatTreeWorker.onmessage=n=>{s()||n.data.subTrees&&(r&&r(!1),S((()=>{if(!s()){for(let e of n.data.subTrees){const s=ps.convertWorkerSubTree(e,t);this.subTrees.push(s)}this.diposeSplatTreeWorker(),r&&r(!0),S((()=>{e()}))}})))},S((()=>{if(s())return;n&&n(!0);const e=i.map((e=>e.buffer));!function(e,t,s,n,r){e.postMessage({process:{centers:t,maxDepth:n,maxCentersPerNode:r}},s)}(this.splatTreeWorker,i,e,this.maxDepth,this.maxCentersPerNode)}))}))}))};countLeaves(){let e=0;return this.visitLeaves((()=>{e++})),e}visitLeaves(e){const t=(e,s)=>{0===e.children.length&&s(e);for(let n of e.children)t(n,s)};for(let s of this.subTrees)t(s.rootNode,e)}}function As(e){const t={};function s(s){if(void 0!==t[s])return t[s];let n;switch(s){case"WEBGL_depth_texture":n=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=e.getExtension(s)}return t[s]=n,n}return{has:function(e){return null!==s(e)},init:function(e){e.isWebGL2?(s("EXT_color_buffer_float"),s("WEBGL_clip_cull_distance")):(s("WEBGL_depth_texture"),s("OES_texture_float"),s("OES_texture_half_float"),s("OES_texture_half_float_linear"),s("OES_standard_derivatives"),s("OES_element_index_uint"),s("OES_vertex_array_object"),s("ANGLE_instanced_arrays")),s("OES_texture_float_linear"),s("EXT_color_buffer_half_float"),s("WEBGL_multisampled_render_to_texture")},get:function(e){const t=s(e);return null===t&&console.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function fs(e,t,s){let n;function r(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const i="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let o=void 0!==s.precision?s.precision:"highp";const a=r(o);a!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",a,"instead."),o=a);const l=i||t.has("WEBGL_draw_buffers"),c=!0===s.logarithmicDepthBuffer,h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=e.getParameter(e.MAX_TEXTURE_SIZE),u=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),A=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),f=e.getParameter(e.MAX_VARYING_VECTORS),g=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),S=d>0,C=i||t.has("OES_texture_float");return{isWebGL2:i,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==n)return n;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");n=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n},getMaxPrecision:r,precision:o,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:d,maxTextureSize:p,maxCubemapSize:u,maxAttributes:m,maxVertexUniforms:A,maxVaryings:f,maxFragmentUniforms:g,vertexTextures:S,floatFragmentTextures:C,floatVertexTextures:S&&C,maxSamples:i?e.getParameter(e.MAX_SAMPLES):0}}const gs=0,Ss=2,Cs=0,ys=3,xs=new e.BufferGeometry,vs=new e.MeshBasicMaterial,Is=16777216;class Bs extends e.Mesh{constructor(t=ns,s=!1,n=!1,r=!1,i=1,o=!0,a=!1,l=!1,c=1024,h=Cs,d=0,p=1,u=.3){super(xs,vs),this.renderer=void 0,this.splatRenderMode=t,this.dynamicMode=s,this.enableOptionalEffects=n,this.halfPrecisionCovariancesOnGPU=r,this.devicePixelRatio=i,this.enableDistancesComputationOnGPU=o,this.integerBasedDistancesComputation=a,this.antialiased=l,this.kernel2DSize=u,this.maxScreenSpaceSplatSize=c,this.logLevel=h,this.sphericalHarmonicsDegree=d,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=p,this.scenes=[],this.splatTree=null,this.baseSplatTree=null,this.splatDataTextures={},this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new e.Box3,this.calculatedSceneCenter=new e.Vector3,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!1,this.lastRenderer=null,this.visible=!1}static buildScenes(t,s,n){const r=[];r.length=s.length;for(let i=0;i<s.length;i++){const o=s[i],a=n[i]||{};let l=a.position||[0,0,0],c=a.rotation||[0,0,0,1],h=a.scale||[1,1,1];const d=(new e.Vector3).fromArray(l),p=(new e.Quaternion).fromArray(c),u=(new e.Vector3).fromArray(h),m=Bs.createScene(o,d,p,u,a.splatAlphaRemovalThreshold||1,a.opacity,a.visible);t.add(m),r[i]=m}return r}static createScene(e,t,s,n,r,i=1,o=!0){return new hs(e,t,s,n,r,i,o)}static buildSplatIndexMaps(e){const t=[],s=[];let n=0;for(let r=0;r<e.length;r++){const i=e[r].getMaxSplatCount();for(let e=0;e<i;e++)t[n]=e,s[n]=r,n++}return{localSplatIndexMap:t,sceneIndexMap:s}}buildSplatTree=function(t=[],s,n){return new Promise((r=>{this.disposeSplatTree(),this.baseSplatTree=new ms(8,1e3);const i=performance.now(),o=new e.Vector4;this.baseSplatTree.processSplatMesh(this,(e=>{this.getSplatColor(e,o);const s=this.getSceneIndexForSplat(e),n=t[s]||1;return o.w>=n}),s,n).then((()=>{const e=performance.now()-i;if(this.logLevel>=ys&&console.log("SplatTree build: "+e+" ms"),this.disposed)r();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let e=0,t=0,s=0;this.splatTree.visitLeaves((n=>{const r=n.data.indexes.length;r>0&&(t+=r,s++,e++)})),this.logLevel>=ys&&(console.log(`SplatTree leaves: ${this.splatTree.countLeaves()}`),console.log(`SplatTree leaves with splats:${e}`),t/=s,console.log(`Avg splat count per node: ${t}`),console.log(`Total splat count: ${this.getSplatCount()}`)),r()}}))}))};build(t,s,n=!0,r=!1,i,o,a=!0){this.sceneOptions=s,this.finalBuild=r;const l=Bs.getTotalMaxSplatCountForSplatBuffers(t),c=Bs.buildScenes(this,t,s);if(n)for(let e=0;e<this.scenes.length&&e<c.length;e++){const t=c[e],s=this.getScene(e);t.copyTransformData(s)}this.scenes=c;let h=3;for(let e of t){const t=e.getMinSphericalHarmonicsDegree();t<h&&(h=t)}this.minSphericalHarmonicsDegree=Math.min(h,this.sphericalHarmonicsDegree);let d=!1;if(t.length!==this.lastBuildScenes.length)d=!0;else for(let e=0;e<t.length;e++){if(t[e]!==this.lastBuildScenes[e].splatBuffer){d=!0;break}}let p=!0;if((1!==this.scenes.length||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==l||d)&&(p=!1),!p){this.boundingBox=new e.Box3,a||(this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.firstRenderTime=-1),this.lastBuildScenes=[],this.lastBuildSplatCount=0,this.lastBuildMaxSplatCount=0,this.disposeMeshData(),this.geometry=cs.build(l),this.splatRenderMode===ns?this.material=as.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize):this.material=ls.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const s=Bs.buildSplatIndexMaps(t);this.globalSplatIndexToLocalSplatIndexMap=s.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=s.sceneIndexMap}const u=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();const m=this.refreshGPUDataFromSplatBuffers(p);for(let e=0;e<this.scenes.length;e++)this.lastBuildScenes[e]=this.scenes[e];return this.lastBuildSplatCount=u,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,r&&this.scenes.length>0&&this.buildSplatTree(s.map((e=>e.splatAlphaRemovalThreshold||1)),i,o).then((()=>{this.onSplatTreeReadyCallback&&this.onSplatTreeReadyCallback(this.splatTree),this.onSplatTreeReadyCallback=null})),this.visible=this.scenes.length>0,m}freeIntermediateSplatData(){const e=e=>{delete e.source.data,delete e.image,e.onUpdate=null};delete this.splatDataTextures.baseData.covariances,delete this.splatDataTextures.baseData.centers,delete this.splatDataTextures.baseData.colors,delete this.splatDataTextures.baseData.sphericalHarmonics,delete this.splatDataTextures.centerColors.data,delete this.splatDataTextures.covariances.data,this.splatDataTextures.sphericalHarmonics&&delete this.splatDataTextures.sphericalHarmonics.data,this.splatDataTextures.sceneIndexes&&delete this.splatDataTextures.sceneIndexes.data,this.splatDataTextures.centerColors.texture.needsUpdate=!0,this.splatDataTextures.centerColors.texture.onUpdate=()=>{e(this.splatDataTextures.centerColors.texture)},this.splatDataTextures.covariances.texture.needsUpdate=!0,this.splatDataTextures.covariances.texture.onUpdate=()=>{e(this.splatDataTextures.covariances.texture)},this.splatDataTextures.sphericalHarmonics&&(this.splatDataTextures.sphericalHarmonics.texture?(this.splatDataTextures.sphericalHarmonics.texture.needsUpdate=!0,this.splatDataTextures.sphericalHarmonics.texture.onUpdate=()=>{e(this.splatDataTextures.sphericalHarmonics.texture)}):this.splatDataTextures.sphericalHarmonics.textures.forEach((t=>{t.needsUpdate=!0,t.onUpdate=()=>{e(t)}}))),this.splatDataTextures.sceneIndexes&&(this.splatDataTextures.sceneIndexes.texture.needsUpdate=!0,this.splatDataTextures.sceneIndexes.texture.onUpdate=()=>{e(this.splatDataTextures.sceneIndexes.texture)})}dispose(){this.disposeMeshData(),this.disposeTextures(),this.disposeSplatTree(),this.enableDistancesComputationOnGPU&&(this.computeDistancesOnGPUSyncTimeout&&(clearTimeout(this.computeDistancesOnGPUSyncTimeout),this.computeDistancesOnGPUSyncTimeout=null),this.disposeDistancesComputationGPUResources()),this.scenes=[],this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.renderer=null,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new e.Box3,this.calculatedSceneCenter=new e.Vector3,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!0,this.lastRenderer=null,this.visible=!1}disposeMeshData(){this.geometry&&this.geometry!==xs&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}disposeTextures(){for(let e in this.splatDataTextures)if(this.splatDataTextures.hasOwnProperty(e)){const t=this.splatDataTextures[e];t.texture&&(t.texture.dispose(),t.texture=null)}this.splatDataTextures=null}disposeSplatTree(){this.splatTree&&(this.splatTree.dispose(),this.splatTree=null),this.baseSplatTree&&(this.baseSplatTree.dispose(),this.baseSplatTree=null)}getSplatTree(){return this.splatTree}onSplatTreeReady(e){this.onSplatTreeReadyCallback=e}getDataForDistancesComputation(e,t){return{centers:this.integerBasedDistancesComputation?this.getIntegerCenters(e,t,!0):this.getFloatCenters(e,t,!0),sceneIndexes:this.getSceneIndexes(e,t)}}refreshGPUDataFromSplatBuffers(e){const t=this.getSplatCount(!0);this.refreshDataTexturesFromSplatBuffers(e);const s=e?this.lastBuildSplatCount:0,{centers:n,sceneIndexes:r}=this.getDataForDistancesComputation(s,t-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(n,r,e),{from:s,to:t-1,count:t-s,centers:n,sceneIndexes:r}}refreshGPUBuffersForDistancesComputation(e,t,s=!1){const n=s?this.lastBuildSplatCount:0;this.updateGPUCentersBufferForDistancesComputation(s,e,n),this.updateGPUTransformIndexesBufferForDistancesComputation(s,t,n)}refreshDataTexturesFromSplatBuffers(e){const t=this.getSplatCount(!0),s=this.lastBuildSplatCount,n=t-1;e?this.updateBaseDataFromSplatBuffers(s,n):(this.setupDataTextures(),this.updateBaseDataFromSplatBuffers()),this.updateDataTexturesFromBaseData(s,n),this.updateVisibleRegion(e)}setupDataTextures(){const t=this.getMaxSplatCount(),s=this.getSplatCount(!0);this.disposeTextures();const n=(s,n)=>{const r=new e.Vector2(4096,1024);for(;r.x*r.y*s<t*n;)r.y*=2;return r},r=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:n(t,6)}};let i=this.getTargetCovarianceCompressionLevel();const o=this.getTargetSphericalHarmonicsCompressionLevel();let a,l,c;if(this.splatRenderMode===ns){const e=r(i);e.texSize.x*e.texSize.y>Is&&0===i&&(i=1),a=new Float32Array(6*t)}else l=new Float32Array(3*t),c=new Float32Array(4*t);const h=new Float32Array(3*t),d=new Uint8Array(4*t);let p=Float32Array;1===o?p=Uint16Array:2===o&&(p=Uint8Array);const u=C(this.minSphericalHarmonicsDegree),m=this.minSphericalHarmonicsDegree?new p(t*u):void 0,A=n(4,4),f=new Uint32Array(A.x*A.y*4);Bs.updateCenterColorsPaddedData(0,s-1,h,d,f);const g=new e.DataTexture(f,A.x,A.y,e.RGBAIntegerFormat,e.UnsignedIntType);if(g.internalFormat="RGBA32UI",g.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=g,this.material.uniforms.centersColorsTextureSize.value.copy(A),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:a,scales:l,rotations:c,centers:h,colors:d,sphericalHarmonics:m},centerColors:{data:f,texture:g,size:A}},this.splatRenderMode===ns){const t=r(i),s=t.elementsPerTexelStored,n=t.texSize;const o=i>=1?8:4,l=new(i>=1?Uint32Array:Float32Array)(n.x*n.y*o);let c;if(0===i?l.set(a):Bs.updatePaddedCompressedCovariancesTextureData(a,l,0,0,a.length),i>=1)c=new e.DataTexture(l,n.x,n.y,e.RGBAIntegerFormat,e.UnsignedIntType),c.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=c;else{c=new e.DataTexture(l,n.x,n.y,e.RGBAFormat,e.FloatType),this.material.uniforms.covariancesTexture.value=c;const t=new e.DataTexture(new Uint32Array(32),2,2,e.RGBAIntegerFormat,e.UnsignedIntType);t.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=t,t.needsUpdate=!0}c.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=i>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(n),this.splatDataTextures.covariances={data:l,texture:c,size:n,compressionLevel:i,elementsPerTexelStored:s,elementsPerTexelAllocated:o}}else{const t=n(4,6);let r=Float32Array,i=e.FloatType;const o=new r(t.x*t.y*4);Bs.updateScaleRotationsPaddedData(0,s-1,l,c,o);const a=new e.DataTexture(o,t.x,t.y,e.RGBAFormat,i);a.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=a,this.material.uniforms.scaleRotationsTextureSize.value.copy(t),this.splatDataTextures.scaleRotations={data:o,texture:a,size:t,compressionLevel:0}}if(m){const t=2===o?e.UnsignedByteType:e.HalfFloatType;let r=u;r%2!=0&&r++;const i=4,a=e.RGBAFormat;let l=n(i,r);if(l.x*l.y<=Is){const n=new p(l.x*l.y*i);for(let e=0;e<s;e++){const t=u*e,s=r*e;for(let e=0;e<u;e++)n[s+e]=m[t+e]}const c=new e.DataTexture(n,l.x,l.y,a,t);c.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=c,this.splatDataTextures.sphericalHarmonics={componentCount:u,paddedComponentCount:r,data:n,textureCount:1,texture:c,size:l,compressionLevel:o,elementsPerTexel:i}}else{const c=u/3;r=c,r%2!=0&&r++,l=n(i,r);const h=l.x*l.y*i,d=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],A=[],f=[];for(let n=0;n<3;n++){const i=new p(h);A.push(i);for(let e=0;e<s;e++){const t=u*e,s=r*e;if(c>=3){for(let e=0;e<3;e++)i[s+e]=m[t+3*n+e];if(c>=8)for(let e=0;e<5;e++)i[s+3+e]=m[t+9+5*n+e]}}const o=new e.DataTexture(i,l.x,l.y,a,t);f.push(o),o.needsUpdate=!0,d[n].value=o}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:u,componentCountPerChannel:c,paddedComponentCount:r,data:A,textureCount:3,textures:f,size:l,compressionLevel:o,elementsPerTexel:i}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(l),this.material.uniforms.sphericalHarmonics8BitMode.value=2===o?1:0;for(let e=0;e<this.scenes.length;e++){const t=this.scenes[e].splatBuffer;this.material.uniforms.sphericalHarmonics8BitCompressionRangeMin.value[e]=t.minSphericalHarmonicsCoeff,this.material.uniforms.sphericalHarmonics8BitCompressionRangeMax.value[e]=t.maxSphericalHarmonicsCoeff}this.material.uniformsNeedUpdate=!0}const S=n(1,4),y=new Uint32Array(S.x*S.y*1);for(let e=0;e<s;e++)y[e]=this.globalSplatIndexToSceneIndexMap[e];const x=new e.DataTexture(y,S.x,S.y,e.RedIntegerFormat,e.UnsignedIntType);x.internalFormat="R32UI",x.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=x,this.material.uniforms.sceneIndexesTextureSize.value.copy(S),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:y,texture:x,size:S},this.material.uniforms.sceneCount.value=this.scenes.length}updateBaseDataFromSplatBuffers(e,t){const s=this.splatDataTextures.covariances,n=s?s.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,i=r?r.compressionLevel:void 0,o=this.splatDataTextures.sphericalHarmonics,a=o?o.compressionLevel:0;this.fillSplatDataArrays(this.splatDataTextures.baseData.covariances,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,this.splatDataTextures.baseData.sphericalHarmonics,void 0,n,i,a,e,t,e)}updateDataTexturesFromBaseData(e,t){const s=this.splatDataTextures.covariances,n=s?s.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,i=r?r.compressionLevel:void 0,o=this.splatDataTextures.sphericalHarmonics,a=o?o.compressionLevel:0,l=this.splatDataTextures.centerColors,c=l.data,h=l.texture;Bs.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,c);const d=this.renderer?this.renderer.properties.get(h):null;if(d&&d.__webglTexture?this.updateDataTexture(c,l.texture,l.size,d,4,4,4,e,t):h.needsUpdate=!0,s){const r=s.texture,i=6*e,o=6*t;if(0===n)for(let e=i;e<=o;e++){const t=this.splatDataTextures.baseData.covariances[e];s.data[e]=t}else Bs.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,s.data,e*s.elementsPerTexelAllocated,i,o);const a=this.renderer?this.renderer.properties.get(r):null;a&&a.__webglTexture?0===n?this.updateDataTexture(s.data,s.texture,s.size,a,s.elementsPerTexelStored,6,4,e,t):this.updateDataTexture(s.data,s.texture,s.size,a,s.elementsPerTexelAllocated,s.elementsPerTexelAllocated,2,e,t):r.needsUpdate=!0}if(r){const s=r.data,n=r.texture,o=6,a=0===i?4:2;Bs.updateScaleRotationsPaddedData(e,t,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,s);const l=this.renderer?this.renderer.properties.get(n):null;l&&l.__webglTexture?this.updateDataTexture(s,r.texture,r.size,l,4,o,a,e,t):n.needsUpdate=!0}const p=this.splatDataTextures.baseData.sphericalHarmonics;if(p){let s=4;1===a?s=2:2===a&&(s=1);const n=(n,r,i,o,a)=>{const l=this.renderer?this.renderer.properties.get(n):null;l&&l.__webglTexture?this.updateDataTexture(o,n,r,l,i,a,s,e,t):n.needsUpdate=!0},r=o.componentCount,i=o.paddedComponentCount;if(1===o.textureCount){const s=o.data;for(let n=e;n<=t;n++){const e=r*n,t=i*n;for(let n=0;n<r;n++)s[t+n]=p[e+n]}n(o.texture,o.size,o.elementsPerTexel,s,i)}else{const s=o.componentCountPerChannel;for(let a=0;a<3;a++){const l=o.data[a];for(let n=e;n<=t;n++){const e=r*n,t=i*n;if(s>=3){for(let s=0;s<3;s++)l[t+s]=p[e+3*a+s];if(s>=8)for(let s=0;s<5;s++)l[t+3+s]=p[e+9+5*a+s]}}n(o.textures[a],o.size,o.elementsPerTexel,l,i)}}}const u=this.splatDataTextures.sceneIndexes,m=u.data;for(let e=this.lastBuildSplatCount;e<=t;e++)m[e]=this.globalSplatIndexToSceneIndexMap[e];const A=u.texture,f=this.renderer?this.renderer.properties.get(A):null;f&&f.__webglTexture?this.updateDataTexture(m,u.texture,u.size,f,1,1,1,this.lastBuildSplatCount,t):A.needsUpdate=!0}getTargetCovarianceCompressionLevel(){return this.halfPrecisionCovariancesOnGPU?1:0}getTargetSphericalHarmonicsCompressionLevel(){return Math.max(1,this.getMaximumSplatBufferCompressionLevel())}getMaximumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const s=this.getScene(t).splatBuffer;(0===t||s.compressionLevel>e)&&(e=s.compressionLevel)}return e}getMinimumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const s=this.getScene(t).splatBuffer;(0===t||s.compressionLevel<e)&&(e=s.compressionLevel)}return e}static computeTextureUpdateRegion(e,t,s,n,r){const i=r/n,o=e*i,a=Math.floor(o/s),l=a*s*n,c=t*i,h=Math.floor(c/s);return{dataStart:l,dataEnd:h*s*n+s*n,startRow:a,endRow:h}}updateDataTexture(e,t,s,n,r,i,o,a,l){const c=this.renderer.getContext(),h=Bs.computeTextureUpdateRegion(a,l,s.x,r,i),d=h.dataEnd-h.dataStart,p=new e.constructor(e.buffer,h.dataStart*o,d),u=h.endRow-h.startRow+1,m=this.webGLUtils.convert(t.type),A=this.webGLUtils.convert(t.format,t.colorSpace),f=c.getParameter(c.TEXTURE_BINDING_2D);c.bindTexture(c.TEXTURE_2D,n.__webglTexture),c.texSubImage2D(c.TEXTURE_2D,0,0,h.startRow,s.x,u,A,m,p),c.bindTexture(c.TEXTURE_2D,f)}static updatePaddedCompressedCovariancesTextureData(e,t,s,n,r){let i=new DataView(t.buffer),o=s,a=0;for(let t=n;t<=r;t+=2)i.setUint16(2*o,e[t],!0),i.setUint16(2*o+2,e[t+1],!0),o+=2,a++,a>=3&&(o+=2,a=0)}static updateCenterColorsPaddedData(e,t,s,n,r){for(let a=e;a<=t;a++){const e=4*a,t=3*a,l=4*a;r[l]=(i=n)[o=e]+(i[o+1]<<8)+(i[o+2]<<16)+(i[o+3]<<24),r[l+1]=u(s[t]),r[l+2]=u(s[t+1]),r[l+3]=u(s[t+2])}var i,o}static updateScaleRotationsPaddedData(e,t,s,n,r){for(let i=e;i<=t;i++){const e=3*i,t=4*i,o=6*i;r[o]=s[e],r[o+1]=s[e+1],r[o+2]=s[e+2],r[o+3]=n[t],r[o+4]=n[t+1],r[o+5]=n[t+2]}}updateVisibleRegion(t){const s=this.getSplatCount(!0),n=new e.Vector3;if(!t){const t=new e.Vector3;this.scenes.forEach((e=>{t.add(e.splatBuffer.sceneCenter)})),t.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(t),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}for(let e=t?this.lastBuildSplatCount:0;e<s;e++){this.getSplatCenter(e,n,!0);const t=n.sub(this.calculatedSceneCenter).length();t>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=t)}this.maxSplatDistanceFromSceneCenter-this.visibleRegionBufferRadius>1&&(this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter,this.visibleRegionRadius=Math.max(this.visibleRegionBufferRadius-1,0)),this.finalBuild&&(this.visibleRegionRadius=this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter),this.updateVisibleRegionFadeDistance()}updateVisibleRegionFadeDistance(e=gs){const t=.012*this.sceneFadeInRateMultiplier,s=.003*this.sceneFadeInRateMultiplier,n=this.finalBuild?t:s,r=e===gs?n:s;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*r+this.visibleRegionFadeStartRadius;const i=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,o=i||e===Ss?1:0;this.material.uniforms.visibleRegionFadeStartRadius.value=this.visibleRegionFadeStartRadius,this.material.uniforms.visibleRegionRadius.value=this.visibleRegionRadius,this.material.uniforms.firstRenderTime.value=this.firstRenderTime,this.material.uniforms.currentTime.value=performance.now(),this.material.uniforms.fadeInComplete.value=o,this.material.uniformsNeedUpdate=!0,this.visibleRegionChanging=!i}updateRenderIndexes(e,t){const s=this.geometry;s.attributes.splatIndex.set(e),s.attributes.splatIndex.needsUpdate=!0,t>0&&-1===this.firstRenderTime&&(this.firstRenderTime=performance.now()),s.instanceCount=t,s.setDrawRange(0,t)}updateTransforms(){for(let e=0;e<this.scenes.length;e++){this.getScene(e).updateTransform(this.dynamicMode)}}updateUniforms=function(){const t=new e.Vector2;return function(e,s,n,r,i,o){if(this.getSplatCount()>0){if(t.set(e.x*this.devicePixelRatio,e.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(t),this.material.uniforms.basisViewport.value.set(1/t.x,1/t.y),this.material.uniforms.focal.value.set(s,n),this.material.uniforms.orthographicMode.value=r?1:0,this.material.uniforms.orthoZoom.value=i,this.material.uniforms.inverseFocalAdjustment.value=o,this.dynamicMode)for(let e=0;e<this.scenes.length;e++)this.material.uniforms.transforms.value[e].copy(this.getScene(e).transform);if(this.enableOptionalEffects)for(let e=0;e<this.scenes.length;e++)this.material.uniforms.sceneOpacity.value[e]=A(this.getScene(e).opacity,0,1),this.material.uniforms.sceneVisibility.value[e]=this.getScene(e).visible?1:0,this.material.uniformsNeedUpdate=!0;this.material.uniformsNeedUpdate=!0}}}();setSplatScale(e=1){this.splatScale=e,this.material.uniforms.splatScale.value=e,this.material.uniformsNeedUpdate=!0}getSplatScale(){return this.splatScale}setPointCloudModeEnabled(e){this.pointCloudModeEnabled=e,this.material.uniforms.pointCloudModeEnabled.value=e?1:0,this.material.uniformsNeedUpdate=!0}getPointCloudModeEnabled(){return this.pointCloudModeEnabled}getSplatDataTextures(){return this.splatDataTextures}getSplatCount(e=!1){return e?Bs.getTotalSplatCountForScenes(this.scenes):this.lastBuildSplatCount}static getTotalSplatCountForScenes(e){let t=0;for(let s of e)s&&s.splatBuffer&&(t+=s.splatBuffer.getSplatCount());return t}static getTotalSplatCountForSplatBuffers(e){let t=0;for(let s of e)t+=s.getSplatCount();return t}getMaxSplatCount(){return Bs.getTotalMaxSplatCountForScenes(this.scenes)}static getTotalMaxSplatCountForScenes(e){let t=0;for(let s of e)s&&s.splatBuffer&&(t+=s.splatBuffer.getMaxSplatCount());return t}static getTotalMaxSplatCountForSplatBuffers(e){let t=0;for(let s of e)t+=s.getMaxSplatCount();return t}disposeDistancesComputationGPUResources(){if(!this.renderer)return;const e=this.renderer.getContext();this.distancesTransformFeedback.vao&&(e.deleteVertexArray(this.distancesTransformFeedback.vao),this.distancesTransformFeedback.vao=null),this.distancesTransformFeedback.program&&(e.deleteProgram(this.distancesTransformFeedback.program),e.deleteShader(this.distancesTransformFeedback.vertexShader),e.deleteShader(this.distancesTransformFeedback.fragmentShader),this.distancesTransformFeedback.program=null,this.distancesTransformFeedback.vertexShader=null,this.distancesTransformFeedback.fragmentShader=null),this.disposeDistancesComputationGPUBufferResources(),this.distancesTransformFeedback.id&&(e.deleteTransformFeedback(this.distancesTransformFeedback.id),this.distancesTransformFeedback.id=null)}disposeDistancesComputationGPUBufferResources(){if(!this.renderer)return;const e=this.renderer.getContext();this.distancesTransformFeedback.centersBuffer&&(this.distancesTransformFeedback.centersBuffer=null,e.deleteBuffer(this.distancesTransformFeedback.centersBuffer)),this.distancesTransformFeedback.outDistancesBuffer&&(e.deleteBuffer(this.distancesTransformFeedback.outDistancesBuffer),this.distancesTransformFeedback.outDistancesBuffer=null)}setRenderer(t){if(t!==this.renderer){this.renderer=t;const s=this.renderer.getContext(),n=new As(s),r=new fs(s,n,{});if(n.init(r),this.webGLUtils=new e.WebGLUtils(s,n,r),this.enableDistancesComputationOnGPU&&this.getSplatCount()>0){this.setupDistancesComputationTransformFeedback();const{centers:e,sceneIndexes:t}=this.getDataForDistancesComputation(0,this.getSplatCount()-1);this.refreshGPUBuffersForDistancesComputation(e,t)}}}setupDistancesComputationTransformFeedback=function(){let e;return function(){const t=this.getMaxSplatCount();if(!this.renderer)return;const s=this.lastRenderer!==this.renderer,n=e!==t;if(!s&&!n)return;s?this.disposeDistancesComputationGPUResources():n&&this.disposeDistancesComputationGPUBufferResources();const r=this.renderer.getContext(),i=(e,t,s)=>{const n=e.createShader(t);if(!n)return console.error("Fatal error: gl could not create a shader object."),null;e.shaderSource(n,s),e.compileShader(n);if(!e.getShaderParameter(n,e.COMPILE_STATUS)){let s="unknown";t===e.VERTEX_SHADER?s="vertex shader":t===e.FRAGMENT_SHADER&&(s="fragement shader");const r=e.getShaderInfoLog(n);return console.error("Failed to compile "+s+" with these errors:"+r),e.deleteShader(n),null}return n};let o;this.integerBasedDistancesComputation?(o="#version 300 es\n in ivec4 center;\n flat out int distance;",this.dynamicMode?o+=`\n in uint sceneIndex;\n uniform ivec4 transforms[${b.MaxScenes}];\n void main(void) {\n ivec4 transform = transforms[sceneIndex];\n distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;\n }\n `:o+="\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "):(o="#version 300 es\n in vec4 center;\n flat out float distance;",this.dynamicMode?o+=`\n in uint sceneIndex;\n uniform mat4 transforms[${b.MaxScenes}];\n void main(void) {\n vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n `:o+="\n uniform vec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n ");const a=r.getParameter(r.VERTEX_ARRAY_BINDING),l=r.getParameter(r.CURRENT_PROGRAM),c=!!l&&r.getProgramParameter(l,r.DELETE_STATUS);if(s&&(this.distancesTransformFeedback.vao=r.createVertexArray()),r.bindVertexArray(this.distancesTransformFeedback.vao),s){const e=r.createProgram(),t=i(r,r.VERTEX_SHADER,o),s=i(r,r.FRAGMENT_SHADER,"#version 300 es\n precision lowp float;\n out vec4 fragColor;\n void main(){}\n ");if(!t||!s)throw new Error("Could not compile shaders for distances computation on GPU.");r.attachShader(e,t),r.attachShader(e,s),r.transformFeedbackVaryings(e,["distance"],r.SEPARATE_ATTRIBS),r.linkProgram(e);if(!r.getProgramParameter(e,r.LINK_STATUS)){const n=r.getProgramInfoLog(e);throw console.error("Fatal error: Failed to link program: "+n),r.deleteProgram(e),r.deleteShader(s),r.deleteShader(t),new Error("Could not link shaders for distances computation on GPU.")}this.distancesTransformFeedback.program=e,this.distancesTransformFeedback.vertexShader=t,this.distancesTransformFeedback.vertexShader=s}if(r.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let e=0;e<this.scenes.length;e++)this.distancesTransformFeedback.transformsLocs[e]=r.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${e}]`)}else this.distancesTransformFeedback.modelViewProjLoc=r.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(s||n)&&(this.distancesTransformFeedback.centersBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?r.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,r.INT,0,0):r.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,r.FLOAT,!1,0,0),this.dynamicMode&&(this.distancesTransformFeedback.sceneIndexesBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),r.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,r.UNSIGNED_INT,0,0))),(s||n)&&(this.distancesTransformFeedback.outDistancesBuffer=r.createBuffer()),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),r.bufferData(r.ARRAY_BUFFER,4*t,r.STATIC_READ),s&&(this.distancesTransformFeedback.id=r.createTransformFeedback()),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),l&&!0!==c&&r.useProgram(l),a&&r.bindVertexArray(a),this.lastRenderer=this.renderer,e=t}}();updateGPUCentersBufferForDistancesComputation(e,t,s){if(!this.renderer)return;const n=this.renderer.getContext(),r=n.getParameter(n.VERTEX_ARRAY_BINDING);n.bindVertexArray(this.distancesTransformFeedback.vao);const i=this.integerBasedDistancesComputation?Uint32Array:Float32Array,o=16*s;if(n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),e)n.bufferSubData(n.ARRAY_BUFFER,o,t);else{const e=new i(16*this.getMaxSplatCount());e.set(t),n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW)}n.bindBuffer(n.ARRAY_BUFFER,null),r&&n.bindVertexArray(r)}updateGPUTransformIndexesBufferForDistancesComputation(e,t,s){if(!this.renderer||!this.dynamicMode)return;const n=this.renderer.getContext(),r=n.getParameter(n.VERTEX_ARRAY_BINDING);n.bindVertexArray(this.distancesTransformFeedback.vao);const i=4*s;if(n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)n.bufferSubData(n.ARRAY_BUFFER,i,t);else{const e=new Uint32Array(4*this.getMaxSplatCount());e.set(t),n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW)}n.bindBuffer(n.ARRAY_BUFFER,null),r&&n.bindVertexArray(r)}getSceneIndexes(e,t){let s;s=new Uint32Array(t-e+1);for(let n=e;n<=t;n++)s[n]=this.globalSplatIndexToSceneIndexMap[n];return s}fillTransformsArray=function(){const e=[];return function(t){e.length!==t.length&&(e.length=t.length);for(let t=0;t<this.scenes.length;t++){const s=this.getScene(t).transform.elements;for(let n=0;n<16;n++)e[16*t+n]=s[n]}t.set(e)}}();computeDistancesOnGPU=function(){const t=new e.Matrix4;return function(e,s){if(!this.renderer)return;const n=this.renderer.getContext(),r=n.getParameter(n.VERTEX_ARRAY_BINDING),i=n.getParameter(n.CURRENT_PROGRAM),o=!!i&&n.getProgramParameter(i,n.DELETE_STATUS);if(n.bindVertexArray(this.distancesTransformFeedback.vao),n.useProgram(this.distancesTransformFeedback.program),n.enable(n.RASTERIZER_DISCARD),this.dynamicMode)for(let s=0;s<this.scenes.length;s++)if(t.copy(this.getScene(s).transform),t.premultiply(e),this.integerBasedDistancesComputation){const e=Bs.getIntegerMatrixArray(t),r=[e[2],e[6],e[10],e[14]];n.uniform4i(this.distancesTransformFeedback.transformsLocs[s],r[0],r[1],r[2],r[3])}else n.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[s],!1,t.elements);else if(this.integerBasedDistancesComputation){const t=Bs.getIntegerMatrixArray(e),s=[t[2],t[6],t[10]];n.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,s[0],s[1],s[2])}else{const t=[e.elements[2],e.elements[6],e.elements[10]];n.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,t[0],t[1],t[2])}n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),n.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?n.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,n.INT,0,0):n.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,n.FLOAT,!1,0,0),this.dynamicMode&&(n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),n.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),n.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,n.UNSIGNED_INT,0,0)),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),n.bindBufferBase(n.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),n.beginTransformFeedback(n.POINTS),n.drawArrays(n.POINTS,0,this.getSplatCount()),n.endTransformFeedback(),n.bindBufferBase(n.TRANSFORM_FEEDBACK_BUFFER,0,null),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,null),n.disable(n.RASTERIZER_DISCARD);const a=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);n.flush();const l=new Promise((e=>{const t=()=>{if(this.disposed)e();else{const r=0,i=0;switch(n.clientWaitSync(a,i,r)){case n.TIMEOUT_EXPIRED:return this.computeDistancesOnGPUSyncTimeout=setTimeout(t),this.computeDistancesOnGPUSyncTimeout;case n.WAIT_FAILED:throw new Error("should never get here");default:this.computeDistancesOnGPUSyncTimeout=null,n.deleteSync(a);const r=n.getParameter(n.VERTEX_ARRAY_BINDING);n.bindVertexArray(this.distancesTransformFeedback.vao),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),n.getBufferSubData(n.ARRAY_BUFFER,0,s),n.bindBuffer(n.ARRAY_BUFFER,null),r&&n.bindVertexArray(r),e()}}};this.computeDistancesOnGPUSyncTimeout=setTimeout(t)}));return i&&!0!==o&&n.useProgram(i),r&&n.bindVertexArray(r),l}}();getLocalSplatParameters(e,t,s){null==s&&(s=!this.dynamicMode),t.splatBuffer=this.getSplatBufferForSplat(e),t.localIndex=this.getSplatLocalIndex(e),t.sceneTransform=s?this.getSceneTransformForSplat(e):null}fillSplatDataArrays(t,s,n,r,i,o,a,l=0,c=0,h=1,d,p,u=0,m){const A=new e.Vector3;A.x=void 0,A.y=void 0,this.splatRenderMode===ns?A.z=void 0:A.z=1;const f=new e.Matrix4;let g=0,S=this.scenes.length-1;null!=m&&m>=0&&m<=this.scenes.length&&(g=m,S=m);for(let e=g;e<=S;e++){null==a&&(a=!this.dynamicMode);const m=this.getScene(e),g=m.splatBuffer;let S;if(a&&(this.getSceneTransform(e,f),S=f),t&&g.fillSplatCovarianceArray(t,S,d,p,u,l),s||n){if(!s||!n)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');g.fillSplatScaleRotationArray(s,n,S,d,p,u,c,A)}r&&g.fillSplatCenterArray(r,S,d,p,u),i&&g.fillSplatColorArray(i,m.minimumAlpha,d,p,u),o&&g.fillSphericalHarmonicsArray(o,this.minSphericalHarmonicsDegree,S,d,p,u,h),u+=g.getSplatCount()}}getIntegerCenters(e,t,s=!1){const n=t-e+1,r=new Float32Array(3*n);let i;this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e);let o=s?4:3;i=new Int32Array(n*o);for(let e=0;e<n;e++){for(let t=0;t<3;t++)i[e*o+t]=Math.round(1e3*r[3*e+t]);s&&(i[e*o+3]=1e3)}return i}getFloatCenters(e,t,s=!1){const n=t-e+1,r=new Float32Array(3*n);if(this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e),!s)return r;let i=new Float32Array(4*n);for(let e=0;e<n;e++){for(let t=0;t<3;t++)i[4*e+t]=r[3*e+t];i[4*e+3]=1}return i}getSplatCenter=function(){const e={};return function(t,s,n){this.getLocalSplatParameters(t,e,n),e.splatBuffer.getSplatCenter(e.localIndex,s,e.sceneTransform)}}();getSplatScaleAndRotation=function(){const t={},s=new e.Vector3;return function(e,n,r,i){this.getLocalSplatParameters(e,t,i),s.x=void 0,s.y=void 0,s.z=void 0,this.splatRenderMode===rs&&(s.z=0),t.splatBuffer.getSplatScaleAndRotation(t.localIndex,n,r,t.sceneTransform,s)}}();getSplatColor=function(){const e={};return function(t,s){this.getLocalSplatParameters(t,e),e.splatBuffer.getSplatColor(e.localIndex,s)}}();getSceneTransform(e,t){const s=this.getScene(e);s.updateTransform(this.dynamicMode),t.copy(s.transform)}getScene(e){if(e<0||e>=this.scenes.length)throw new Error("SplatMesh::getScene() -> Invalid scene index.");return this.scenes[e]}getSceneCount(){return this.scenes.length}getSplatBufferForSplat(e){return this.getScene(this.globalSplatIndexToSceneIndexMap[e]).splatBuffer}getSceneIndexForSplat(e){return this.globalSplatIndexToSceneIndexMap[e]}getSceneTransformForSplat(e){return this.getScene(this.globalSplatIndexToSceneIndexMap[e]).transform}getSplatLocalIndex(e){return this.globalSplatIndexToLocalSplatIndexMap[e]}static getIntegerMatrixArray(e){const t=e.elements,s=[];for(let e=0;e<16;e++)s[e]=Math.round(1e3*t[e]);return s}computeBoundingBox(t=!1,s){let n=this.getSplatCount();if(null!=s){if(s<0||s>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");n=this.scenes[s].splatBuffer.getSplatCount()}const r=new Float32Array(3*n);this.fillSplatDataArrays(null,null,null,r,null,null,t,void 0,void 0,void 0,void 0,s);const i=new e.Vector3,o=new e.Vector3;for(let e=0;e<n;e++){const t=3*e,s=r[t],n=r[t+1],a=r[t+2];(0===e||s<i.x)&&(i.x=s),(0===e||n<i.y)&&(i.y=n),(0===e||a<i.z)&&(i.z=a),(0===e||s>o.x)&&(o.x=s),(0===e||n>o.y)&&(o.y=n),(0===e||a>o.z)&&(o.z=a)}return new e.Box3(i,o)}}var ws="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";function bs(e){let t,s,n,r,i,o,a,l,c,h,d,p,u,m,A,f,g,S,C,y;e.onmessage=x=>{if(x.data.centers)centers=x.data.centers,sceneIndexes=x.data.sceneIndexes,r?new Int32Array(s,m+x.data.range.from*y.BytesPerInt*4,4*x.data.range.count).set(new Int32Array(centers)):new Float32Array(s,m+x.data.range.from*y.BytesPerFloat*4,4*x.data.range.count).set(new Float32Array(centers)),i&&new Uint32Array(s,c+4*x.data.range.from,x.data.range.count).set(new Uint32Array(sceneIndexes)),C=x.data.range.from+x.data.range.count;else if(x.data.sort){const v=Math.min(x.data.sort.splatRenderCount||0,C),I=Math.min(x.data.sort.splatSortCount||0,C),B=x.data.sort.usePrecomputedDistances;let w,b,D;n||(w=x.data.sort.indexesToSort,D=x.data.sort.transforms,B&&(b=x.data.sort.precomputedDistances)),function(C,x,v,I,B,w,b){const D=performance.now();if(!n&&(new Uint32Array(s,a,B.byteLength/y.BytesPerInt).set(B),new Float32Array(s,h,b.byteLength/y.BytesPerFloat).set(b),I)){let e;e=r?new Int32Array(s,d,w.byteLength/y.BytesPerInt):new Float32Array(s,d,w.byteLength/y.BytesPerFloat),e.set(w)}f||(f=new Uint32Array(S)),new Float32Array(s,A,16).set(v),new Uint32Array(s,u,S).set(f),t.exports.sortIndexes(a,m,d,p,u,A,l,c,h,S,C,x,o,I,r,i);const T={sortDone:!0,splatSortCount:C,splatRenderCount:x,sortTime:0};if(!n){const e=new Uint32Array(s,l,x);(!g||g.length<x)&&(g=new Uint32Array(x)),g.set(e),T.sortedIndexes=g}const E=performance.now();T.sortTime=E-D,e.postMessage(T)}(I,v,x.data.sort.modelViewProj,B,w,b,D)}else if(x.data.init){y=x.data.init.Constants,o=x.data.init.splatCount,n=x.data.init.useSharedMemory,r=x.data.init.integerBasedSort,i=x.data.init.dynamicMode,S=x.data.init.distanceMapRange,C=0;const f=r?4*y.BytesPerInt:4*y.BytesPerFloat,g=new Uint8Array(x.data.init.sorterWasmBytes),v=16*y.BytesPerFloat,I=o*y.BytesPerInt,B=o*f,w=v,b=r?o*y.BytesPerInt:o*y.BytesPerFloat,D=o*y.BytesPerInt,T=o*y.BytesPerInt,E=r?S*y.BytesPerInt*2:S*y.BytesPerFloat*2,M=i?o*y.BytesPerInt:0,F=i?y.MaxScenes*v:0,R=32*y.MemoryPageSize,P=I+B+w+b+D+E+T+M+F+R,H=Math.floor(P/y.MemoryPageSize)+1,k={module:{},env:{memory:new WebAssembly.Memory({initial:H,maximum:H,shared:!0})}};WebAssembly.compile(g).then((e=>WebAssembly.instantiate(e,k))).then((r=>{t=r,a=0,m=a+I,A=m+B,d=A+w,p=d+b,u=p+D,l=u+E,c=l+T,h=c+M,s=k.env.memory.buffer,n?e.postMessage({sortSetupPhase1Complete:!0,indexesToSortBuffer:s,indexesToSortOffset:a,sortedIndexesBuffer:s,sortedIndexesOffset:l,precomputedDistancesBuffer:s,precomputedDistancesOffset:d,transformsBuffer:s,transformsOffset:h}):e.postMessage({sortSetupPhase1Complete:!0})}))}}}const Ds=0,Ts=1,Es=2;class Ms{static createButton(e,t={}){const s=document.createElement("button");function n(){s.style.display="",s.style.cursor="auto",s.style.left="calc(50% - 75px)",s.style.width="150px",s.onmouseenter=null,s.onmouseleave=null,s.onclick=null}function r(e){e.style.position="absolute",e.style.bottom="20px",e.style.padding="12px 6px",e.style.border="1px solid #fff",e.style.borderRadius="4px",e.style.background="rgba(0,0,0,0.1)",e.style.color="#fff",e.style.font="normal 13px sans-serif",e.style.textAlign="center",e.style.opacity="0.5",e.style.outline="none",e.style.zIndex="999"}if("xr"in navigator)return s.id="VRButton",s.style.display="none",r(s),navigator.xr.isSessionSupported("immersive-vr").then((function(r){r?function(){let n=null;async function r(t){t.addEventListener("end",i),await e.xr.setSession(t),s.textContent="EXIT VR",n=t}function i(){n.removeEventListener("end",i),s.textContent="ENTER VR",n=null}s.style.display="",s.style.cursor="pointer",s.style.left="calc(50% - 50px)",s.style.width="100px",s.textContent="ENTER VR";const o={...t,optionalFeatures:["local-floor","bounded-floor","layers",...t.optionalFeatures||[]]};s.onmouseenter=function(){s.style.opacity="1.0"},s.onmouseleave=function(){s.style.opacity="0.5"},s.onclick=function(){null===n?navigator.xr.requestSession("immersive-vr",o).then(r):(n.end(),void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-vr",o).then(r).catch((e=>{console.warn(e)})))},void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-vr",o).then(r).catch((e=>{console.warn(e)}))}():(n(),s.textContent="VR NOT SUPPORTED"),r&&Ms.xrSessionIsGranted&&s.click()})).catch((function(e){n(),console.warn("Exception when trying to call xr.isSessionSupported",e),s.textContent="VR NOT ALLOWED"})),s;{const e=document.createElement("a");return!1===window.isSecureContext?(e.href=document.location.href.replace(/^http:/,"https:"),e.innerHTML="WEBXR NEEDS HTTPS"):(e.href="https://immersiveweb.dev/",e.innerHTML="WEBXR NOT AVAILABLE"),e.style.left="calc(50% - 90px)",e.style.width="180px",e.style.textDecoration="none",r(e),e}}static registerSessionGrantedListener(){if("undefined"!=typeof navigator&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",(()=>{Ms.xrSessionIsGranted=!0}))}}}Ms.xrSessionIsGranted=!1,Ms.registerSessionGrantedListener();class Fs{static createButton(e,t={}){const s=document.createElement("button");function n(){s.style.display="",s.style.cursor="auto",s.style.left="calc(50% - 75px)",s.style.width="150px",s.onmouseenter=null,s.onmouseleave=null,s.onclick=null}function r(e){e.style.position="absolute",e.style.bottom="20px",e.style.padding="12px 6px",e.style.border="1px solid #fff",e.style.borderRadius="4px",e.style.background="rgba(0,0,0,0.1)",e.style.color="#fff",e.style.font="normal 13px sans-serif",e.style.textAlign="center",e.style.opacity="0.5",e.style.outline="none",e.style.zIndex="999"}if("xr"in navigator)return s.id="ARButton",s.style.display="none",r(s),navigator.xr.isSessionSupported("immersive-ar").then((function(r){r?function(){if(void 0===t.domOverlay){const e=document.createElement("div");e.style.display="none",document.body.appendChild(e);const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width",38),s.setAttribute("height",38),s.style.position="absolute",s.style.right="20px",s.style.top="20px",s.addEventListener("click",(function(){n.end()})),e.appendChild(s);const r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),r.setAttribute("stroke","#fff"),r.setAttribute("stroke-width",2),s.appendChild(r),void 0===t.optionalFeatures&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:e}}let n=null;async function r(r){r.addEventListener("end",i),e.xr.setReferenceSpaceType("local"),await e.xr.setSession(r),s.textContent="STOP AR",t.domOverlay.root.style.display="",n=r}function i(){n.removeEventListener("end",i),s.textContent="START AR",t.domOverlay.root.style.display="none",n=null}s.style.display="",s.style.cursor="pointer",s.style.left="calc(50% - 50px)",s.style.width="100px",s.textContent="START AR",s.onmouseenter=function(){s.style.opacity="1.0"},s.onmouseleave=function(){s.style.opacity="0.5"},s.onclick=function(){null===n?navigator.xr.requestSession("immersive-ar",t).then(r):(n.end(),void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-ar",t).then(r).catch((e=>{console.warn(e)})))},void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-ar",t).then(r).catch((e=>{console.warn(e)}))}():(n(),s.textContent="AR NOT SUPPORTED")})).catch((function(e){n(),console.warn("Exception when trying to call xr.isSessionSupported",e),s.textContent="AR NOT ALLOWED"})),s;{const e=document.createElement("a");return!1===window.isSecureContext?(e.href=document.location.href.replace(/^http:/,"https:"),e.innerHTML="WEBXR NEEDS HTTPS"):(e.href="https://immersiveweb.dev/",e.innerHTML="WEBXR NOT AVAILABLE"),e.style.left="calc(50% - 90px)",e.style.width="180px",e.style.textDecoration="none",r(e),e}}}const Rs=0,Ps=2;class Hs{constructor(t={}){if(t.cameraUp||(t.cameraUp=[0,1,0]),this.cameraUp=(new e.Vector3).fromArray(t.cameraUp),t.initialCameraPosition||(t.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new e.Vector3).fromArray(t.initialCameraPosition),t.initialCameraLookAt||(t.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new e.Vector3).fromArray(t.initialCameraLookAt),this.dropInMode=t.dropInMode||!1,void 0!==t.selfDrivenMode&&null!==t.selfDrivenMode||(t.selfDrivenMode=!0),this.selfDrivenMode=t.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),void 0===t.useBuiltInControls&&(t.useBuiltInControls=!0),this.useBuiltInControls=t.useBuiltInControls,this.rootElement=t.rootElement,this.ignoreDevicePixelRatio=t.ignoreDevicePixelRatio||!1,this.devicePixelRatio=this.ignoreDevicePixelRatio?1:window.devicePixelRatio||1,this.halfPrecisionCovariancesOnGPU=t.halfPrecisionCovariancesOnGPU||!1,this.threeScene=t.threeScene,this.renderer=t.renderer,this.camera=t.camera,this.gpuAcceleratedSort=t.gpuAcceleratedSort||!1,void 0!==t.integerBasedSort&&null!==t.integerBasedSort||(t.integerBasedSort=!0),this.integerBasedSort=t.integerBasedSort,void 0!==t.sharedMemoryForWorkers&&null!==t.sharedMemoryForWorkers||(t.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=t.sharedMemoryForWorkers,this.dynamicScene=!!t.dynamicScene,this.antialiased=t.antialiased||!1,this.kernel2DSize=void 0===t.kernel2DSize?.3:t.kernel2DSize,this.webXRMode=t.webXRMode||Ds,this.webXRMode!==Ds&&(this.gpuAcceleratedSort=!1),this.webXRActive=!1,this.webXRSessionInit=t.webXRSessionInit||{},this.renderMode=t.renderMode||Rs,this.sceneRevealMode=t.sceneRevealMode||gs,this.focalAdjustment=t.focalAdjustment||1,this.maxScreenSpaceSplatSize=t.maxScreenSpaceSplatSize||1024,this.logLevel=t.logLevel||Cs,this.sphericalHarmonicsDegree=t.sphericalHarmonicsDegree||0,this.enableOptionalEffects=t.enableOptionalEffects||!1,void 0!==t.enableSIMDInSort&&null!==t.enableSIMDInSort||(t.enableSIMDInSort=!0),this.enableSIMDInSort=t.enableSIMDInSort,void 0!==t.inMemoryCompressionLevel&&null!==t.inMemoryCompressionLevel||(t.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=t.inMemoryCompressionLevel,void 0!==t.optimizeSplatData&&null!==t.optimizeSplatData||(t.optimizeSplatData=!0),this.optimizeSplatData=t.optimizeSplatData,void 0!==t.freeIntermediateSplatData&&null!==t.freeIntermediateSplatData||(t.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=t.freeIntermediateSplatData,I()){const e=B();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==t.splatRenderMode&&null!==t.splatRenderMode||(t.splatRenderMode=ns),this.splatRenderMode=t.splatRenderMode,this.sceneFadeInRateMultiplier=t.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=t.splatSortDistanceMapPrecision||b.DefaultSplatSortDistanceMapPrecision;const s=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=A(this.splatSortDistanceMapPrecision,10,s),this.onSplatMeshChangedCallback=null,this.createSplatMesh(),this.controls=null,this.perspectiveControls=null,this.orthographicControls=null,this.orthographicCamera=null,this.perspectiveCamera=null,this.showMeshCursor=!1,this.showControlPlane=!1,this.showInfo=!1,this.sceneHelper=null,this.sortWorker=null,this.sortRunning=!1,this.splatRenderCount=0,this.splatSortCount=0,this.lastSplatSortCount=0,this.sortWorkerIndexesToSort=null,this.sortWorkerSortedIndexes=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.preSortMessages=[],this.runAfterNextSort=[],this.selfDrivenModeRunning=!1,this.splatRenderReady=!1,this.raycaster=new is,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new e.Vector3,this.nextCameraTarget=new e.Vector3,this.mousePosition=new e.Vector2,this.mouseDownPosition=new e.Vector2,this.mouseDownTime=null,this.resizeObserver=null,this.mouseMoveListener=null,this.mouseDownListener=null,this.mouseUpListener=null,this.keyDownListener=null,this.sortPromise=null,this.sortPromiseResolver=null,this.splatSceneDownloadPromises={},this.splatSceneDownloadAndBuildPromise=null,this.splatSceneRemovalPromise=null,this.loadingSpinner=new qt(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Wt(this.rootElement||document.body),this.loadingProgressBar.hide(),this.infoPanel=new jt(this.rootElement||document.body),this.infoPanel.hide(),this.usingExternalCamera=!(!this.dropInMode&&!this.camera),this.usingExternalRenderer=!(!this.dropInMode&&!this.renderer),this.initialized=!1,this.disposing=!1,this.disposed=!1,this.disposePromise=null,this.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new Bs(this.splatRenderMode,this.dynamicScene,this.enableOptionalEffects,this.halfPrecisionCovariancesOnGPU,this.devicePixelRatio,this.gpuAcceleratedSort,this.integerBasedSort,this.antialiased,this.maxScreenSpaceSplatSize,this.logLevel,this.sphericalHarmonicsDegree,this.sceneFadeInRateMultiplier,this.kernel2DSize),this.splatMesh.frustumCulled=!1,this.onSplatMeshChangedCallback&&this.onSplatMeshChangedCallback()}init(){this.initialized||(this.rootElement||(this.usingExternalRenderer?this.rootElement=this.renderer.domElement||document.body:(this.rootElement=document.createElement("div"),this.rootElement.style.width="100%",this.rootElement.style.height="100%",this.rootElement.style.position="absolute",document.body.appendChild(this.rootElement))),this.setupCamera(),this.setupRenderer(),this.setupWebXR(this.webXRSessionInit),this.setupControls(),this.setupEventHandlers(),this.threeScene=this.threeScene||new e.Scene,this.sceneHelper=new Jt(this.threeScene),this.sceneHelper.setupMeshCursor(),this.sceneHelper.setupFocusMarker(),this.sceneHelper.setupControlPlane(),this.loadingProgressBar.setContainer(this.rootElement),this.loadingSpinner.setContainer(this.rootElement),this.infoPanel.setContainer(this.rootElement),this.initialized=!0)}setupCamera(){if(!this.usingExternalCamera){const t=new e.Vector2;this.getRenderDimensions(t),this.perspectiveCamera=new e.PerspectiveCamera(50,t.x/t.y,.1,1e3),this.orthographicCamera=new e.OrthographicCamera(t.x/-2,t.x/2,t.y/2,t.y/-2,.1,1e3),this.camera=this.startInOrthographicMode?this.orthographicCamera:this.perspectiveCamera,this.camera.position.copy(this.initialCameraPosition),this.camera.up.copy(this.cameraUp).normalize(),this.camera.lookAt(this.initialCameraLookAt)}}setupRenderer(){if(!this.usingExternalRenderer){const t=new e.Vector2;this.getRenderDimensions(t),this.renderer=new e.WebGLRenderer({antialias:!1,precision:"highp"}),this.renderer.setPixelRatio(this.devicePixelRatio),this.renderer.autoClear=!0,this.renderer.setClearColor(new e.Color(0),0),this.renderer.setSize(t.x,t.y),this.resizeObserver=new ResizeObserver((()=>{this.getRenderDimensions(t),this.renderer.setSize(t.x,t.y),this.forceRenderNextFrame()})),this.resizeObserver.observe(this.rootElement),this.rootElement.appendChild(this.renderer.domElement)}}setupWebXR(e){this.webXRMode&&(this.webXRMode===Ts?this.rootElement.appendChild(Ms.createButton(this.renderer,e)):this.webXRMode===Es&&this.rootElement.appendChild(Fs.createButton(this.renderer,e)),this.renderer.xr.addEventListener("sessionstart",(e=>{this.webXRActive=!0})),this.renderer.xr.addEventListener("sessionend",(e=>{this.webXRActive=!1})),this.renderer.xr.enabled=!0,this.camera.position.copy(this.initialCameraPosition),this.camera.up.copy(this.cameraUp).normalize(),this.camera.lookAt(this.initialCameraLookAt))}setupControls(){if(this.useBuiltInControls&&this.webXRMode===Ds){this.usingExternalCamera?this.camera.isOrthographicCamera?this.orthographicControls=new Kt(this.camera,this.renderer.domElement):this.perspectiveControls=new Kt(this.camera,this.renderer.domElement):(this.perspectiveControls=new Kt(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new Kt(this.orthographicCamera,this.renderer.domElement));for(let e of[this.orthographicControls,this.perspectiveControls])e&&(e.listenToKeyEvents(window),e.rotateSpeed=.5,e.maxPolarAngle=.75*Math.PI,e.minPolarAngle=.1,e.enableDamping=!0,e.dampingFactor=.05,e.target.copy(this.initialCameraLookAt),e.update());this.controls=this.camera.isOrthographicCamera?this.orthographicControls:this.perspectiveControls,this.controls.update()}}setupEventHandlers(){this.useBuiltInControls&&this.webXRMode===Ds&&(this.mouseMoveListener=this.onMouseMove.bind(this),this.renderer.domElement.addEventListener("pointermove",this.mouseMoveListener,!1),this.mouseDownListener=this.onMouseDown.bind(this),this.renderer.domElement.addEventListener("pointerdown",this.mouseDownListener,!1),this.mouseUpListener=this.onMouseUp.bind(this),this.renderer.domElement.addEventListener("pointerup",this.mouseUpListener,!1),this.keyDownListener=this.onKeyDown.bind(this),window.addEventListener("keydown",this.keyDownListener,!1))}removeEventHandlers(){this.useBuiltInControls&&(this.renderer.domElement.removeEventListener("pointermove",this.mouseMoveListener),this.mouseMoveListener=null,this.renderer.domElement.removeEventListener("pointerdown",this.mouseDownListener),this.mouseDownListener=null,this.renderer.domElement.removeEventListener("pointerup",this.mouseUpListener),this.mouseUpListener=null,window.removeEventListener("keydown",this.keyDownListener),this.keyDownListener=null)}setRenderMode(e){this.renderMode=e}setActiveSphericalHarmonicsDegrees(e){this.splatMesh.material.uniforms.sphericalHarmonicsDegree.value=e,this.splatMesh.material.uniformsNeedUpdate=!0}onSplatMeshChanged(e){this.onSplatMeshChangedCallback=e}onKeyDown=function(){const t=new e.Vector3,s=new e.Matrix4,n=new e.Matrix4;return function(e){switch(t.set(0,0,-1),t.transformDirection(this.camera.matrixWorld),s.makeRotationAxis(t,Math.PI/128),n.makeRotationAxis(t,-Math.PI/128),e.code){case"KeyG":this.focalAdjustment+=.02,this.forceRenderNextFrame();break;case"KeyF":this.focalAdjustment-=.02,this.forceRenderNextFrame();break;case"ArrowLeft":this.camera.up.transformDirection(s);break;case"ArrowRight":this.camera.up.transformDirection(n);break;case"KeyC":this.showMeshCursor=!this.showMeshCursor;break;case"KeyU":this.showControlPlane=!this.showControlPlane;break;case"KeyI":this.showInfo=!this.showInfo,this.showInfo?this.infoPanel.show():this.infoPanel.hide();break;case"KeyO":this.usingExternalCamera||this.setOrthographicMode(!this.camera.isOrthographicCamera);break;case"KeyP":this.usingExternalCamera||this.splatMesh.setPointCloudModeEnabled(!this.splatMesh.getPointCloudModeEnabled());break;case"Equal":this.usingExternalCamera||this.splatMesh.setSplatScale(this.splatMesh.getSplatScale()+.05);break;case"Minus":this.usingExternalCamera||this.splatMesh.setSplatScale(Math.max(this.splatMesh.getSplatScale()-.05,0))}}}();onMouseMove(e){this.mousePosition.set(e.offsetX,e.offsetY)}onMouseDown(){this.mouseDownPosition.copy(this.mousePosition),this.mouseDownTime=f()}onMouseUp=function(){const t=new e.Vector2;return function(e){t.copy(this.mousePosition).sub(this.mouseDownPosition);f()-this.mouseDownTime<.5&&t.length()<2&&this.onMouseClick(e)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkForFocalPointChange=function(){const t=new e.Vector2,s=new e.Vector3,n=[];return function(){if(!this.transitioningCameraTarget&&(this.getRenderDimensions(t),n.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,t),this.raycaster.intersectSplatMesh(this.splatMesh,n),n.length>0)){const e=n[0].origin;s.copy(e).sub(this.camera.position),s.length()>.75&&(this.previousCameraTarget.copy(this.controls.target),this.nextCameraTarget.copy(e),this.transitioningCameraTarget=!0,this.transitioningCameraTargetStartTime=f())}}}();getRenderDimensions(e){this.rootElement?(e.x=this.rootElement.offsetWidth,e.y=this.rootElement.offsetHeight):this.renderer.getSize(e)}setOrthographicMode(e){if(e===this.camera.isOrthographicCamera)return;const t=this.camera,s=e?this.orthographicCamera:this.perspectiveCamera;if(s.position.copy(t.position),s.up.copy(t.up),s.rotation.copy(t.rotation),s.quaternion.copy(t.quaternion),s.matrix.copy(t.matrix),this.camera=s,this.controls){const n=e=>{e.saveState(),e.reset()},r=this.controls,i=e?this.orthographicControls:this.perspectiveControls;n(i),n(r),i.target.copy(r.target),e?Hs.setCameraZoomFromPosition(s,t,r):Hs.setCameraPositionFromZoom(s,t,i),this.controls=i,this.camera.lookAt(this.controls.target)}}static setCameraPositionFromZoom=function(){const t=new e.Vector3;return function(e,s,n){const r=1/(.001*s.zoom);t.copy(n.target).sub(e.position).normalize().multiplyScalar(r).negate(),e.position.copy(n.target).add(t)}}();static setCameraZoomFromPosition=function(){const t=new e.Vector3;return function(e,s,n){const r=t.copy(n.target).sub(s.position).length();e.zoom=1/(.001*r)}}();updateSplatMesh=function(){const t=new e.Vector2;return function(){if(!this.splatMesh)return;if(this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(t);const e=.5*this.camera.projectionMatrix.elements[0]*this.devicePixelRatio*t.x,s=.5*this.camera.projectionMatrix.elements[5]*this.devicePixelRatio*t.y,n=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,r=this.focalAdjustment*n,i=1/r;this.adjustForWebXRStereo(t),this.splatMesh.updateUniforms(t,e*r,s*r,this.camera.isOrthographicCamera,this.camera.zoom||1,i)}}}();adjustForWebXRStereo(e){if(this.camera&&this.webXRActive){const t=this.renderer.xr.getCamera().projectionMatrix.elements[0],s=this.camera.projectionMatrix.elements[0];e.x*=s/t}}isLoadingOrUnloading(){return Object.keys(this.splatSceneDownloadPromises).length>0||null!==this.splatSceneDownloadAndBuildPromise||null!==this.splatSceneRemovalPromise}isDisposingOrDisposed(){return this.disposing||this.disposed}addSplatSceneDownloadPromise(e){this.splatSceneDownloadPromises[e.id]=e}removeSplatSceneDownloadPromise(e){delete this.splatSceneDownloadPromises[e.id]}setSplatSceneDownloadAndBuildPromise(e){this.splatSceneDownloadAndBuildPromise=e}clearSplatSceneDownloadAndBuildPromise(){this.splatSceneDownloadAndBuildPromise=null}addSplatScene(e,t={}){if(this.isLoadingOrUnloading())throw new Error("Cannot add splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot add splat scene after dispose() is called.");t.progressiveLoad&&this.splatMesh.scenes&&this.splatMesh.scenes.length>0&&(console.log('addSplatScene(): "progressiveLoad" option ignore because there are multiple splat scenes'),t.progressiveLoad=!1);const s=void 0!==t.format&&null!==t.format?t.format:Ut(e),n=Hs.isProgressivelyLoadable(s)&&t.progressiveLoad,r=void 0===t.showLoadingUI||null===t.showLoadingUI||t.showLoadingUI;let i=null;r&&(this.loadingSpinner.removeAllTasks(),i=this.loadingSpinner.addTask("Downloading..."));const o=(e,t,s)=>{if(r)if(s===lt)if(100==e)this.loadingSpinner.setMessageForTask(i,"Download complete!");else if(n)this.loadingSpinner.setMessageForTask(i,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(i,`Downloading${e}`)}else s===ct&&this.loadingSpinner.setMessageForTask(i,"Processing splats...")};let a=!1,l=0;const c=(e,t)=>{r&&((e&&n||t&&!n)&&(this.loadingSpinner.removeTask(i),t||a||this.loadingProgressBar.show()),n&&(t?(a=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(l)))};return(n?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(e,s,t.splatAlphaRemovalThreshold,((e,s,i)=>{!n&&t.onProgress&&t.onProgress(0,"0%",ct);const o={rotation:t.rotation||t.orientation,position:t.position,scale:t.scale,splatAlphaRemovalThreshold:t.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[o],i,s&&r,r,n,n).then((()=>{!n&&t.onProgress&&t.onProgress(100,"100%",ct),c(s,i)}))}).bind(this),((e,s,n)=>{l=e,o(e,s,n),t.onProgress&&t.onProgress(e,s,n)}),(()=>{this.loadingProgressBar.hide(),this.loadingSpinner.removeAllTasks()}).bind(this),t.headers)}downloadAndBuildSingleSplatSceneStandardLoad(e,t,s,n,r,i,o){const a=this.downloadSplatSceneToSplatBuffer(e,s,r,!1,void 0,t,o),l=x(a.abortHandler);return a.then((e=>(this.removeSplatSceneDownloadPromise(a),n(e,!0,!0).then((()=>{l.resolve(),this.clearSplatSceneDownloadAndBuildPromise()}))))).catch((t=>{i&&i(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(a),l.reject(this.updateError(t,`Viewer::addSplatScene -> Could not load file ${e}`))})),this.addSplatSceneDownloadPromise(a),this.setSplatSceneDownloadAndBuildPromise(l.promise),l.promise}downloadAndBuildSingleSplatSceneProgressiveLoad(e,t,s,n,r,i,o){let a=0,l=!1;const c=[],h=()=>{if(c.length>0&&!l&&!this.isDisposingOrDisposed()){l=!0;const e=c.shift();n(e.splatBuffer,e.firstBuild,e.finalBuild).then((()=>{l=!1,e.firstBuild?p.resolve():e.finalBuild&&(u.resolve(),this.clearSplatSceneDownloadAndBuildPromise()),c.length>0&&S((()=>h()))}))}},d=this.downloadSplatSceneToSplatBuffer(e,s,r,!0,((e,t)=>{this.isDisposingOrDisposed()||(t||0===c.length||e.getSplatCount()>c[0].splatBuffer.getSplatCount())&&(c.push({splatBuffer:e,firstBuild:0===a,finalBuild:t}),a++,h())}),t,o),p=x(d.abortHandler),u=x();return this.addSplatSceneDownloadPromise(d),this.setSplatSceneDownloadAndBuildPromise(u.promise),d.then((()=>{this.removeSplatSceneDownloadPromise(d)})).catch((e=>{this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(d);const t=this.updateError(e,"Viewer::addSplatScene -> Could not load one or more scenes");p.reject(t),i&&i(t)})),p.promise}addSplatScenes(e,t=!0,s=void 0){if(this.isLoadingOrUnloading())throw new Error("Cannot add splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot add splat scene after dispose() is called.");const n=e.length,r=[];let i;t&&(this.loadingSpinner.removeAllTasks(),i=this.loadingSpinner.addTask("Downloading..."));const o=(e,o,a,l)=>{r[e]=o;let c=0;for(let e=0;e<n;e++)c+=r[e]||0;c/=n,a=`${c.toFixed(2)}%`,t&&l===lt&&this.loadingSpinner.setMessageForTask(i,100==c?"Download complete!":`Downloading: ${a}`),s&&s(c,a,l)},a=[],l=[];for(let t=0;t<e.length;t++){const s=e[t],n=void 0!==s.format&&null!==s.format?s.format:Ut(s.path),r=this.downloadSplatSceneToSplatBuffer(s.path,s.splatAlphaRemovalThreshold,o.bind(this,t),!1,void 0,n,s.headers);a.push(r),l.push(r.promise)}const c=new d(((n,r)=>{Promise.all(l).then((r=>{t&&this.loadingSpinner.removeTask(i),s&&s(0,"0%",ct),this.addSplatBuffers(r,e,!0,t,t,!1,!1).then((()=>{s&&s(100,"100%",ct),this.clearSplatSceneDownloadAndBuildPromise(),n()}))})).catch((e=>{t&&this.loadingSpinner.removeTask(i),this.clearSplatSceneDownloadAndBuildPromise(),r(this.updateError(e,"Viewer::addSplatScenes -> Could not load one or more splat scenes."))})).finally((()=>{this.removeSplatSceneDownloadPromise(c)}))}),(e=>{for(let t of a)t.abort(e)}));return this.addSplatSceneDownloadPromise(c),this.setSplatSceneDownloadAndBuildPromise(c),c}downloadSplatSceneToSplatBuffer(e,t=1,s=void 0,n=!1,r=void 0,i,o){try{if(i===Ht||i===kt||i===Lt){const a=!n&&this.optimizeSplatData;if(i===Ht)return Rt.loadFromURL(e,s,n,r,t,this.inMemoryCompressionLevel,a,o);if(i===kt)return Pt.loadFromURL(e,s,n,r,o);if(i===Lt)return gt.loadFromURL(e,s,n,r,t,this.inMemoryCompressionLevel,a,this.sphericalHarmonicsDegree,o)}else if(i===Ot)return Et.loadFromURL(e,s,t,this.inMemoryCompressionLevel,this.optimizeSplatData,this.sphericalHarmonicsDegree,o)}catch(e){throw this.updateError(e,null)}throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${e}`)}static isProgressivelyLoadable(e){return e===Ht||e===kt||e===Lt}addSplatBuffers=function(){return function(e,t=[],s=!0,n=!0,r=!0,i=!1,o=!1,a=!0){if(this.isDisposingOrDisposed())return Promise.resolve();let l=null;const c=()=>{null!==l&&(this.loadingSpinner.removeTask(l),l=null)};return this.splatRenderReady=!1,new Promise((h=>{n&&(l=this.loadingSpinner.addTask("Processing splats...")),S((()=>{if(this.isDisposingOrDisposed())h();else{const n=this.addSplatBuffersToMesh(e,t,s,r,i,a),l=this.splatMesh.getMaxSplatCount();this.sortWorker&&this.sortWorker.maxSplatCount!==l&&this.disposeSortWorker(),this.gpuAcceleratedSort||this.preSortMessages.push({centers:n.centers.buffer,sceneIndexes:n.sceneIndexes.buffer,range:{from:n.from,to:n.to,count:n.count}});(!this.sortWorker&&l>0?this.setupSortWorker(this.splatMesh):Promise.resolve()).then((()=>{this.isDisposingOrDisposed()||this.runSplatSort(!0,!0).then((e=>{this.sortWorker&&e?(o?this.splatRenderReady=!0:this.runAfterNextSort.push((()=>{this.splatRenderReady=!0})),this.runAfterNextSort.push((()=>{c(),h()}))):(this.splatRenderReady=!0,c(),h())}))}))}}),!0)}))}}();addSplatBuffersToMesh=function(){let e;return function(t,s,n=!0,r=!1,i=!1,o=!0){if(this.isDisposingOrDisposed())return;let a=[],l=[];i||(a=this.splatMesh.scenes.map((e=>e.splatBuffer))||[],l=this.splatMesh.sceneOptions?this.splatMesh.sceneOptions.map((e=>e)):[]),a.push(...t),l.push(...s),this.renderer&&this.splatMesh.setRenderer(this.renderer);const c=this.splatMesh.build(a,l,!0,n,(t=>{if(this.isDisposingOrDisposed())return;const s=this.splatMesh.getSplatCount();r&&s>=15e5&&(t||e||(this.loadingSpinner.setMinimized(!0,!0),e=this.loadingSpinner.addTask("Optimizing data structures...")))}),(t=>{this.isDisposingOrDisposed()||t&&e&&(this.loadingSpinner.removeTask(e),e=null)}),o);return n&&this.freeIntermediateSplatData&&this.splatMesh.freeIntermediateSplatData(),c}}();setupSortWorker(e){if(!this.isDisposingOrDisposed())return new Promise((t=>{const s=this.integerBasedSort?Int32Array:Float32Array,n=e.getSplatCount(),r=e.getMaxSplatCount();this.sortWorker=function(e,t,s,n,r,i=b.DefaultSplatSortDistanceMapPrecision){const o=new Worker(URL.createObjectURL(new Blob(["(",bs.toString(),")(self)"],{type:"application/javascript"})));let a="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";const l=I()?B():null;s||t?s?t||l&&l.major<=16&&l.minor<4&&(a="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"):a=ws:(a=ws,l&&l.major<=16&&l.minor<4&&(a="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"));const c=atob(a),h=new Uint8Array(c.length);for(let e=0;e<c.length;e++)h[e]=c.charCodeAt(e);return o.postMessage({init:{sorterWasmBytes:h.buffer,splatCount:e,useSharedMemory:t,integerBasedSort:n,dynamicMode:r,distanceMapRange:1<<i,Constants:{BytesPerFloat:b.BytesPerFloat,BytesPerInt:b.BytesPerInt,MemoryPageSize:b.MemoryPageSize,MaxScenes:b.MaxScenes}}}),o}(r,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),this.sortWorker.onmessage=e=>{if(e.data.sortDone){if(this.sortRunning=!1,this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,e.data.splatRenderCount);else{const t=new Uint32Array(e.data.sortedIndexes.buffer,0,e.data.splatRenderCount);this.splatMesh.updateRenderIndexes(t,e.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=e.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach((e=>{e()})),this.runAfterNextSort.length=0)}else if(e.data.sortCanceled)this.sortRunning=!1;else if(e.data.sortSetupPhase1Complete){this.logLevel>=ys&&console.log("Sorting web worker WASM setup complete."),this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(e.data.sortedIndexesBuffer,e.data.sortedIndexesOffset,r),this.sortWorkerIndexesToSort=new Uint32Array(e.data.indexesToSortBuffer,e.data.indexesToSortOffset,r),this.sortWorkerPrecomputedDistances=new s(e.data.precomputedDistancesBuffer,e.data.precomputedDistancesOffset,r),this.sortWorkerTransforms=new Float32Array(e.data.transformsBuffer,e.data.transformsOffset,16*b.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(r),this.sortWorkerPrecomputedDistances=new s(r),this.sortWorkerTransforms=new Float32Array(16*b.MaxScenes));for(let e=0;e<n;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=r,this.logLevel>=ys){console.log("Sorting web worker ready.");const e=this.splatMesh.getSplatDataTextures(),t=e.covariances.size,s=e.centerColors.size;console.log("Covariances texture size: "+t.x+" x "+t.y),console.log("Centers/colors texture size: "+s.x+" x "+s.y)}t()}}}))}updateError(e,t){return e instanceof p?e:e instanceof dt?new Error("File type or server does not support progressive loading."):t?new Error(t):e}disposeSortWorker(){this.sortWorker&&this.sortWorker.terminate(),this.sortWorker=null,this.sortPromise=null,this.sortPromiseResolver&&(this.sortPromiseResolver(),this.sortPromiseResolver=null),this.preSortMessages=[],this.sortRunning=!1}removeSplatScene(e,t=!0){return this.removeSplatScenes([e],t)}removeSplatScenes(e,t=!0){if(this.isLoadingOrUnloading())throw new Error("Cannot remove splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot remove splat scene after dispose() is called.");let s;return this.splatSceneRemovalPromise=new Promise(((n,r)=>{let i;t&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),i=this.loadingSpinner.addTask("Removing splat scene..."));const o=()=>{t&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(i))},a=e=>{o(),this.splatSceneRemovalPromise=null,e?r(e):n()},l=()=>!!this.isDisposingOrDisposed()&&(a(),!0);s=this.sortPromise||Promise.resolve(),s.then((()=>{if(l())return;const t=[],n=[],r=[];for(let s=0;s<this.splatMesh.scenes.length;s++){let i=!1;for(let t of e)if(t===s){i=!0;break}if(!i){const e=this.splatMesh.scenes[s];t.push(e.splatBuffer),n.push(this.splatMesh.sceneOptions[s]),r.push({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=Ss,this.createSplatMesh(),this.addSplatBuffers(t,n,!0,!1,!0).then((()=>{l()||(o(),this.splatMesh.scenes.forEach(((e,t)=>{e.position.copy(r[t].position),e.quaternion.copy(r[t].quaternion),e.scale.copy(r[t].scale)})),this.splatMesh.updateTransforms(),this.splatRenderReady=!1,this.runSplatSort(!0).then((()=>{l()?this.splatRenderReady=!0:(s=this.sortPromise||Promise.resolve(),s.then((()=>{this.splatRenderReady=!0,a()})))})))})).catch((e=>{a(e)}))}))})),this.splatSceneRemovalPromise}start(){if(!this.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");this.webXRMode?this.renderer.setAnimationLoop(this.selfDrivenUpdateFunc):this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc),this.selfDrivenModeRunning=!0}stop(){this.selfDrivenMode&&this.selfDrivenModeRunning&&(this.webXRMode?this.renderer.setAnimationLoop(null):cancelAnimationFrame(this.requestFrameId),this.selfDrivenModeRunning=!1)}async dispose(){if(this.isDisposingOrDisposed())return this.disposePromise;let e=[],t=[];for(let s in this.splatSceneDownloadPromises)if(this.splatSceneDownloadPromises.hasOwnProperty(s)){const n=this.splatSceneDownloadPromises[s];t.push(n),e.push(n.promise)}return this.sortPromise&&e.push(this.sortPromise),this.disposing=!0,this.disposePromise=Promise.all(e).finally((()=>{this.stop(),this.orthographicControls&&(this.orthographicControls.dispose(),this.orthographicControls=null),this.perspectiveControls&&(this.perspectiveControls.dispose(),this.perspectiveControls=null),this.controls=null,this.splatMesh&&(this.splatMesh.dispose(),this.splatMesh=null),this.sceneHelper&&(this.sceneHelper.dispose(),this.sceneHelper=null),this.resizeObserver&&(this.resizeObserver.unobserve(this.rootElement),this.resizeObserver=null),this.disposeSortWorker(),this.removeEventHandlers(),this.loadingSpinner.removeAllTasks(),this.loadingSpinner.setContainer(null),this.loadingProgressBar.hide(),this.loadingProgressBar.setContainer(null),this.infoPanel.setContainer(null),this.camera=null,this.threeScene=null,this.splatRenderReady=!1,this.initialized=!1,this.renderer&&(this.usingExternalRenderer||(this.rootElement.removeChild(this.renderer.domElement),this.renderer.dispose()),this.renderer=null),this.usingExternalRenderer||document.body.removeChild(this.rootElement),this.sortWorkerSortedIndexes=null,this.sortWorkerIndexesToSort=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.disposed=!0,this.disposing=!1,this.disposePromise=null})),t.forEach((e=>{e.abort("Scene disposed")})),this.disposePromise}selfDrivenUpdate(){this.selfDrivenMode&&!this.webXRMode&&(this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc)),this.update(),this.shouldRender()?(this.render(),this.consecutiveRenderFrames++):this.consecutiveRenderFrames=0,this.renderNextFrame=!1}forceRenderNextFrame(){this.renderNextFrame=!0}shouldRender=function(){let t=0;const s=new e.Vector3,n=new e.Quaternion,r=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let e=!1,i=!1;if(this.camera){const e=this.camera.position,t=this.camera.quaternion;i=Math.abs(e.x-s.x)>r||Math.abs(e.y-s.y)>r||Math.abs(e.z-s.z)>r||Math.abs(t.x-n.x)>r||Math.abs(t.y-n.y)>r||Math.abs(t.z-n.z)>r||Math.abs(t.w-n.w)>r}return e=this.renderMode!==Ps&&(0===t||this.splatMesh.visibleRegionChanging||i||this.renderMode===Rs||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(s.copy(this.camera.position),n.copy(this.camera.quaternion)),t++,e}}();render=function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return;const e=this.renderer.autoClear;(e=>{for(let t of e.children)if(t.visible)return!0;return!1})(this.threeScene)&&(this.renderer.render(this.threeScene,this.camera),this.renderer.autoClear=!1),this.renderer.render(this.splatMesh,this.camera),this.renderer.autoClear=!1,this.sceneHelper.getFocusMarkerOpacity()>0&&this.renderer.render(this.sceneHelper.focusMarker,this.camera),this.showControlPlane&&this.renderer.render(this.sceneHelper.controlPlane,this.camera),this.renderer.autoClear=e};update(e,t){this.dropInMode&&this.updateForDropInMode(e,t),this.initialized&&this.splatRenderReady&&!this.isDisposingOrDisposed()&&(this.controls&&(this.controls.update(),this.camera.isOrthographicCamera&&!this.usingExternalCamera&&Hs.setCameraPositionFromZoom(this.camera,this.camera,this.controls)),this.runSplatSort(),this.updateForRendererSizeChanges(),this.updateSplatMesh(),this.updateMeshCursor(),this.updateFPS(),this.timingSensitiveUpdates(),this.updateInfoPanel(),this.updateControlPlane())}updateForDropInMode(e,t){this.renderer=e,this.splatMesh&&this.splatMesh.setRenderer(this.renderer),this.camera=t,this.controls&&(this.controls.object=t),this.init()}updateFPS=function(){let e=f(),t=0;return function(){if(this.consecutiveRenderFrames>60){const s=f();s-e>=1?(this.currentFPS=t,t=0,e=s):t++}else this.currentFPS=null}}();updateForRendererSizeChanges=function(){const t=new e.Vector2,s=new e.Vector2;let n;return function(){this.usingExternalCamera||(this.renderer.getSize(s),void 0!==n&&n===this.camera.isOrthographicCamera&&s.x===t.x&&s.y===t.y||(this.camera.isOrthographicCamera?(this.camera.left=-s.x/2,this.camera.right=s.x/2,this.camera.top=s.y/2,this.camera.bottom=-s.y/2):this.camera.aspect=s.x/s.y,this.camera.updateProjectionMatrix(),t.copy(s),n=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){const t=f();e||(e=t);const s=t-e;this.updateCameraTransition(t),this.updateFocusMarker(s),e=t}}();updateCameraTransition=function(){let t=new e.Vector3,s=new e.Vector3,n=new e.Vector3;return function(e){if(this.transitioningCameraTarget){s.copy(this.previousCameraTarget).sub(this.camera.position).normalize(),n.copy(this.nextCameraTarget).sub(this.camera.position).normalize();const r=Math.acos(s.dot(n)),i=(r/(Math.PI/3)*.65+.3)/r*(e-this.transitioningCameraTargetStartTime);t.copy(this.previousCameraTarget).lerp(this.nextCameraTarget,i),this.camera.lookAt(t),this.controls.target.copy(t),i>=1&&(this.transitioningCameraTarget=!1)}}}();updateFocusMarker=function(){const t=new e.Vector2;let s=!1;return function(e){if(this.getRenderDimensions(t),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const n=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let r=Math.min(n+10*e,1);this.sceneHelper.setFocusMarkerOpacity(r),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,t),s=!0,this.forceRenderNextFrame()}else{let n;if(n=s?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),n>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,t);let s=Math.max(n-2.5*e,0);this.sceneHelper.setFocusMarkerOpacity(s),0===s&&this.sceneHelper.setFocusMarkerVisibility(!1)}n>0&&this.forceRenderNextFrame(),s=!1}}}();updateMeshCursor=function(){const t=[],s=new e.Vector2;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(s),t.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,s),this.raycaster.intersectSplatMesh(this.splatMesh,t),t.length>0?(this.sceneHelper.setMeshCursorVisibility(!0),this.sceneHelper.positionAndOrientMeshCursor(t[0].origin,this.camera)):this.sceneHelper.setMeshCursorVisibility(!1)):(this.sceneHelper.getMeschCursorVisibility()&&this.forceRenderNextFrame(),this.sceneHelper.setMeshCursorVisibility(!1))}}();updateInfoPanel=function(){const t=new e.Vector2;return function(){if(!this.showInfo)return;const e=this.splatMesh.getSplatCount();this.getRenderDimensions(t);const s=this.controls?this.controls.target:null,n=this.showMeshCursor?this.sceneHelper.meshCursor.position:null,r=e>0?this.splatRenderCount/e*100:0;this.infoPanel.update(t,this.camera.position,s,this.camera.up,this.camera.isOrthographicCamera,n,this.currentFPS||"N/A",e,this.splatRenderCount,r,this.lastSortTime,this.focalAdjustment,this.splatMesh.getSplatScale(),this.splatMesh.getPointCloudModeEnabled())}}();updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}runSplatSort=function(){const t=new e.Matrix4,s=[],n=new e.Vector3(0,0,-1),r=new e.Vector3(0,0,-1),i=new e.Vector3,o=new e.Vector3,a=[],l=[{angleThreshold:.55,sortFractions:[.125,.33333,.75]},{angleThreshold:.65,sortFractions:[.33333,.66667]},{angleThreshold:.8,sortFractions:[.5]}];return function(e=!1,c=!1){if(!this.initialized)return Promise.resolve(!1);if(this.sortRunning)return Promise.resolve(!0);if(this.splatMesh.getSplatCount()<=0)return this.splatRenderCount=0,Promise.resolve(!1);let h=0,d=0,p=!1,u=!1;if(r.set(0,0,-1).applyQuaternion(this.camera.quaternion),h=r.dot(n),d=o.copy(this.camera.position).sub(i).length(),!(e||this.splatMesh.dynamicMode||0!==a.length||(h<=.99&&(p=!0),d>=1&&(u=!0),p||u)))return Promise.resolve(!1);this.sortRunning=!0;let{splatRenderCount:m,shouldSortAll:A}=this.gatherSceneNodesForSort();A=A||c,this.splatRenderCount=m,t.copy(this.camera.matrixWorld).invert();const f=this.perspectiveCamera||this.camera;t.premultiply(f.projectionMatrix),this.splatMesh.dynamicMode||t.multiply(this.splatMesh.matrixWorld);let g=Promise.resolve(!0);return this.gpuAcceleratedSort&&(a.length<=1||a.length%2==0)&&(g=this.splatMesh.computeDistancesOnGPU(t,this.sortWorkerPrecomputedDistances)),g.then((()=>{if(0===a.length)if(this.splatMesh.dynamicMode||A)a.push(this.splatRenderCount);else{for(let e of l)if(h<e.angleThreshold){for(let t of e.sortFractions)a.push(Math.floor(this.splatRenderCount*t));break}a.push(this.splatRenderCount)}let e=Math.min(a.shift(),this.splatRenderCount);this.splatSortCount=e,s[0]=this.camera.position.x,s[1]=this.camera.position.y,s[2]=this.camera.position.z;const o={modelViewProj:t.elements,cameraPosition:s,splatRenderCount:this.splatRenderCount,splatSortCount:e,usePrecomputedDistances:this.gpuAcceleratedSort};return this.splatMesh.dynamicMode&&this.splatMesh.fillTransformsArray(this.sortWorkerTransforms),this.sharedMemoryForWorkers||(o.indexesToSort=this.sortWorkerIndexesToSort,o.transforms=this.sortWorkerTransforms,this.gpuAcceleratedSort&&(o.precomputedDistances=this.sortWorkerPrecomputedDistances)),this.sortPromise=new Promise((e=>{this.sortPromiseResolver=e})),this.preSortMessages.length>0&&(this.preSortMessages.forEach((e=>{this.sortWorker.postMessage(e)})),this.preSortMessages=[]),this.sortWorker.postMessage({sort:o}),0===a.length&&(i.copy(this.camera.position),n.copy(r)),!0})),g}}();gatherSceneNodesForSort=function(){const t=[];let s=null;const n=new e.Vector3,r=new e.Vector3,i=new e.Vector3,o=new e.Matrix4,a=new e.Matrix4,l=new e.Matrix4,c=new e.Vector3,h=new e.Vector3(0,0,-1),d=new e.Vector3,p=e=>d.copy(e.max).sub(e.min).length();return function(d=!1){this.getRenderDimensions(c);const u=c.y/2/Math.tan(this.camera.fov/2*e.MathUtils.DEG2RAD),m=Math.atan(c.x/2/u),A=Math.atan(c.y/2/u),f=Math.cos(m),g=Math.cos(A),S=this.splatMesh.getSplatTree();if(S){a.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||a.multiply(this.splatMesh.matrixWorld);let e=0,s=0;for(let c=0;c<S.subTrees.length;c++){const u=S.subTrees[c];o.copy(a),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(c,l),o.multiply(l));const m=u.nodesWithIndexes.length;for(let a=0;a<m;a++){const l=u.nodesWithIndexes[a];if(!l.data||!l.data.indexes||0===l.data.indexes.length)continue;i.copy(l.center).applyMatrix4(o);const c=i.length();i.normalize(),n.copy(i).setX(0).normalize(),r.copy(i).setY(0).normalize();const m=h.dot(r),A=h.dot(n),S=p(l);!d&&(m<f-.6||A<g-.6)&&c>S||(s+=l.data.indexes.length,t[e]=l,l.data.distanceToNode=c,e++)}}t.length=e,t.sort(((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1));let c=s*b.BytesPerInt;for(let s=0;s<e;s++){const e=t[s],n=e.data.indexes.length,r=n*b.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,c-r,n).set(e.data.indexes),c-=r}return{splatRenderCount:s,shouldSortAll:!1}}{const e=this.splatMesh.getSplatCount();if(!s||s.length!==e){s=new Uint32Array(e);for(let t=0;t<e;t++)s[t]=t}return this.sortWorkerIndexesToSort.set(s),{splatRenderCount:e,shouldSortAll:!0}}}}();getSplatMesh(){return this.splatMesh}getSplatScene(e){return this.splatMesh.getScene(e)}getSceneCount(){return this.splatMesh.getSceneCount()}isMobile(){return navigator.userAgent.includes("Mobi")}}class ks extends e.Group{constructor(e={}){super(),e.selfDrivenMode=!1,e.useBuiltInControls=!1,e.rootElement=null,e.dropInMode=!0,e.camera=void 0,e.renderer=void 0,this.viewer=new Hs(e),this.splatMesh=null,this.updateSplatMesh(),this.callbackMesh=ks.createCallbackMesh(),this.add(this.callbackMesh),this.callbackMesh.onBeforeRender=ks.onBeforeRender.bind(this,this.viewer),this.viewer.onSplatMeshChanged((()=>{this.updateSplatMesh()}))}updateSplatMesh(){this.splatMesh!==this.viewer.splatMesh&&(this.splatMesh&&this.remove(this.splatMesh),this.splatMesh=this.viewer.splatMesh,this.add(this.viewer.splatMesh))}addSplatScene(e,t={}){return!1!==t.showLoadingUI&&(t.showLoadingUI=!0),this.viewer.addSplatScene(e,t)}addSplatScenes(e,t){return!1!==t&&(t=!0),this.viewer.addSplatScenes(e,t)}getSplatScene(e){return this.viewer.getSplatScene(e)}removeSplatScene(e,t=!0){return this.viewer.removeSplatScene(e,t)}removeSplatScenes(e,t=!0){return this.viewer.removeSplatScenes(e,t)}getSceneCount(){return this.viewer.getSceneCount()}setActiveSphericalHarmonicsDegrees(e){this.viewer.setActiveSphericalHarmonicsDegrees(e)}async dispose(){return await this.viewer.dispose()}static onBeforeRender(e,t,s,n){e.update(t,n)}static createCallbackMesh(){const t=new e.SphereGeometry(1,8,8),s=new e.MeshBasicMaterial;s.colorWrite=!1,s.depthWrite=!1;const n=new e.Mesh(t,s);return n.frustumCulled=!1,n}}let Ls=0;const Os=[];class Us{constructor(){this.dropInViewer=this.createViewer()}async load(e){return(await this.loads([{path:e}]))[0]}async loads(e,t){Os.length&&await Promise.allSettled(Os);const s=this.dropInViewer.addSplatScenes(e,null!=t&&t);Os.push(s),await Promise.allSettled(Os);const n=[];return e.forEach((()=>n.push(Ls++))),n}createViewer(e){return new ks(Object.assign({sharedMemoryForWorkers:!1,gpuAcceleratedSort:!1,halfPrecisionCovariancesOnGPU:!0,dynamicScene:!0},e))}getSplatScene(e){return this.dropInViewer.getSplatScene(e)}getSceneCount(){return this.dropInViewer.getSceneCount()}async dispose(){this.dropInViewer&&await this.dropInViewer.dispose()}}export{Us as default};
|
|
1
|
+
import*as e from"three";import{Ray as t,Plane as n,MathUtils as s,EventDispatcher as r,Vector3 as i,MOUSE as o,TOUCH as a,Quaternion as l,Spherical as c,Vector2 as h}from"three";class d{static idGen=0;constructor(e,t){let n,s;this.promise=new Promise(((e,t)=>{n=e,s=t}));const r=n.bind(this),i=s.bind(this);e(((...e)=>{r(...e)}).bind(this),(e=>{i(e)}).bind(this)),this.abortHandler=t,this.id=d.idGen++}then(e){return new d(((t,n)=>{this.promise=this.promise.then(((...n)=>{const s=e(...n);s instanceof Promise||s instanceof d?s.then(((...e)=>{t(...e)})):t(s)})).catch((e=>{n(e)}))}),this.abortHandler)}catch(e){return new d((t=>{this.promise=this.promise.then(((...e)=>{t(...e)})).catch(e)}),this.abortHandler)}abort(e){this.abortHandler&&this.abortHandler(e)}}class p extends Error{constructor(e){super(e)}}!function(){const e=new Float32Array(1),t=new Int32Array(e.buffer)}();const u=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(n){return e[0]=n,t[0]}}(),m=function(e,t,n=!0,s){const r=new AbortController,i=r.signal;let o=!1;let a=!1;const l=(e,n,s,r)=>{t&&!a&&(t(e,n,s,r),100===e&&(a=!0))};return new d(((t,r)=>{const a={signal:i};s&&(a.headers=s),fetch(e,a).then((async e=>{if(!e.ok){const t=await e.text();return void r(new Error(`Fetch failed: ${e.status} ${e.statusText} ${t}`))}const s=e.body.getReader();let i=0,a=e.headers.get("Content-Length"),c=a?parseInt(a):void 0;const h=[];for(;!o;)try{const{value:e,done:r}=await s.read();if(r){if(l(100,"100%",e,c),n){const e=new Blob(h).arrayBuffer();t(e)}else t();break}let o,a;i+=e.length,void 0!==c&&(o=i/c*100,a=`${o.toFixed(2)}%`),n&&h.push(e),l(o,a,e,c)}catch(e){return void r(e)}})).catch((e=>{r(new p(e))}))}),(e=>{r.abort(e),o=!0}))},A=function(e,t,n){return Math.max(Math.min(e,n),t)},f=function(){return performance.now()/1e3},g=e=>{if(e.geometry&&(e.geometry.dispose(),e.geometry=null),e.material&&(e.material.dispose(),e.material=null),e.children)for(let t of e.children)g(t)},S=(e,t)=>new Promise((n=>{window.setTimeout((()=>{n(e?e():void 0)}),t?1:50)})),C=(e=0)=>{let t=0;if(1===e)t=9;else if(2===e)t=24;else if(3===e)t=45;else if(e>3)throw new Error("getSphericalHarmonicsComponentCountForDegree() -> Invalid spherical harmonics degree");return t},y=()=>{let e,t;return{promise:new Promise(((n,s)=>{e=n,t=s})),resolve:e,reject:t}},x=e=>{let t,n;e||(e=()=>{});return{promise:new d(((e,s)=>{t=e,n=s}),e),resolve:t,reject:n}};class v{constructor(e,t,n){this.major=e,this.minor=t,this.patch=n}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function I(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function B(){if(I()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new v(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}class w{static OFFSET={X:0,Y:1,Z:2,SCALE0:3,SCALE1:4,SCALE2:5,ROTATION0:6,ROTATION1:7,ROTATION2:8,ROTATION3:9,FDC0:10,FDC1:11,FDC2:12,OPACITY:13,FRC0:14,FRC1:15,FRC2:16,FRC3:17,FRC4:18,FRC5:19,FRC6:20,FRC7:21,FRC8:22,FRC9:23,FRC10:24,FRC11:25,FRC12:26,FRC13:27,FRC14:28,FRC15:29,FRC16:30,FRC17:31,FRC18:32,FRC19:33,FRC20:34,FRC21:35,FRC22:36,FRC23:37};constructor(e=0){this.sphericalHarmonicsDegree=e,this.sphericalHarmonicsCount=C(this.sphericalHarmonicsDegree),this.componentCount=this.sphericalHarmonicsCount+14,this.defaultSphericalHarmonics=new Array(this.sphericalHarmonicsCount).fill(0),this.splats=[],this.splatCount=0}static createSplat(e=0){const t=[0,0,0,1,1,1,1,0,0,0,0,0,0,0];let n=C(e);for(let e=0;e<n;e++)t.push(0);return t}addSplat(e){this.splats.push(e),this.splatCount++}getSplat(e){return this.splats[e]}addDefaultSplat(){const e=w.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(e),e}addSplatFromComonents(e,t,n,s,r,i,o,a,l,c,h,d,p,u,...m){const A=[e,t,n,s,r,i,o,a,l,c,h,d,p,u,...this.defaultSphericalHarmonics];for(let e=0;e<m.length&&e<this.sphericalHarmonicsCount;e++)A[e]=m[e];return this.addSplat(A),A}addSplatFromArray(e,t){const n=e.splats[t],s=w.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<n.length;e++)s[e]=n[e];this.addSplat(s)}}class b{static DefaultSplatSortDistanceMapPrecision=16;static MemoryPageSize=65536;static BytesPerFloat=4;static BytesPerInt=4;static MaxScenes=32;static ProgressiveLoadSectionSize=262144;static ProgressiveLoadSectionDelayDuration=15;static SphericalHarmonics8BitCompressionRange=3}const D=b.SphericalHarmonics8BitCompressionRange/2,T=e.DataUtils.toHalfFloat.bind(e.DataUtils),E=e.DataUtils.fromHalfFloat.bind(e.DataUtils),M=(t,n,s=!1,r,i)=>0===n?t:1===n||2===n&&!s?e.DataUtils.fromHalfFloat(t):2===n?R(t,r,i):void 0,F=(e,t,n)=>{e=A(e,t,n);const s=n-t;return A(Math.floor((e-t)/s*255),0,255)},R=(e,t,n)=>e/255*(n-t)+t,P=(e,t,n)=>F(E(e,t,n)),H=(e,t,n)=>T(R(e,t,n)),k=(e,t,n,s=!1)=>0===n?e.getFloat32(4*t,!0):1===n||2===n&&!s?e.getUint16(2*t,!0):e.getUint8(t,!0),L=function(){const e=e=>e;return function(t,n,s,r=!1){if(n===s)return t;let i=e;return 2===n&&r?1===s?i=H:0==s&&(i=R):2===n||1===n?0===s?i=E:2==s&&(i=r?P:e):0===n&&(1===s?i=T:2==s&&(i=r?F:T)),i(t)}}(),O=(e,t,n,s,r=0)=>{const i=new Uint8Array(e,t),o=new Uint8Array(n,s);for(let e=0;e<r;e++)o[e]=i[e]};class U{static CurrentMajorVersion=0;static CurrentMinorVersion=1;static CenterComponentCount=3;static ScaleComponentCount=3;static RotationComponentCount=4;static ColorComponentCount=4;static CovarianceComponentCount=6;static SplatScaleOffsetFloat=3;static SplatRotationOffsetFloat=6;static CompressionLevels={0:{BytesPerCenter:12,BytesPerScale:12,BytesPerRotation:16,BytesPerColor:4,ScaleOffsetBytes:12,RotationffsetBytes:24,ColorOffsetBytes:40,SphericalHarmonicsOffsetBytes:44,ScaleRange:1,BytesPerSphericalHarmonicsComponent:4,SphericalHarmonicsOffsetFloat:11,SphericalHarmonicsDegrees:{0:{BytesPerSplat:44},1:{BytesPerSplat:80},2:{BytesPerSplat:140}}},1:{BytesPerCenter:6,BytesPerScale:6,BytesPerRotation:8,BytesPerColor:4,ScaleOffsetBytes:6,RotationffsetBytes:12,ColorOffsetBytes:20,SphericalHarmonicsOffsetBytes:24,ScaleRange:32767,BytesPerSphericalHarmonicsComponent:2,SphericalHarmonicsOffsetFloat:12,SphericalHarmonicsDegrees:{0:{BytesPerSplat:24},1:{BytesPerSplat:42},2:{BytesPerSplat:72}}},2:{BytesPerCenter:6,BytesPerScale:6,BytesPerRotation:8,BytesPerColor:4,ScaleOffsetBytes:6,RotationffsetBytes:12,ColorOffsetBytes:20,SphericalHarmonicsOffsetBytes:24,ScaleRange:32767,BytesPerSphericalHarmonicsComponent:1,SphericalHarmonicsOffsetFloat:12,SphericalHarmonicsDegrees:{0:{BytesPerSplat:24},1:{BytesPerSplat:33},2:{BytesPerSplat:48}}}};static CovarianceSizeFloats=6;static HeaderSizeBytes=4096;static SectionHeaderSizeBytes=1024;static BucketStorageSizeBytes=12;static BucketStorageSizeFloats=3;static BucketBlockSize=5;static BucketSize=256;constructor(e,t=!0){this.constructFromBuffer(e,t)}getSplatCount(){return this.splatCount}getMaxSplatCount(){return this.maxSplatCount}getMinSphericalHarmonicsDegree(){let e=0;for(let t=0;t<this.sections.length;t++){const n=this.sections[t];(0===t||n.sphericalHarmonicsDegree<e)&&(e=n.sphericalHarmonicsDegree)}return e}getBucketIndex(e,t){let n;const s=e.fullBucketCount*e.bucketSize;if(t<s)n=Math.floor(t/e.bucketSize);else{let r=s;n=e.fullBucketCount;let i=0;for(;r<e.splatCount;){let s=e.partiallyFilledBucketLengths[i];if(t>=r&&t<r+s)break;r+=s,n++,i++}}return n}getSplatCenter(e,t,n){const s=this.globalSplatIndexToSectionMap[e],r=this.sections[s],i=e-r.splatCountOffset,o=r.bytesPerSplat*i,a=new DataView(this.bufferData,r.dataBase+o),l=k(a,0,this.compressionLevel),c=k(a,1,this.compressionLevel),h=k(a,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(r,i)*U.BucketStorageSizeFloats,n=r.compressionScaleFactor,s=r.compressionScaleRange;t.x=(l-s)*n+r.bucketArray[e],t.y=(c-s)*n+r.bucketArray[e+1],t.z=(h-s)*n+r.bucketArray[e+2]}else t.x=l,t.y=c,t.z=h;n&&t.applyMatrix4(n)}getSplatScaleAndRotation=function(){const t=new e.Matrix4,n=new e.Matrix4,s=new e.Matrix4,r=new e.Vector3,i=new e.Vector3,o=new e.Quaternion;return function(e,a,l,c,h){const d=this.globalSplatIndexToSectionMap[e],p=this.sections[d],u=e-p.splatCountOffset,m=p.bytesPerSplat*u+U.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,A=new DataView(this.bufferData,p.dataBase+m);i.set(M(k(A,0,this.compressionLevel),this.compressionLevel),M(k(A,1,this.compressionLevel),this.compressionLevel),M(k(A,2,this.compressionLevel),this.compressionLevel)),h&&(void 0!==h.x&&(i.x=h.x),void 0!==h.y&&(i.y=h.y),void 0!==h.z&&(i.z=h.z)),o.set(M(k(A,4,this.compressionLevel),this.compressionLevel),M(k(A,5,this.compressionLevel),this.compressionLevel),M(k(A,6,this.compressionLevel),this.compressionLevel),M(k(A,3,this.compressionLevel),this.compressionLevel)),c?(t.makeScale(i.x,i.y,i.z),n.makeRotationFromQuaternion(o),s.copy(t).multiply(n).multiply(c),s.decompose(r,l,a)):(a.copy(i),l.copy(o))}}();getSplatColor(e,t){const n=this.globalSplatIndexToSectionMap[e],s=this.sections[n],r=e-s.splatCountOffset,i=s.bytesPerSplat*r+U.CompressionLevels[this.compressionLevel].ColorOffsetBytes,o=new Uint8Array(this.bufferData,s.dataBase+i,4);t.set(o[0],o[1],o[2],o[3])}fillSplatCenterArray(t,n,s,r,i){const o=this.splatCount;s=s||0,r=r||o-1,void 0===i&&(i=s);const a=new e.Vector3;for(let e=s;e<=r;e++){const r=this.globalSplatIndexToSectionMap[e],o=this.sections[r],l=e-o.splatCountOffset,c=(e-s+i)*U.CenterComponentCount,h=o.bytesPerSplat*l,d=new DataView(this.bufferData,o.dataBase+h),p=k(d,0,this.compressionLevel),u=k(d,1,this.compressionLevel),m=k(d,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(o,l)*U.BucketStorageSizeFloats,t=o.compressionScaleFactor,n=o.compressionScaleRange;a.x=(p-n)*t+o.bucketArray[e],a.y=(u-n)*t+o.bucketArray[e+1],a.z=(m-n)*t+o.bucketArray[e+2]}else a.x=p,a.y=u,a.z=m;n&&a.applyMatrix4(n),t[c]=a.x,t[c+1]=a.y,t[c+2]=a.z}}fillSplatScaleRotationArray=function(){const t=new e.Matrix4,n=new e.Matrix4,s=new e.Matrix4,r=new e.Vector3,i=new e.Quaternion,o=new e.Vector3,a=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(e,l,c,h,d,p,u,m){const A=this.splatCount;h=h||0,d=d||A-1,void 0===p&&(p=h);const f=(e,t)=>(void 0===t&&(t=this.compressionLevel),L(e,t,u));for(let u=h;u<=d;u++){const d=this.globalSplatIndexToSectionMap[u],A=this.sections[d],g=u-A.splatCountOffset,S=A.bytesPerSplat*g+U.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,C=(u-h+p)*U.ScaleComponentCount,y=(u-h+p)*U.RotationComponentCount,x=new DataView(this.bufferData,A.dataBase+S),v=m&&void 0!==m.x?m.x:k(x,0,this.compressionLevel),I=m&&void 0!==m.y?m.y:k(x,1,this.compressionLevel),B=m&&void 0!==m.z?m.z:k(x,2,this.compressionLevel),w=k(x,3,this.compressionLevel),b=k(x,4,this.compressionLevel),D=k(x,5,this.compressionLevel),T=k(x,6,this.compressionLevel);r.set(M(v,this.compressionLevel),M(I,this.compressionLevel),M(B,this.compressionLevel)),i.set(M(b,this.compressionLevel),M(D,this.compressionLevel),M(T,this.compressionLevel),M(w,this.compressionLevel)).normalize(),c&&(o.set(0,0,0),t.makeScale(r.x,r.y,r.z),n.makeRotationFromQuaternion(i),s.identity().premultiply(t).premultiply(n),s.premultiply(c),s.decompose(o,i,r),i.normalize()),a(i),e&&(e[C]=f(r.x,0),e[C+1]=f(r.y,0),e[C+2]=f(r.z,0)),l&&(l[y]=f(i.x,0),l[y+1]=f(i.y,0),l[y+2]=f(i.z,0),l[y+3]=f(i.w,0))}}}();static computeCovariance=function(){const t=new e.Matrix4,n=new e.Matrix3,s=new e.Matrix3,r=new e.Matrix3,i=new e.Matrix3,o=new e.Matrix3,a=new e.Matrix3;return function(e,l,c,h,d=0,p){t.makeScale(e.x,e.y,e.z),n.setFromMatrix4(t),t.makeRotationFromQuaternion(l),s.setFromMatrix4(t),r.copy(s).multiply(n),i.copy(r).transpose().premultiply(r),c&&(o.setFromMatrix4(c),a.copy(o).transpose(),i.multiply(a),i.premultiply(o)),p>=1?(h[d]=T(i.elements[0]),h[d+1]=T(i.elements[3]),h[d+2]=T(i.elements[6]),h[d+3]=T(i.elements[4]),h[d+4]=T(i.elements[7]),h[d+5]=T(i.elements[8])):(h[d]=i.elements[0],h[d+1]=i.elements[3],h[d+2]=i.elements[6],h[d+3]=i.elements[4],h[d+4]=i.elements[7],h[d+5]=i.elements[8])}}();fillSplatCovarianceArray(t,n,s,r,i,o){const a=this.splatCount,l=new e.Vector3,c=new e.Quaternion;s=s||0,r=r||a-1,void 0===i&&(i=s);for(let e=s;e<=r;e++){const r=this.globalSplatIndexToSectionMap[e],a=this.sections[r],h=e-a.splatCountOffset,d=(e-s+i)*U.CovarianceComponentCount,p=a.bytesPerSplat*h+U.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,u=new DataView(this.bufferData,a.dataBase+p);l.set(M(k(u,0,this.compressionLevel),this.compressionLevel),M(k(u,1,this.compressionLevel),this.compressionLevel),M(k(u,2,this.compressionLevel),this.compressionLevel)),c.set(M(k(u,4,this.compressionLevel),this.compressionLevel),M(k(u,5,this.compressionLevel),this.compressionLevel),M(k(u,6,this.compressionLevel),this.compressionLevel),M(k(u,3,this.compressionLevel),this.compressionLevel)),U.computeCovariance(l,c,n,t,d,o)}}fillSplatColorArray(e,t,n,s,r){const i=this.splatCount;n=n||0,s=s||i-1,void 0===r&&(r=n);for(let i=n;i<=s;i++){const s=this.globalSplatIndexToSectionMap[i],o=this.sections[s],a=i-o.splatCountOffset,l=(i-n+r)*U.ColorComponentCount,c=o.bytesPerSplat*a+U.CompressionLevels[this.compressionLevel].ColorOffsetBytes,h=new Uint8Array(this.bufferData,o.dataBase+c);let d=h[3];d=d>=t?d:0,e[l]=h[0],e[l+1]=h[1],e[l+2]=h[2],e[l+3]=d}}fillSphericalHarmonicsArray=function(){for(let t=0;t<15;t++)new e.Vector3;const t=new e.Matrix3,n=new e.Matrix4,s=new e.Vector3,r=new e.Vector3,i=new e.Quaternion,o=[],a=[],l=[],c=[],h=[],d=[],p=[],u=[],m=[],A=[],f=[],g=[],S=[],y=[],x=[],v=[],I=[],B=[],w=e=>e,b=(e,t,n,s)=>{e[0]=t,e[1]=n,e[2]=s},D=(e,t,n,s,r)=>{e[0]=k(t,s,r,!0),e[1]=k(t,s+n,r,!0),e[2]=k(t,s+n+n,r,!0)},R=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},H=(e,t,n,s)=>{t[n]=s(e[0]),t[n+1]=s(e[1]),t[n+2]=s(e[2])},L=(e,t,n,s,r)=>(t[0]=M(e[0],n,!0,s,r),t[1]=M(e[1],n,!0,s,r),t[2]=M(e[2],n,!0,s,r),t);return function(e,M,k,O,z,_,Q){const V=this.splatCount;O=O||0,z=z||V-1,void 0===_&&(_=O),k&&M>=1&&(n.copy(k),n.decompose(s,i,r),i.normalize(),n.makeRotationFromQuaternion(i),t.setFromMatrix4(n),b(o,t.elements[4],-t.elements[7],t.elements[1]),b(a,-t.elements[5],t.elements[8],-t.elements[2]),b(l,t.elements[3],-t.elements[6],t.elements[0]));const N=e=>P(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),G=e=>F(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let t=O;t<=z;t++){const n=this.globalSplatIndexToSectionMap[t],s=this.sections[n];M=Math.min(M,s.sphericalHarmonicsDegree);const r=C(M),i=t-s.splatCountOffset,b=s.bytesPerSplat*i+U.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,F=new DataView(this.bufferData,s.dataBase+b),P=(t-O+_)*r;let z=k?0:this.compressionLevel,V=w;z!==Q&&(1===z?0===Q?V=E:2==Q&&(V=N):0===z&&(1===Q?V=T:2==Q&&(V=G)));const K=this.minSphericalHarmonicsCoeff,q=this.maxSphericalHarmonicsCoeff;M>=1&&(D(m,F,3,0,this.compressionLevel),D(A,F,3,1,this.compressionLevel),D(f,F,3,2,this.compressionLevel),k?(L(m,m,this.compressionLevel,K,q),L(A,A,this.compressionLevel,K,q),L(f,f,this.compressionLevel,K,q),U.rotateSphericalHarmonics3(m,A,f,o,a,l,y,x,v)):(R(m,y),R(A,x),R(f,v)),H(y,e,P,V),H(x,e,P+3,V),H(v,e,P+6,V),M>=2&&(D(m,F,5,9,this.compressionLevel),D(A,F,5,10,this.compressionLevel),D(f,F,5,11,this.compressionLevel),D(g,F,5,12,this.compressionLevel),D(S,F,5,13,this.compressionLevel),k?(L(m,m,this.compressionLevel,K,q),L(A,A,this.compressionLevel,K,q),L(f,f,this.compressionLevel,K,q),L(g,g,this.compressionLevel,K,q),L(S,S,this.compressionLevel,K,q),U.rotateSphericalHarmonics5(m,A,f,g,S,o,a,l,c,h,d,p,u,y,x,v,I,B)):(R(m,y),R(A,x),R(f,v),R(g,I),R(S,B)),H(y,e,P+9,V),H(x,e,P+12,V),H(v,e,P+15,V),H(I,e,P+18,V),H(B,e,P+21,V)))}}}();static dot3=(e,t,n,s,r)=>{r[0]=r[1]=r[2]=0;const i=s[0],o=s[1],a=s[2];U.addInto3(e[0]*i,e[1]*i,e[2]*i,r),U.addInto3(t[0]*o,t[1]*o,t[2]*o,r),U.addInto3(n[0]*a,n[1]*a,n[2]*a,r)};static addInto3=(e,t,n,s)=>{s[0]=s[0]+e,s[1]=s[1]+t,s[2]=s[2]+n};static dot5=(e,t,n,s,r,i,o)=>{o[0]=o[1]=o[2]=0;const a=i[0],l=i[1],c=i[2],h=i[3],d=i[4];U.addInto3(e[0]*a,e[1]*a,e[2]*a,o),U.addInto3(t[0]*l,t[1]*l,t[2]*l,o),U.addInto3(n[0]*c,n[1]*c,n[2]*c,o),U.addInto3(s[0]*h,s[1]*h,s[2]*h,o),U.addInto3(r[0]*d,r[1]*d,r[2]*d,o)};static rotateSphericalHarmonics3=(e,t,n,s,r,i,o,a,l)=>{U.dot3(e,t,n,s,o),U.dot3(e,t,n,r,a),U.dot3(e,t,n,i,l)};static rotateSphericalHarmonics5=(e,t,n,s,r,i,o,a,l,c,h,d,p,u,m,A,f,g)=>{const S=Math.sqrt(1/4),C=Math.sqrt(3/4),y=Math.sqrt(1/3),x=Math.sqrt(4/3),v=Math.sqrt(1/12);l[0]=S*(a[2]*i[0]+a[0]*i[2]+(i[2]*a[0]+i[0]*a[2])),l[1]=a[1]*i[0]+i[1]*a[0],l[2]=C*(a[1]*i[1]+i[1]*a[1]),l[3]=a[1]*i[2]+i[1]*a[2],l[4]=S*(a[2]*i[2]-a[0]*i[0]+(i[2]*a[2]-i[0]*a[0])),U.dot5(e,t,n,s,r,l,u),c[0]=S*(o[2]*i[0]+o[0]*i[2]+(i[2]*o[0]+i[0]*o[2])),c[1]=o[1]*i[0]+i[1]*o[0],c[2]=C*(o[1]*i[1]+i[1]*o[1]),c[3]=o[1]*i[2]+i[1]*o[2],c[4]=S*(o[2]*i[2]-o[0]*i[0]+(i[2]*o[2]-i[0]*o[0])),U.dot5(e,t,n,s,r,c,m),h[0]=y*(o[2]*o[0]+o[0]*o[2])+-v*(a[2]*a[0]+a[0]*a[2]+(i[2]*i[0]+i[0]*i[2])),h[1]=x*o[1]*o[0]+-y*(a[1]*a[0]+i[1]*i[0]),h[2]=o[1]*o[1]+-S*(a[1]*a[1]+i[1]*i[1]),h[3]=x*o[1]*o[2]+-y*(a[1]*a[2]+i[1]*i[2]),h[4]=y*(o[2]*o[2]-o[0]*o[0])+-v*(a[2]*a[2]-a[0]*a[0]+(i[2]*i[2]-i[0]*i[0])),U.dot5(e,t,n,s,r,h,A),d[0]=S*(o[2]*a[0]+o[0]*a[2]+(a[2]*o[0]+a[0]*o[2])),d[1]=o[1]*a[0]+a[1]*o[0],d[2]=C*(o[1]*a[1]+a[1]*o[1]),d[3]=o[1]*a[2]+a[1]*o[2],d[4]=S*(o[2]*a[2]-o[0]*a[0]+(a[2]*o[2]-a[0]*o[0])),U.dot5(e,t,n,s,r,d,f),p[0]=S*(a[2]*a[0]+a[0]*a[2]-(i[2]*i[0]+i[0]*i[2])),p[1]=a[1]*a[0]-i[1]*i[0],p[2]=C*(a[1]*a[1]-i[1]*i[1]),p[3]=a[1]*a[2]-i[1]*i[2],p[4]=S*(a[2]*a[2]-a[0]*a[0]-(i[2]*i[2]-i[0]*i[0])),U.dot5(e,t,n,s,r,p,g)};static parseHeader(t){const n=new Uint8Array(t,0,U.HeaderSizeBytes),s=new Uint16Array(t,0,U.HeaderSizeBytes/2),r=new Uint32Array(t,0,U.HeaderSizeBytes/4),i=new Float32Array(t,0,U.HeaderSizeBytes/4);return{versionMajor:n[0],versionMinor:n[1],maxSectionCount:r[1],sectionCount:r[2],maxSplatCount:r[3],splatCount:r[4],compressionLevel:s[10],sceneCenter:new e.Vector3(i[6],i[7],i[8]),minSphericalHarmonicsCoeff:i[9]||-D,maxSphericalHarmonicsCoeff:i[10]||D}}static writeHeaderCountsToBuffer(e,t,n){const s=new Uint32Array(n,0,U.HeaderSizeBytes/4);s[2]=e,s[4]=t}static writeHeaderToBuffer(e,t){const n=new Uint8Array(t,0,U.HeaderSizeBytes),s=new Uint16Array(t,0,U.HeaderSizeBytes/2),r=new Uint32Array(t,0,U.HeaderSizeBytes/4),i=new Float32Array(t,0,U.HeaderSizeBytes/4);n[0]=e.versionMajor,n[1]=e.versionMinor,n[2]=0,n[3]=0,r[1]=e.maxSectionCount,r[2]=e.sectionCount,r[3]=e.maxSplatCount,r[4]=e.splatCount,s[10]=e.compressionLevel,i[6]=e.sceneCenter.x,i[7]=e.sceneCenter.y,i[8]=e.sceneCenter.z,i[9]=e.minSphericalHarmonicsCoeff||-D,i[10]=e.maxSphericalHarmonicsCoeff||D}static parseSectionHeaders(e,t,n=0,s){const r=e.compressionLevel,i=e.maxSectionCount,o=new Uint16Array(t,n,i*U.SectionHeaderSizeBytes/2),a=new Uint32Array(t,n,i*U.SectionHeaderSizeBytes/4),l=new Float32Array(t,n,i*U.SectionHeaderSizeBytes/4),c=[];let h=0,d=h/2,p=h/4,u=U.HeaderSizeBytes+e.maxSectionCount*U.SectionHeaderSizeBytes,m=0;for(let e=0;e<i;e++){const t=a[p+1],n=a[p+2],i=a[p+3],A=l[p+4],f=A/2,g=o[d+10],S=a[p+6]||U.CompressionLevels[r].ScaleRange,C=a[p+8],y=a[p+9],x=4*y,v=g*i+x,I=o[d+20],{bytesPerSplat:B}=U.calculateComponentStorage(r,I),w=B*t,b=w+v,D={bytesPerSplat:B,splatCountOffset:m,splatCount:s?t:0,maxSplatCount:t,bucketSize:n,bucketCount:i,bucketBlockSize:A,halfBucketBlockSize:f,bucketStorageSizeBytes:g,bucketsStorageSizeBytes:v,splatDataStorageSizeBytes:w,storageSizeBytes:b,compressionScaleRange:S,compressionScaleFactor:f/S,base:u,bucketsBase:u+x,dataBase:u+v,fullBucketCount:C,partiallyFilledBucketCount:y,sphericalHarmonicsDegree:I};c[e]=D,u+=b,h+=U.SectionHeaderSizeBytes,d=h/2,p=h/4,m+=t}return c}static writeSectionHeaderToBuffer(e,t,n,s=0){const r=new Uint16Array(n,s,U.SectionHeaderSizeBytes/2),i=new Uint32Array(n,s,U.SectionHeaderSizeBytes/4),o=new Float32Array(n,s,U.SectionHeaderSizeBytes/4);i[0]=e.splatCount,i[1]=e.maxSplatCount,i[2]=t>=1?e.bucketSize:0,i[3]=t>=1?e.bucketCount:0,o[4]=t>=1?e.bucketBlockSize:0,r[10]=t>=1?U.BucketStorageSizeBytes:0,i[6]=t>=1?e.compressionScaleRange:0,i[7]=e.storageSizeBytes,i[8]=t>=1?e.fullBucketCount:0,i[9]=t>=1?e.partiallyFilledBucketCount:0,r[20]=e.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(e,t,n=0){new Uint32Array(t,n,U.SectionHeaderSizeBytes/4)[0]=e}constructFromBuffer(t,n){this.bufferData=t,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const s=U.parseHeader(this.bufferData);this.versionMajor=s.versionMajor,this.versionMinor=s.versionMinor,this.maxSectionCount=s.maxSectionCount,this.sectionCount=n?s.maxSectionCount:0,this.maxSplatCount=s.maxSplatCount,this.splatCount=n?s.maxSplatCount:0,this.compressionLevel=s.compressionLevel,this.sceneCenter=(new e.Vector3).copy(s.sceneCenter),this.minSphericalHarmonicsCoeff=s.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=s.maxSphericalHarmonicsCoeff,this.sections=U.parseSectionHeaders(s,this.bufferData,U.HeaderSizeBytes,n),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,t){const n=U.CompressionLevels[e].BytesPerCenter,s=U.CompressionLevels[e].BytesPerScale,r=U.CompressionLevels[e].BytesPerRotation,i=U.CompressionLevels[e].BytesPerColor,o=C(t),a=U.CompressionLevels[e].BytesPerSphericalHarmonicsComponent*o;return{bytesPerCenter:n,bytesPerScale:s,bytesPerRotation:r,bytesPerColor:i,sphericalHarmonicsComponentsPerSplat:o,sphericalHarmonicsBytesPerSplat:a,bytesPerSplat:n+s+r+i+a}}linkBufferArrays(){for(let e=0;e<this.maxSectionCount;e++){const t=this.sections[e];t.bucketArray=new Float32Array(this.bufferData,t.bucketsBase,t.bucketCount*U.BucketStorageSizeFloats),t.partiallyFilledBucketCount>0&&(t.partiallyFilledBucketLengths=new Uint32Array(this.bufferData,t.base,t.partiallyFilledBucketCount))}}buildMaps(){let e=0;for(let t=0;t<this.maxSectionCount;t++){const n=this.sections[t];for(let s=0;s<n.maxSplatCount;s++){const n=e+s;this.globalSplatIndexToLocalSplatIndexMap[n]=s,this.globalSplatIndexToSectionMap[n]=t}e+=n.maxSplatCount}}updateLoadedCounts(e,t){U.writeHeaderCountsToBuffer(e,t,this.bufferData),this.sectionCount=e,this.splatCount=t}updateSectionLoadedCounts(e,t){const n=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*e;U.writeSectionHeaderSplatCountToBuffer(t,this.bufferData,n),this.sections[e].splatCount=t}static writeSplatDataToSectionBuffer=function(){const t=new ArrayBuffer(12),n=new ArrayBuffer(12),s=new ArrayBuffer(16),r=new ArrayBuffer(4),i=new ArrayBuffer(256),o=new e.Quaternion,a=new e.Vector3,l=new e.Vector3,{X:c,Y:h,Z:d,SCALE0:p,SCALE1:u,SCALE2:m,ROTATION0:f,ROTATION1:g,ROTATION2:S,ROTATION3:y,FDC0:x,FDC1:v,FDC2:I,OPACITY:B,FRC0:b,FRC9:E}=w.OFFSET,M=(e,t,n)=>{const s=2*n+1;return e=Math.round(e*t)+n,A(e,0,s)};return function(e,A,w,R,P,H,k,L,z=-D,_=D){const Q=C(P),V=w,N=V+U.CompressionLevels[R].BytesPerCenter,G=N+U.CompressionLevels[R].BytesPerScale,K=G+U.CompressionLevels[R].BytesPerRotation,q=K+U.CompressionLevels[R].BytesPerColor;if(void 0!==e[f]?(o.set(e[f],e[g],e[S],e[y]),o.normalize()):o.set(1,0,0,0),void 0!==e[p]?a.set(e[p]||0,e[u]||0,e[m]||0):a.set(0,0,0),0===R){const t=new Float32Array(A,V,U.CenterComponentCount),n=new Float32Array(A,G,U.RotationComponentCount),s=new Float32Array(A,N,U.ScaleComponentCount);if(n.set([o.x,o.y,o.z,o.w]),s.set([a.x,a.y,a.z]),t.set([e[c],e[h],e[d]]),P>0){const t=new Float32Array(A,q,Q);if(P>=1){for(let n=0;n<9;n++)t[n]=e[b+n]||0;if(P>=2)for(let n=0;n<15;n++)t[n+9]=e[E+n]||0}}}else{const r=new Uint16Array(t,0,U.CenterComponentCount),p=new Uint16Array(s,0,U.RotationComponentCount),u=new Uint16Array(n,0,U.ScaleComponentCount);if(p.set([T(o.x),T(o.y),T(o.z),T(o.w)]),u.set([T(a.x),T(a.y),T(a.z)]),l.set(e[c],e[h],e[d]).sub(H),l.x=M(l.x,k,L),l.y=M(l.y,k,L),l.z=M(l.z,k,L),r.set([l.x,l.y,l.z]),P>0){const t=1===R?2:1,n=new(1===R?Uint16Array:Uint8Array)(i,0,Q);if(P>=1){for(let t=0;t<9;t++){const s=e[b+t]||0;n[t]=1===R?T(s):F(s,z,_)}const s=9*t;if(O(n.buffer,0,A,q,s),P>=2){for(let t=0;t<15;t++){const s=e[E+t]||0;n[t+9]=1===R?T(s):F(s,z,_)}O(n.buffer,s,A,q+s,15*t)}}}O(r.buffer,0,A,V,6),O(u.buffer,0,A,N,6),O(p.buffer,0,A,G,8)}const W=new Uint8ClampedArray(r,0,4);W.set([e[x]||0,e[v]||0,e[I]||0]),W[3]=e[B]||0,O(W.buffer,0,A,K,4)}}();static generateFromUncompressedSplatArrays(t,n,s,r,i,o,a=[]){let l,c,h=0;for(let e=0;e<t.length;e++){const n=t[e];h=Math.max(n.sphericalHarmonicsDegree,h)}for(let e=0;e<t.length;e++){const n=t[e];for(let e=0;e<n.splats.length;e++){const t=n.splats[e];for(let e=w.OFFSET.FRC0;e<w.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-D,c=c||D;const{bytesPerSplat:d}=U.calculateComponentStorage(s,h),p=U.CompressionLevels[s].ScaleRange,u=[],m=[];let A=0;for(let r=0;r<t.length;r++){const f=t[r],g=new w(h);for(let e=0;e<f.splatCount;e++){const t=f.splats[e];(t[w.OFFSET.OPACITY]||0)>=n&&g.addSplat(t)}const S=a[r]||{},C=(S.blockSizeFactor||1)*(i||U.BucketBlockSize),y=Math.ceil((S.bucketSizeFactor||1)*(o||U.BucketSize)),x=U.computeBucketsForUncompressedSplatArray(g,C,y),v=x.fullBuckets.length,I=x.partiallyFullBuckets.map((e=>e.splats.length)),B=I.length,b=[...x.fullBuckets,...x.partiallyFullBuckets],D=g.splats.length*d,T=4*B,E=s>=1?b.length*U.BucketStorageSizeBytes+T:0,M=D+E,F=new ArrayBuffer(M),R=p/(.5*C),P=new e.Vector3;let H=0;for(let e=0;e<b.length;e++){const t=b[e];P.fromArray(t.center);for(let e=0;e<t.splats.length;e++){let n=t.splats[e];const r=g.splats[n],i=E+H*d;U.writeSplatDataToSectionBuffer(r,F,i,s,h,P,R,p,l,c),H++}}if(A+=H,s>=1){const e=new Uint32Array(F,0,4*I.length);for(let t=0;t<I.length;t++)e[t]=I[t];const t=new Float32Array(F,T,b.length*U.BucketStorageSizeFloats);for(let e=0;e<b.length;e++){const n=b[e],s=3*e;t[s]=n.center[0],t[s+1]=n.center[1],t[s+2]=n.center[2]}}u.push(F);const k=new ArrayBuffer(U.SectionHeaderSizeBytes);U.writeSectionHeaderToBuffer({maxSplatCount:H,splatCount:H,bucketSize:y,bucketCount:b.length,bucketBlockSize:C,compressionScaleRange:p,storageSizeBytes:M,fullBucketCount:v,partiallyFilledBucketCount:B,sphericalHarmonicsDegree:h},s,k,0),m.push(k)}let f=0;for(let e of u)f+=e.byteLength;const g=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*u.length+f,S=new ArrayBuffer(g);U.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:u.length,sectionCount:u.length,maxSplatCount:A,splatCount:A,compressionLevel:s,sceneCenter:r,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},S);let C=U.HeaderSizeBytes;for(let e of m)new Uint8Array(S,C,U.SectionHeaderSizeBytes).set(new Uint8Array(e)),C+=U.SectionHeaderSizeBytes;for(let e of u)new Uint8Array(S,C,e.byteLength).set(new Uint8Array(e)),C+=e.byteLength;return new U(S)}static computeBucketsForUncompressedSplatArray(t,n,s){let r=t.splatCount;const i=n/2,o=new e.Vector3,a=new e.Vector3;for(let e=0;e<r;e++){const n=t.splats[e],s=[n[w.OFFSET.X],n[w.OFFSET.Y],n[w.OFFSET.Z]];(0===e||s[0]<o.x)&&(o.x=s[0]),(0===e||s[0]>a.x)&&(a.x=s[0]),(0===e||s[1]<o.y)&&(o.y=s[1]),(0===e||s[1]>a.y)&&(a.y=s[1]),(0===e||s[2]<o.z)&&(o.z=s[2]),(0===e||s[2]>a.z)&&(a.z=s[2])}const l=(new e.Vector3).copy(a).sub(o),c=Math.ceil(l.y/n),h=Math.ceil(l.z/n),d=new e.Vector3,p=[],u={};for(let e=0;e<r;e++){const r=t.splats[e],a=[r[w.OFFSET.X],r[w.OFFSET.Y],r[w.OFFSET.Z]],l=Math.floor((a[0]-o.x)/n),m=Math.floor((a[1]-o.y)/n),A=Math.floor((a[2]-o.z)/n);d.x=l*n+o.x+i,d.y=m*n+o.y+i,d.z=A*n+o.z+i;const f=l*(c*h)+m*h+A;let g=u[f];g||(u[f]=g={splats:[],center:d.toArray()}),g.splats.push(e),g.splats.length>=s&&(p.push(g),u[f]=null)}const m=[];for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];t&&m.push(t)}return{fullBuckets:p,partiallyFullBuckets:m}}static preallocateUncompressed(t,n){const s=U.CompressionLevels[0].SphericalHarmonicsDegrees[n],r=U.HeaderSizeBytes+U.SectionHeaderSizeBytes,i=r+s.BytesPerSplat*t,o=new ArrayBuffer(i);return U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:t,splatCount:t,compressionLevel:0,sceneCenter:new e.Vector3},o),U.writeSectionHeaderToBuffer({maxSplatCount:t,splatCount:t,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:n},0,o,U.HeaderSizeBytes),{splatBuffer:new U(o,!0),splatBufferDataOffsetBytes:r}}}const z=new Uint8Array([112,108,121,10]),_=new Uint8Array([10,101,110,100,95,104,101,97,100,101,114,10]),Q="end_header",V=new Map([["char",Int8Array],["uchar",Uint8Array],["short",Int16Array],["ushort",Uint16Array],["int",Int32Array],["uint",Uint32Array],["float",Float32Array],["double",Float64Array]]),N=(e,t)=>{const n=(1<<t)-1;return(e&n)/n},G=(e,t)=>{e.x=N(t>>>21,11),e.y=N(t>>>11,10),e.z=N(t,11)},K=(e,t,n)=>e*(1-n)+t*n,q=(e,t)=>e.properties.find((e=>e.name===t&&e.storage))?.storage;class W{static decodeHeaderText(e){let t,n,s,r;const i=e.split("\n").filter((e=>!e.startsWith("comment ")));let o=0,a=!1;for(let e=1;e<i.length;++e){const l=i[e].split(" ");switch(l[0]){case"format":if("binary_little_endian"!==l[1])throw new Error("Unsupported ply format");break;case"element":t={name:l[1],count:parseInt(l[2],10),properties:[],storageSizeBytes:0},"chunk"===t.name?n=t:"vertex"===t.name?s=t:"sh"===t.name&&(r=t);break;case"property":{if(!V.has(l[1]))throw new Error(`Unrecognized property data type '${l[1]}' in ply header`);const e=V.get(l[1]),n=e.BYTES_PER_ELEMENT*t.count;"vertex"===t.name&&(o+=e.BYTES_PER_ELEMENT),t.properties.push({type:l[1],name:l[2],storage:null,byteSize:e.BYTES_PER_ELEMENT,storageSizeByes:n}),t.storageSizeBytes+=n;break}case Q:a=!0;break;default:throw new Error(`Unrecognized header value '${l[0]}' in ply header`)}if(a)break}let l=0,c=0;return r&&(c=r.properties.length,r.properties.length>=45?l=3:r.properties.length>=24?l=2:r.properties.length>=9&&(l=1)),{chunkElement:n,vertexElement:s,shElement:r,bytesPerSplat:o,headerSizeBytes:e.indexOf(Q)+10+1,sphericalHarmonicsDegree:l,sphericalHarmonicsPerSplat:c}}static decodeHeader(e){let t,n=new Uint8Array(e);if(n.length>=z.length&&!((e,t)=>{if(e.length<t.length)return!1;for(let n=0;n<t.length;++n)if(e[n]!==t[n])return!1;return!0})(n,z))throw new Error("Invalid PLY header");if(t=((e,t)=>{const n=e.length-t.length;let s,r;for(s=0;s<=n;++s){for(r=0;r<t.length&&e[s+r]===t[r];++r);if(r===t.length)return s}return-1})(n,_),-1===t)throw new Error("End of PLY header not found");const s=new TextDecoder("ascii").decode(n.slice(0,t)),{chunkElement:r,vertexElement:i,shElement:o,sphericalHarmonicsDegree:a,sphericalHarmonicsPerSplat:l,bytesPerSplat:c}=W.decodeHeaderText(s);return{headerSizeBytes:t+_.length,bytesPerSplat:c,chunkElement:r,vertexElement:i,shElement:o,sphericalHarmonicsDegree:a,sphericalHarmonicsPerSplat:l}}static readElementData(e,t,n,s,r,i=null){let o=t instanceof DataView?t:new DataView(t);s=s||0,r=r||e.count-1;for(let t=s;t<=r;++t)for(let s=0;s<e.properties.length;++s){const r=e.properties[s],a=V.get(r.type),l=a.BYTES_PER_ELEMENT*e.count;if(r.storage&&!(r.storage.byteLength<l)||i&&!i(r.name)||(r.storage=new a(e.count)),r.storage)switch(r.type){case"char":r.storage[t]=o.getInt8(n);break;case"uchar":r.storage[t]=o.getUint8(n);break;case"short":r.storage[t]=o.getInt16(n,!0);break;case"ushort":r.storage[t]=o.getUint16(n,!0);break;case"int":r.storage[t]=o.getInt32(n,!0);break;case"uint":r.storage[t]=o.getUint32(n,!0);break;case"float":r.storage[t]=o.getFloat32(n,!0);break;case"double":r.storage[t]=o.getFloat64(n,!0)}n+=r.byteSize}return n}static readPly(e,t=null){const n=W.decodeHeader(e);let s=W.readElementData(n.chunkElement,e,n.headerSizeBytes,null,null,t);return s=W.readElementData(n.vertexElement,e,s,null,null,t),W.readElementData(n.shElement,e,s,null,null,t),{chunkElement:n.chunkElement,vertexElement:n.vertexElement,shElement:n.shElement,sphericalHarmonicsDegree:n.sphericalHarmonicsDegree,sphericalHarmonicsPerSplat:n.sphericalHarmonicsPerSplat}}static getElementStorageArrays(e,t,n){const s={};if(t){const n=q(e,"min_r"),r=q(e,"min_g"),i=q(e,"min_b"),o=q(e,"max_r"),a=q(e,"max_g"),l=q(e,"max_b"),c=q(e,"min_x"),h=q(e,"min_y"),d=q(e,"min_z"),p=q(e,"max_x"),u=q(e,"max_y"),m=q(e,"max_z"),A=q(e,"min_scale_x"),f=q(e,"min_scale_y"),g=q(e,"min_scale_z"),S=q(e,"max_scale_x"),C=q(e,"max_scale_y"),y=q(e,"max_scale_z"),x=q(t,"packed_position"),v=q(t,"packed_rotation"),I=q(t,"packed_scale"),B=q(t,"packed_color");s.colorExtremes={minR:n,maxR:o,minG:r,maxG:a,minB:i,maxB:l},s.positionExtremes={minX:c,maxX:p,minY:h,maxY:u,minZ:d,maxZ:m},s.scaleExtremes={minScaleX:A,maxScaleX:S,minScaleY:f,maxScaleY:C,minScaleZ:g,maxScaleZ:y},s.position=x,s.rotation=v,s.scale=I,s.color=B}if(n){const e={};for(let t=0;t<45;t++){const s=`f_rest_${t}`,r=q(n,s);if(!r)break;e[s]=r}s.sh=e}return s}static decompressBaseSplat=function(){const t=new e.Vector3,n=new e.Quaternion,s=new e.Vector3,r=new e.Vector4,i=w.OFFSET;return function(e,o,a,l,c,h,d,p,u,m){m=m||w.createSplat();const f=Math.floor((o+e)/256);var g,S;return G(t,a[e]),((e,t)=>{const n=1/(.5*Math.sqrt(2)),s=(N(t>>>20,10)-.5)*n,r=(N(t>>>10,10)-.5)*n,i=(N(t,10)-.5)*n,o=Math.sqrt(1-(s*s+r*r+i*i));switch(t>>>30){case 0:e.set(o,s,r,i);break;case 1:e.set(s,o,r,i);break;case 2:e.set(s,r,o,i);break;case 3:e.set(s,r,i,o)}})(n,d[e]),G(s,c[e]),g=r,S=u[e],g.x=N(S>>>24,8),g.y=N(S>>>16,8),g.z=N(S>>>8,8),g.w=N(S,8),m[i.X]=K(l.minX[f],l.maxX[f],t.x),m[i.Y]=K(l.minY[f],l.maxY[f],t.y),m[i.Z]=K(l.minZ[f],l.maxZ[f],t.z),m[i.ROTATION0]=n.x,m[i.ROTATION1]=n.y,m[i.ROTATION2]=n.z,m[i.ROTATION3]=n.w,m[i.SCALE0]=Math.exp(K(h.minScaleX[f],h.maxScaleX[f],s.x)),m[i.SCALE1]=Math.exp(K(h.minScaleY[f],h.maxScaleY[f],s.y)),m[i.SCALE2]=Math.exp(K(h.minScaleZ[f],h.maxScaleZ[f],s.z)),p.minR&&p.maxR?m[i.FDC0]=A(Math.round(255*K(p.minR[f],p.maxR[f],r.x)),0,255):m[i.FDC0]=A(Math.floor(255*r.x),0,255),p.minG&&p.maxG?m[i.FDC1]=A(Math.round(255*K(p.minG[f],p.maxG[f],r.y)),0,255):m[i.FDC1]=A(Math.floor(255*r.y),0,255),p.minB&&p.maxB?m[i.FDC2]=A(Math.round(255*K(p.minB[f],p.maxB[f],r.z)),0,255):m[i.FDC2]=A(Math.floor(255*r.z),0,255),m[i.OPACITY]=A(Math.floor(255*r.w),0,255),m}}();static decompressSphericalHarmonics=function(){const e=[0,3,8,15],t=[0,1,2,9,10,11,12,13,24,25,26,27,28,29,30,3,4,5,14,15,16,17,18,31,32,33,34,35,36,37,6,7,8,19,20,21,22,23,38,39,40,41,42,43,44];return function(n,s,r,i,o){o=o||w.createSplat();let a=e[r],l=e[i];for(let e=0;e<3;++e)for(let r=0;r<15;++r){const i=t[15*e+r];r<a&&r<l&&(o[w.OFFSET.FRC0+i]=s[e*l+r][n]*(8/255)-4)}return o}}();static parseToUncompressedSplatBufferSection(e,t,n,s,r,i,o,a,l=null){W.readElementData(t,i,0,n,s,l);const c=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat,{positionExtremes:h,scaleExtremes:d,colorExtremes:p,position:u,rotation:m,scale:A,color:f}=W.getElementStorageArrays(e,t),g=w.createSplat();for(let e=n;e<=s;++e){W.decompressBaseSplat(e,r,u,h,A,d,m,p,f,g);const t=e*c+a;U.writeSplatDataToSectionBuffer(g,o,t,0,0)}}static parseToUncompressedSplatArraySection(e,t,n,s,r,i,o,a=null){W.readElementData(t,i,0,n,s,a);const{positionExtremes:l,scaleExtremes:c,colorExtremes:h,position:d,rotation:p,scale:u,color:m}=W.getElementStorageArrays(e,t);for(let e=n;e<=s;++e){const t=w.createSplat();W.decompressBaseSplat(e,r,d,l,u,c,p,h,m,t),o.addSplat(t)}}static parseSphericalHarmonicsToUncompressedSplatArraySection(e,t,n,s,r,i,o,a,l,c=null){W.readElementData(t,r,i,n,s,c);const{sh:h}=W.getElementStorageArrays(e,void 0,t),d=Object.values(h);for(let e=n;e<=s;++e)W.decompressSphericalHarmonics(e,d,o,a,l.splats[e])}static parseToUncompressedSplatArray(e,t){const{chunkElement:n,vertexElement:s,shElement:r,sphericalHarmonicsDegree:i}=W.readPly(e);t=Math.min(t,i);const o=new w(t),{positionExtremes:a,scaleExtremes:l,colorExtremes:c,position:h,rotation:d,scale:p,color:u}=W.getElementStorageArrays(n,s);let m;if(t>0){const{sh:e}=W.getElementStorageArrays(n,void 0,r);m=Object.values(e)}for(let e=0;e<s.count;++e){o.addDefaultSplat();const n=o.getSplat(o.splatCount-1);W.decompressBaseSplat(e,0,h,a,p,l,d,c,u,n),t>0&&W.decompressSphericalHarmonics(e,m,t,i,n)}return o}static parseToUncompressedSplatBuffer(e,t){const{chunkElement:n,vertexElement:s,shElement:r,sphericalHarmonicsDegree:i}=W.readPly(e);t=Math.min(t,i);const{splatBuffer:o,splatBufferDataOffsetBytes:a}=U.preallocateUncompressed(s.count,t),{positionExtremes:l,scaleExtremes:c,colorExtremes:h,position:d,rotation:p,scale:u,color:m}=W.getElementStorageArrays(n,s);let A;if(t>0){const{sh:e}=W.getElementStorageArrays(n,void 0,r);A=Object.values(e)}const f=U.CompressionLevels[0].SphericalHarmonicsDegrees[t].BytesPerSplat,g=w.createSplat(t);for(let e=0;e<s.count;++e){W.decompressBaseSplat(e,0,d,l,u,c,p,h,m,g),t>0&&W.decompressSphericalHarmonics(e,A,t,i,g);const n=e*f+a;U.writeSplatDataToSectionBuffer(g,o.bufferData,n,0,t)}return o}}const j=0,Y=1,X=2,[J,Z,$,ee,te,ne,se]=[0,1,2,3,4,5,6],re={double:J,int:Z,uint:$,float:ee,short:te,ushort:ne,uchar:se},ie={[J]:8,[Z]:4,[$]:4,[ee]:4,[te]:2,[ne]:2,[se]:1};class oe{static HeaderEndToken="end_header";static decodeSectionHeader(e,t,n=0){const s=[];let r=!1,i=-1,o=0,a=!1,l=null;const c=[],h=[],d=[],p={};for(let u=n;u<e.length;u++){const m=e[u].trim();if(m.startsWith("element")){if(r){i--;break}{r=!0,n=u,i=u;const e=m.split(" ");let t=0;for(let n of e){const e=n.trim();e.length>0&&(t++,2===t?l=e:3===t&&(o=parseInt(e)))}}}else if(m.startsWith("property")){const e=m.match(/(\w+)\s+(\w+)\s+(\w+)/);if(e){const n=e[2],s=e[3];d.push(s);const r=t[s];p[s]=n;const i=re[n];void 0!==r&&(c.push(r),h[r]=i)}}if(m===oe.HeaderEndToken){a=!0;break}r&&(s.push(m),i++)}const u=[];let m=0;for(let e of d){const n=p[e];if(p.hasOwnProperty(e)){const n=t[e];void 0!==n&&(u[n]=m)}m+=ie[re[n]]}const A=oe.decodeSphericalHarmonicsFromSectionHeader(d,t);return{headerLines:s,headerStartLine:n,headerEndLine:i,fieldTypes:h,fieldIds:c,fieldOffsets:u,bytesPerVertex:m,vertexCount:o,dataSizeBytes:m*o,endOfHeader:a,sectionName:l,sphericalHarmonicsDegree:A.degree,sphericalHarmonicsCoefficientsPerChannel:A.coefficientsPerChannel,sphericalHarmonicsDegree1Fields:A.degree1Fields,sphericalHarmonicsDegree2Fields:A.degree2Fields}}static decodeSphericalHarmonicsFromSectionHeader(e,t){let n=0,s=0;for(let t of e)t.startsWith("f_rest")&&n++;s=n/3;let r=0;s>=3&&(r=1),s>=8&&(r=2);let i=[],o=[];for(let e=0;e<3;e++){if(r>=1)for(let n=0;n<3;n++)i.push(t["f_rest_"+(n+s*e)]);if(r>=2)for(let n=0;n<5;n++)o.push(t["f_rest_"+(n+s*e+3)])}return{degree:r,coefficientsPerChannel:s,degree1Fields:i,degree2Fields:o}}static getHeaderSectionNames(e){const t=[];for(let n of e)if(n.startsWith("element")){const e=n.split(" ");let s=0;for(let n of e){const e=n.trim();e.length>0&&(s++,2===s&&t.push(e))}}return t}static checkTextForEndHeader(e){return!!e.includes(oe.HeaderEndToken)}static checkBufferForEndHeader(e,t,n,s){const r=new Uint8Array(e,Math.max(0,t-n),n),i=s.decode(r);return oe.checkTextForEndHeader(i)}static extractHeaderFromBufferToText(e){const t=new TextDecoder;let n=0,s="";const r=100;for(;;){if(n+r>=e.byteLength)throw new Error("End of file reached while searching for end of header");const i=new Uint8Array(e,n,r);if(s+=t.decode(i),n+=r,oe.checkBufferForEndHeader(e,n,200,t))break}return s}static readHeaderFromBuffer(e){const t=new TextDecoder;let n=0,s="";const r=100;for(;;){if(n+r>=e.byteLength)throw new Error("End of file reached while searching for end of header");const i=new Uint8Array(e,n,r);if(s+=t.decode(i),n+=r,oe.checkBufferForEndHeader(e,n,200,t))break}return s}static convertHeaderTextToLines(e){const t=e.split("\n"),n=[];for(let e=0;e<t.length;e++){const s=t[e].trim();if(n.push(s),s===oe.HeaderEndToken)break}return n}static determineHeaderFormatFromHeaderText(e){const t=oe.convertHeaderTextToLines(e);let n=j;for(let e=0;e<t.length;e++){const s=t[e].trim();if(s.startsWith("element chunk")||s.match(/[A-Za-z]*packed_[A-Za-z]*/))n=X;else if(s.startsWith("element codebook_centers"))n=Y;else if(s===oe.HeaderEndToken)break}return n}static determineHeaderFormatFromPlyBuffer(e){const t=oe.extractHeaderFromBufferToText(e);return oe.determineHeaderFormatFromHeaderText(t)}static readVertex(e,t,n,s,r,i,o=!0){const a=n*t.bytesPerVertex+s,l=t.fieldOffsets,c=t.fieldTypes;for(let t of r){const n=c[t];n===ee?i[t]=e.getFloat32(a+l[t],!0):n===te?i[t]=e.getInt16(a+l[t],!0):n===ne?i[t]=e.getUint16(a+l[t],!0):n===Z?i[t]=e.getInt32(a+l[t],!0):n===$?i[t]=e.getUint32(a+l[t],!0):n===se&&(i[t]=o?e.getUint8(a+l[t])/255:e.getUint8(a+l[t]))}}}const ae=["scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","red","green","blue","f_rest_0"],le=ae.map(((e,t)=>t)),[ce,he,de,pe,ue,me,Ae,fe,ge,Se,Ce,ye,xe,ve,Ie,Be,we,be]=le;class De{static decodeHeaderLines(e){let t=0;e.forEach((e=>{e.includes("f_rest_")&&t++}));let n=0;t>=45?n=45:t>=24?n=24:t>=9&&(n=9);let s=Array.from(Array(Math.max(n-1,0))).map(((e,t)=>`f_rest_${t+1}`));const r=[...ae,...s],i=r.map(((e,t)=>t)),o=i.reduce(((e,t)=>(e[r[t]]=t,e)),{}),a=oe.decodeSectionHeader(e,o,0);return a.splatCount=a.vertexCount,a.bytesPerSplat=a.bytesPerVertex,a.fieldsToReadIndexes=i,a}static decodeHeaderText(e){const t=oe.convertHeaderTextToLines(e),n=De.decodeHeaderLines(t);return n.headerText=e,n.headerSizeBytes=e.indexOf(oe.HeaderEndToken)+oe.HeaderEndToken.length+1,n}static decodeHeaderFromBuffer(e){const t=oe.readHeaderFromBuffer(e);return De.decodeHeaderText(t)}static findSplatData(e,t){return new DataView(e,t.headerSizeBytes)}static parseToUncompressedSplatBufferSection(e,t,n,s,r,i,o,a=0){a=Math.min(a,e.sphericalHarmonicsDegree);const l=U.CompressionLevels[0].SphericalHarmonicsDegrees[a].BytesPerSplat;for(let c=t;c<=n;c++){const t=De.parseToUncompressedSplat(s,c,e,r,a),n=c*l+o;U.writeSplatDataToSectionBuffer(t,i,n,0,a)}}static parseToUncompressedSplatArraySection(e,t,n,s,r,i,o=0){o=Math.min(o,e.sphericalHarmonicsDegree);for(let a=t;a<=n;a++){const t=De.parseToUncompressedSplat(s,a,e,r,o);i.addSplat(t)}}static decodeSectionSplatData(e,t,n,s,r=!0){if(s=Math.min(s,n.sphericalHarmonicsDegree),r){const r=new w(s);for(let i=0;i<t;i++){const t=De.parseToUncompressedSplat(e,i,n,0,s);r.addSplat(t)}return r}{const{splatBuffer:r,splatBufferDataOffsetBytes:i}=U.preallocateUncompressed(t,s);return De.parseToUncompressedSplatBufferSection(n,0,t-1,e,0,r.bufferData,i,s),r}}static parseToUncompressedSplat=function(){let t=[];const n=new e.Quaternion,s=w.OFFSET.X,r=w.OFFSET.Y,i=w.OFFSET.Z,o=w.OFFSET.SCALE0,a=w.OFFSET.SCALE1,l=w.OFFSET.SCALE2,c=w.OFFSET.ROTATION0,h=w.OFFSET.ROTATION1,d=w.OFFSET.ROTATION2,p=w.OFFSET.ROTATION3,u=w.OFFSET.FDC0,m=w.OFFSET.FDC1,f=w.OFFSET.FDC2,g=w.OFFSET.OPACITY,S=[];for(let e=0;e<45;e++)S[e]=w.OFFSET.FRC0+e;return function(e,C,y,x=0,v=0){v=Math.min(v,y.sphericalHarmonicsDegree),De.readSplat(e,y,C,x,t);const I=w.createSplat(v);if(void 0!==t[ce]?(I[o]=Math.exp(t[ce]),I[a]=Math.exp(t[he]),I[l]=Math.exp(t[de])):(I[o]=.01,I[a]=.01,I[l]=.01),void 0!==t[Ce]){const e=.28209479177387814;I[u]=255*(.5+e*t[Ce]),I[m]=255*(.5+e*t[ye]),I[f]=255*(.5+e*t[xe])}else void 0!==t[Ie]?(I[u]=255*t[Ie],I[m]=255*t[Be],I[f]=255*t[we]):(I[u]=0,I[m]=0,I[f]=0);if(void 0!==t[ve]&&(I[g]=1/(1+Math.exp(-t[ve]))*255),I[u]=A(Math.floor(I[u]),0,255),I[m]=A(Math.floor(I[m]),0,255),I[f]=A(Math.floor(I[f]),0,255),I[g]=A(Math.floor(I[g]),0,255),v>=1&&void 0!==t[be]){for(let e=0;e<9;e++)I[S[e]]=t[y.sphericalHarmonicsDegree1Fields[e]];if(v>=2)for(let e=0;e<15;e++)I[S[9+e]]=t[y.sphericalHarmonicsDegree2Fields[e]]}return n.set(t[pe],t[ue],t[me],t[Ae]),n.normalize(),I[c]=n.x,I[h]=n.y,I[d]=n.z,I[p]=n.w,I[s]=t[fe],I[r]=t[ge],I[i]=t[Se],I}}();static readSplat(e,t,n,s,r){return oe.readVertex(e,t,n,s,t.fieldsToReadIndexes,r,!0)}static parseToUncompressedSplatArray(e,t=0){const{header:n,splatCount:s,splatData:r}=Te(e);return De.decodeSectionSplatData(r,s,n,t,!0)}static parseToUncompressedSplatBuffer(e,t=0){const{header:n,splatCount:s,splatData:r}=Te(e);return De.decodeSectionSplatData(r,s,n,t,!1)}}function Te(e){const t=De.decodeHeaderFromBuffer(e);return{header:t,splatCount:t.splatCount,splatData:De.findSplatData(e,t)}}const Ee=["features_dc","features_rest_0","features_rest_1","features_rest_2","features_rest_3","features_rest_4","features_rest_5","features_rest_6","features_rest_7","features_rest_8","features_rest_9","features_rest_10","features_rest_11","features_rest_12","features_rest_13","features_rest_14","opacity","scaling","rotation_re","rotation_im"],Me=Ee.map(((e,t)=>t)),[Fe,Re,Pe,He,ke,Le,Oe]=[0,1,4,16,17,18,19],Ue=["scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3","x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","red","green","blue","f_rest_0","f_rest_1","f_rest_2","f_rest_3","f_rest_4","f_rest_5","f_rest_6","f_rest_7","f_rest_8","f_rest_9","f_rest_10","f_rest_11","f_rest_12","f_rest_13","f_rest_14","f_rest_15","f_rest_16","f_rest_17","f_rest_18","f_rest_19","f_rest_20","f_rest_21","f_rest_22","f_rest_23","f_rest_24","f_rest_25","f_rest_26","f_rest_27","f_rest_28","f_rest_29","f_rest_30","f_rest_31","f_rest_32","f_rest_33","f_rest_34","f_rest_35","f_rest_36","f_rest_37","f_rest_38","f_rest_39","f_rest_40","f_rest_41","f_rest_42","f_rest_43","f_rest_44","f_rest_45"],ze=Ue.map(((e,t)=>t)),[_e,Qe,Ve,Ne,Ge,Ke,qe,We,je,Ye,Xe,Je,Ze,$e]=ze,et=Xe,tt=Je,nt=Ze,st=e=>{const t=(31744&e)>>10,n=1023&e;return(e>>15?-1:1)*(t?31===t?n?NaN:1/0:Math.pow(2,t-15)*(1+n/1024):n/1024*6103515625e-14)};class rt{static decodeSectionHeadersFromHeaderLines(e){const t=ze.reduce(((e,t)=>(e[Ue[t]]=t,e)),{}),n=Me.reduce(((e,t)=>(e[Ee[t]]=t,e)),{}),s=oe.getHeaderSectionNames(e);let r;for(let e=0;e<s.length;e++){"codebook_centers"===s[e]&&(r=e)}let i=0,o=!1;const a=[];let l=0;for(;!o;){let s;s=l===r?oe.decodeSectionHeader(e,n,i):oe.decodeSectionHeader(e,t,i),o=s.endOfHeader,i=s.headerEndLine+1,o||(s.splatCount=s.vertexCount,s.bytesPerSplat=s.bytesPerVertex),a.push(s),l++}return a}static decodeSectionHeadersFromHeaderText(e){const t=oe.convertHeaderTextToLines(e);return rt.decodeSectionHeadersFromHeaderLines(t)}static getSplatCountFromSectionHeaders(e){let t=0;for(let n of e)"codebook_centers"!==n.sectionName&&(t+=n.vertexCount);return t}static decodeHeaderFromHeaderText(e){const t=e.indexOf(oe.HeaderEndToken)+oe.HeaderEndToken.length+1,n=rt.decodeSectionHeadersFromHeaderText(e);return{headerSizeBytes:t,sectionHeaders:n,splatCount:rt.getSplatCountFromSectionHeaders(n)}}static decodeHeaderFromBuffer(e){const t=oe.readHeaderFromBuffer(e);return rt.decodeHeaderFromHeaderText(t)}static findVertexData(e,t,n){let s=t.headerSizeBytes;for(let e=0;e<n&&e<t.sectionHeaders.length;e++){s+=t.sectionHeaders[e].dataSizeBytes}return new DataView(e,s,t.sectionHeaders[n].dataSizeBytes)}static decodeCodeBook(e,t){const n=[],s=[];for(let r=0;r<t.vertexCount;r++){oe.readVertex(e,t,r,0,Me,n);for(let e of Me){const t=Me[e];let r=s[t];r||(s[t]=r=[]),r.push(n[e])}}for(let e=0;e<s.length;e++){const t=s[e],n=.28209479177387814;for(let s=0;s<t.length;s++){const r=st(t[s]);t[s]=e===He?Math.round(1/(1+Math.exp(-r))*255):e===Fe?Math.round(255*(.5+n*r)):e===ke?Math.exp(r):r}}return s}static decodeSectionSplatData(e,t,n,s,r){r=Math.min(r,n.sphericalHarmonicsDegree);const i=new w(r);for(let o=0;o<t;o++){const t=rt.parseToUncompressedSplat(e,o,n,s,0,r);i.addSplat(t)}return i}static parseToUncompressedSplat=function(){let t=[];const n=new e.Quaternion,s=w.OFFSET.X,r=w.OFFSET.Y,i=w.OFFSET.Z,o=w.OFFSET.SCALE0,a=w.OFFSET.SCALE1,l=w.OFFSET.SCALE2,c=w.OFFSET.ROTATION0,h=w.OFFSET.ROTATION1,d=w.OFFSET.ROTATION2,p=w.OFFSET.ROTATION3,u=w.OFFSET.FDC0,m=w.OFFSET.FDC1,f=w.OFFSET.FDC2,g=w.OFFSET.OPACITY,S=[];for(let e=0;e<45;e++)S[e]=w.OFFSET.FRC0+e;return function(e,C,y,x,v=0,I=0){I=Math.min(I,y.sphericalHarmonicsDegree),rt.readSplat(e,y,C,v,t);const B=w.createSplat(I);if(void 0!==t[_e]?(B[o]=x[ke][t[_e]],B[a]=x[ke][t[Qe]],B[l]=x[ke][t[Ve]]):(B[o]=.01,B[a]=.01,B[l]=.01),void 0!==t[Xe]?(B[u]=x[Fe][t[Xe]],B[m]=x[Fe][t[Je]],B[f]=x[Fe][t[Ze]]):void 0!==t[et]?(B[u]=255*t[et],B[m]=255*t[tt],B[f]=255*t[nt]):(B[u]=0,B[m]=0,B[f]=0),void 0!==t[$e]&&(B[g]=x[He][t[$e]]),B[u]=A(Math.floor(B[u]),0,255),B[m]=A(Math.floor(B[m]),0,255),B[f]=A(Math.floor(B[f]),0,255),B[g]=A(Math.floor(B[g]),0,255),I>=1&&y.sphericalHarmonicsDegree>=1){for(let e=0;e<9;e++){const n=x[Re+e%3];B[S[e]]=n[t[y.sphericalHarmonicsDegree1Fields[e]]]}if(I>=2&&y.sphericalHarmonicsDegree>=2)for(let e=0;e<15;e++){const n=x[Pe+e%5];B[S[9+e]]=n[t[y.sphericalHarmonicsDegree2Fields[e]]]}}const b=x[Le][t[Ne]],D=x[Oe][t[Ge]],T=x[Oe][t[Ke]],E=x[Oe][t[qe]];return n.set(b,D,T,E),n.normalize(),B[c]=n.x,B[h]=n.y,B[d]=n.z,B[p]=n.w,B[s]=st(t[We]),B[r]=st(t[je]),B[i]=st(t[Ye]),B}}();static readSplat(e,t,n,s,r){return oe.readVertex(e,t,n,s,ze,r,!1)}static parseToUncompressedSplatArray(e,t=0){const n=[],s=rt.decodeHeaderFromBuffer(e,t);let r;for(let t=0;t<s.sectionHeaders.length;t++){const n=s.sectionHeaders[t];if("codebook_centers"===n.sectionName){const i=rt.findVertexData(e,s,t);r=rt.decodeCodeBook(i,n)}}for(let i=0;i<s.sectionHeaders.length;i++){const o=s.sectionHeaders[i];if("codebook_centers"!==o.sectionName){const a=o.vertexCount,l=rt.findVertexData(e,s,i),c=rt.decodeSectionSplatData(l,a,o,r,t);n.push(c)}}const i=new w(t);for(let e of n)for(let t of e.splats)i.addSplat(t);return i}}class it{static parseToUncompressedSplatArray(e,t=0){const n=oe.determineHeaderFormatFromPlyBuffer(e);return n===X?W.parseToUncompressedSplatArray(e,t):n===j?De.parseToUncompressedSplatArray(e,t):n===Y?rt.parseToUncompressedSplatArray(e,t):void 0}static parseToUncompressedSplatBuffer(e,t=0){const n=oe.determineHeaderFormatFromPlyBuffer(e);if(n===X)return W.parseToUncompressedSplatBuffer(e,t);if(n===j)return De.parseToUncompressedSplatBuffer(e,t);if(n===Y)throw new Error("parseToUncompressedSplatBuffer() is not implemented for INRIA V2 PLY files")}}class ot{constructor(e,t,n,s){this.sectionCount=e,this.sectionFilters=t,this.groupingParameters=n,this.partitionGenerator=s}partitionUncompressedSplatArray(e){let t,n,s;if(this.partitionGenerator){const r=this.partitionGenerator(e);t=r.groupingParameters,n=r.sectionCount,s=r.sectionFilters}else t=this.groupingParameters,n=this.sectionCount,s=this.sectionFilters;const r=[];for(let t=0;t<n;t++){const n=new w(e.sphericalHarmonicsDegree),i=s[t];for(let t=0;t<e.splatCount;t++)i(t)&&n.addSplat(e.splats[t]);r.push(n)}return{splatArrays:r,parameters:t}}static getStandardPartitioner(t=0,n=new e.Vector3,s=U.BucketBlockSize,r=U.BucketSize){return new ot(void 0,void 0,void 0,(i=>{const o=w.OFFSET.X,a=w.OFFSET.Y,l=w.OFFSET.Z;t<=0&&(t=i.splatCount);const c=new e.Vector3,h=.5;i.splats.forEach((e=>{var t;c.set(e[o],e[a],e[l]).sub(n),(t=c).x=Math.floor(t.x/h)*h,t.y=Math.floor(t.y/h)*h,t.z=Math.floor(t.z/h)*h,e.centerDist=c.lengthSq()})),i.splats.sort(((e,t)=>e.centerDist>t.centerDist?1:-1));const d=[],p=[];t=Math.min(i.splatCount,t);const u=Math.ceil(i.splatCount/t);let m=0;for(let e=0;e<u;e++){let e=m;d.push((n=>n>=e&&n<e+t)),p.push({blocksSize:s,bucketSize:r}),m+=t}return{sectionCount:d.length,sectionFilters:d,groupingParameters:p}}))}}class at{constructor(t,n,s,r,i,o,a){this.splatPartitioner=t,this.alphaRemovalThreshold=n,this.compressionLevel=s,this.sectionSize=r,this.sceneCenter=i?(new e.Vector3).copy(i):void 0,this.blockSize=o,this.bucketSize=a}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return U.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(t=1,n=1,s=0,r=new e.Vector3,i=U.BucketBlockSize,o=U.BucketSize){const a=ot.getStandardPartitioner(s,r,i,o);return new at(a,t,n,s,r,i,o)}}const lt=0,ct=1,ht=2;class dt extends Error{constructor(e){super(e)}}const pt=0,ut=1,mt=2;function At(e,t){let n=0;for(let t of e)n+=t.sizeBytes;(!t||t.byteLength<n)&&(t=new ArrayBuffer(n));let s=0;for(let n of e)new Uint8Array(t,s,n.sizeBytes).set(n.data),s+=n.sizeBytes;return t}function ft(t,n,s,r,i,o,a,l){if(n){return at.getStandardGenerator(s,r,i,o,a,l).generateFromUncompressedSplatArray(t)}return U.generateFromUncompressedSplatArrays([t],s,0,new e.Vector3)}class gt{static loadFromURL(t,n,s,r,i,o,a=!0,l=0,c,h,d,p,u){let A;A=s||a?a?ut:pt:mt;const f=b.ProgressiveLoadSectionSize,g=U.HeaderSizeBytes+U.SectionHeaderSizeBytes;let C,x,v,I,B,D=0,T=0,E=0,M=!1,F=!1,R=!1;const P=y();let H,k=0,L=0,O=0,z=0,_="",Q=null,V=[];const N=new TextDecoder;return n&&n(0,"0%",lt),m(t,((t,s,i)=>{const o=t>=100;if(i&&(V.push({data:i,sizeBytes:i.byteLength,startBytes:O,endBytes:O+i.byteLength}),O+=i.byteLength),A===mt)o&&P.resolve(V);else{if(M){if(C===X&&!F){const e=Q.headerSizeBytes+Q.chunkElement.storageSizeBytes;B=At(V,B),B.byteLength>=e&&(W.readElementData(Q.chunkElement,B,Q.headerSizeBytes),k=e,L=e,F=!0)}}else if(_+=N.decode(i),oe.checkTextForEndHeader(_)){if(C=oe.determineHeaderFormatFromHeaderText(_),C===j)Q=De.decodeHeaderText(_),l=Math.min(l,Q.sphericalHarmonicsDegree),D=Q.splatCount,F=!0,z=Q.headerSizeBytes+Q.bytesPerSplat*D;else{if(C!==X){if(A===pt)throw new dt("PlyLoader.loadFromURL() -> Selected PLY format cannot be progressively loaded.");return void(A=mt)}if(Q=W.decodeHeaderText(_),l=Math.min(l,Q.sphericalHarmonicsDegree),A===pt&&l>0)throw new dt("PlyLoader.loadFromURL() -> Selected PLY format has spherical harmonics data that cannot be progressively loaded.");D=Q.vertexElement.count,z=Q.headerSizeBytes+Q.bytesPerSplat*D+Q.chunkElement.storageSizeBytes}if(A===pt){const t=U.CompressionLevels[0].SphericalHarmonicsDegrees[l],n=g+t.BytesPerSplat*D;v=new ArrayBuffer(n),U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:D,splatCount:0,compressionLevel:0,sceneCenter:new e.Vector3},v)}else H=new w(l);k=Q.headerSizeBytes,L=Q.headerSizeBytes,M=!0}if(M&&F&&V.length>0){x=At(V,x);if(O-k>f||O>=z&&!R||o){const e=R?Q.sphericalHarmonicsPerSplat:Q.bytesPerSplat,t=(R?O:Math.min(z,O))-L,n=Math.floor(t/e),s=n*e,r=O-L-s,i=L-V[0].startBytes,o=new DataView(x,i,s);if(R)C===X&&A===ut&&(W.parseSphericalHarmonicsToUncompressedSplatArraySection(Q.chunkElement,Q.shElement,E,E+n-1,o,0,l,Q.sphericalHarmonicsDegree,H),E+=n);else{if(A===pt){const e=U.CompressionLevels[0].SphericalHarmonicsDegrees[l],t=T*e.BytesPerSplat+g;C===X?W.parseToUncompressedSplatBufferSection(Q.chunkElement,Q.vertexElement,0,n-1,T,o,v,t):De.parseToUncompressedSplatBufferSection(Q,0,n-1,o,0,v,t,l)}else C===X?W.parseToUncompressedSplatArraySection(Q.chunkElement,Q.vertexElement,0,n-1,T,o,H):De.parseToUncompressedSplatArraySection(Q,0,n-1,o,0,H,l);T+=n,A===pt&&(I||(U.writeSectionHeaderToBuffer({maxSplatCount:D,splatCount:T,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:l},0,v,U.HeaderSizeBytes),I=new U(v,!1)),I.updateLoadedCounts(1,T)),O>=z&&(R=!0)}if(0===r)V=[];else{let e=[],t=0;for(let n=V.length-1;n>=0;n--){const s=V[n];if(t+=s.sizeBytes,e.unshift(s),t>=r)break}V=e}k+=f,L+=s}}r&&I&&r(I,o),o&&(A===pt?P.resolve(I):P.resolve(H))}n&&n(t,s,lt)}),!1,c).then((()=>(n&&n(0,"0%",ct),P.promise.then((e=>{if(n&&n(100,"100%",ht),A===mt){const e=V.map((e=>e.data));return new Blob(e).arrayBuffer().then((e=>gt.loadFromFileData(e,i,o,a,l,h,d,p,u)))}return A===pt?e:S((()=>ft(e,a,i,o,h,d,p,u)))})))))}static loadFromFileData(e,t,n,s,r=0,i,o,a,l){return s?S((()=>it.parseToUncompressedSplatArray(e,r))).then((e=>ft(e,s,t,n,i,o,a,l))):S((()=>it.parseToUncompressedSplatBuffer(e,r)))}}const St=e=>new ReadableStream({async start(t){t.enqueue(e),t.close()}});async function Ct(e){try{const t=St(e);if(!t)throw new Error("Failed to create stream from data");return await async function(e){const t=e.pipeThrough(new DecompressionStream("gzip")),n=new Response(t),s=await n.arrayBuffer();return new Uint8Array(s)}(t)}catch(e){throw console.error("Error decompressing gzipped data:",e),e}}const yt=1347635022,xt=1;function vt(e){const t=e>>10&31,n=1023&e,s=1===(e>>15&1)?-1:1;return 0===t?s*Math.pow(2,-14)*n/1024:31===t?0!==n?NaN:s*(1/0):s*Math.pow(2,t-15)*(1+n/1024)}function It(e){switch(e){case 0:return 0;case 1:return 3;case 2:return 8;case 3:return 15;default:return console.error(`[SPZ: ERROR] Unsupported SH degree: ${e}`),0}}const Bt=function(){let t=[];const n=new e.Quaternion,s=w.OFFSET.X,r=w.OFFSET.Y,i=w.OFFSET.Z,o=w.OFFSET.SCALE0,a=w.OFFSET.SCALE1,l=w.OFFSET.SCALE2,c=w.OFFSET.ROTATION0,h=w.OFFSET.ROTATION1,d=w.OFFSET.ROTATION2,p=w.OFFSET.ROTATION3,u=w.OFFSET.FDC0,m=w.OFFSET.FDC1,f=w.OFFSET.FDC2,g=w.OFFSET.OPACITY,S=[It(0),It(1),It(2),It(3)],C=[0,1,2,9,10,11,12,13,24,25,26,27,28,29,30,3,4,5,14,15,16,17,18,31,32,33,34,35,36,37,6,7,8,19,20,21,22,23,38,39,40,41,42,43,44];return function(e,y,x){x=Math.min(y,x);const v=w.createSplat(x);void 0!==e.scale[0]?(v[o]=e.scale[0],v[a]=e.scale[1],v[l]=e.scale[2]):(v[o]=.01,v[a]=.01,v[l]=.01),void 0!==e.color[0]?(v[u]=e.color[0],v[m]=e.color[1],v[f]=e.color[2]):void 0!==t[RED]?(v[u]=255*t[RED],v[m]=255*t[GREEN],v[f]=255*t[BLUE]):(v[u]=0,v[m]=0,v[f]=0),void 0!==e.alpha&&(v[g]=e.alpha),v[u]=A(Math.floor(v[u]),0,255),v[m]=A(Math.floor(v[m]),0,255),v[f]=A(Math.floor(v[f]),0,255),v[g]=A(Math.floor(v[g]),0,255);let I=S[x],B=S[y];for(let t=0;t<3;++t)for(let n=0;n<15;++n){const s=C[15*t+n];n<I&&n<B&&(v[w.OFFSET.FRC0+s]=e.sh[t*B+n])}return n.set(e.rotation[3],e.rotation[0],e.rotation[1],e.rotation[2]),n.normalize(),v[c]=n.x,v[h]=n.y,v[d]=n.z,v[p]=n.w,v[s]=e.position[0],v[r]=e.position[1],v[i]=e.position[2],v}}();function wt(e,t,n,s,r){t=Math.min(t,e.shDegree);const i=e.numPoints,o=It(e.shDegree),a=e.positions.length===3*i*2;if(!function(e,t,n,s){return e.positions.length===3*t*(s?2:3)&&e.scales.length===3*t&&e.rotations.length===3*t&&e.alphas.length===t&&e.colors.length===3*t&&e.sh.length===t*n*3}(e,i,o,a))return null;const l={position:[],scale:[],rotation:[],alpha:void 0,color:[],sh:[]};let c;a&&(c=new Uint16Array(e.positions.buffer,e.positions.byteOffset,3*i));const h=1/(1<<e.fractionalBits),d=It(e.shDegree);for(let o=0;o<i;o++){if(a)for(let e=0;e<3;e++)l.position[e]=vt(c[3*o+e]);else for(let t=0;t<3;t++){const n=9*o+3*t;let s=e.positions[n];s|=e.positions[n+1]<<8,s|=e.positions[n+2]<<16,s|=8388608&s?4278190080:0,l.position[t]=s*h}for(let t=0;t<3;t++)l.scale[t]=Math.exp(e.scales[3*o+t]/16-10);const i=e.rotations.subarray(3*o,3*o+3),p=[i[0]/127.5-1,i[1]/127.5-1,i[2]/127.5-1];l.rotation[0]=p[0],l.rotation[1]=p[1],l.rotation[2]=p[2];const u=p[0]*p[0]+p[1]*p[1]+p[2]*p[2];l.rotation[3]=Math.sqrt(Math.max(0,1-u)),l.alpha=Math.floor(e.alphas[o]);for(let t=0;t<3;t++)l.color[t]=Math.floor(255*((e.colors[3*o+t]/255-.5)/.15*.28209479177387814+.5));for(let t=0;t<3;t++)for(let n=0;n<d;n++)l.sh[t*d+n]=(e.sh[3*d*o+3*n+t]-128)/128;const m=Bt(l,e.shDegree,t);if(n){const e=o*U.CompressionLevels[0].SphericalHarmonicsDegrees[t].BytesPerSplat+r;U.writeSplatDataToSectionBuffer(m,s,e,0,t)}else s.addSplat(m)}}const bt=16,Dt=1e7;async function Tt(e){try{return function(e){const t=new DataView(e);let n=0;const s={magic:t.getUint32(n,!0),version:t.getUint32(n+4,!0),numPoints:t.getUint32(n+8,!0),shDegree:t.getUint8(n+12),fractionalBits:t.getUint8(n+13),flags:t.getUint8(n+14),reserved:t.getUint8(n+15)};if(n+=bt,s.magic!==yt)return console.error("[SPZ ERROR] deserializePackedGaussians: header not found"),null;if(s.version<1||s.version>2)return console.error(`[SPZ ERROR] deserializePackedGaussians: version not supported: ${s.version}`),null;if(s.numPoints>Dt)return console.error(`[SPZ ERROR] deserializePackedGaussians: Too many points: ${s.numPoints}`),null;if(s.shDegree>3)return console.error(`[SPZ ERROR] deserializePackedGaussians: Unsupported SH degree: ${s.shDegree}`),null;const r=s.numPoints,i=It(s.shDegree),o={numPoints:r,shDegree:s.shDegree,fractionalBits:s.fractionalBits,antialiased:0!=(s.flags&xt),positions:new Uint8Array(3*r*(1===s.version?2:3)),scales:new Uint8Array(3*r),rotations:new Uint8Array(3*r),alphas:new Uint8Array(r),colors:new Uint8Array(3*r),sh:new Uint8Array(r*i*3)};try{const t=new Uint8Array(e);let s=o.positions.length,r=n;if(o.positions.set(t.slice(r,r+s)),r+=s,o.alphas.set(t.slice(r,r+o.alphas.length)),r+=o.alphas.length,o.colors.set(t.slice(r,r+o.colors.length)),r+=o.colors.length,o.scales.set(t.slice(r,r+o.scales.length)),r+=o.scales.length,o.rotations.set(t.slice(r,r+o.rotations.length)),r+=o.rotations.length,o.sh.set(t.slice(r,r+o.sh.length)),r+o.sh.length!==e.byteLength)return console.error("[SPZ ERROR] deserializePackedGaussians: incorrect buffer size"),null}catch(e){return console.error("[SPZ ERROR] deserializePackedGaussians: read error",e),null}return o}((await Ct(e)).buffer)}catch(e){return console.error("[SPZ ERROR] loadSpzPacked: decompression error",e),null}}class Et{static loadFromURL(e,t,n,s,r=!0,i=0,o,a,l,c,h){return t&&t(0,"0%",lt),m(e,t,!0,o).then((e=>(t&&t(0,"0%",ct),Et.loadFromFileData(e,n,s,r,i,a,l,c,h))))}static async loadFromFileData(e,t,n,s,r=0,i,o,a,l){await S();const c=await Tt(e);r=Math.min(c.shDegree,r);const h=new w(r);if(s){wt(c,r,!1,h,0);return at.getStandardGenerator(t,n,i,o,a,l).generateFromUncompressedSplatArray(h)}{const{splatBuffer:e,splatBufferDataOffsetBytes:t}=U.preallocateUncompressed(c.numPoints,r);return wt(c,r,!0,e.bufferData,t),e}}}class Mt{static RowSizeBytes=32;static CenterSizeBytes=12;static ScaleSizeBytes=12;static RotationSizeBytes=4;static ColorSizeBytes=4;static parseToUncompressedSplatBufferSection(t,n,s,r,i,o){const a=U.CompressionLevels[0].BytesPerCenter,l=U.CompressionLevels[0].BytesPerScale,c=U.CompressionLevels[0].BytesPerRotation,h=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;for(let d=t;d<=n;d++){const t=d*Mt.RowSizeBytes+r,n=new Float32Array(s,t,3),p=new Float32Array(s,t+Mt.CenterSizeBytes,3),u=new Uint8Array(s,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes,4),m=new Uint8Array(s,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes+Mt.RotationSizeBytes,4),A=new e.Quaternion((m[1]-128)/128,(m[2]-128)/128,(m[3]-128)/128,(m[0]-128)/128);A.normalize();const f=d*h+o,g=new Float32Array(i,f,3),S=new Float32Array(i,f+a,3),C=new Float32Array(i,f+a+l,4),y=new Uint8Array(i,f+a+l+c,4);g[0]=n[0],g[1]=n[1],g[2]=n[2],S[0]=p[0],S[1]=p[1],S[2]=p[2],C[0]=A.w,C[1]=A.x,C[2]=A.y,C[3]=A.z,y[0]=u[0],y[1]=u[1],y[2]=u[2],y[3]=u[3]}}static parseToUncompressedSplatArraySection(t,n,s,r,i){for(let o=t;o<=n;o++){const t=o*Mt.RowSizeBytes+r,n=new Float32Array(s,t,3),a=new Float32Array(s,t+Mt.CenterSizeBytes,3),l=new Uint8Array(s,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes,4),c=new Uint8Array(s,t+Mt.CenterSizeBytes+Mt.ScaleSizeBytes+Mt.RotationSizeBytes,4),h=new e.Quaternion((c[1]-128)/128,(c[2]-128)/128,(c[3]-128)/128,(c[0]-128)/128);h.normalize(),i.addSplatFromComonents(n[0],n[1],n[2],a[0],a[1],a[2],h.w,h.x,h.y,h.z,l[0],l[1],l[2],l[3])}}static parseStandardSplatToUncompressedSplatArray(t){const n=t.byteLength/Mt.RowSizeBytes,s=new w;for(let r=0;r<n;r++){const n=r*Mt.RowSizeBytes,i=new Float32Array(t,n,3),o=new Float32Array(t,n+Mt.CenterSizeBytes,3),a=new Uint8Array(t,n+Mt.CenterSizeBytes+Mt.ScaleSizeBytes,4),l=new Uint8Array(t,n+Mt.CenterSizeBytes+Mt.ScaleSizeBytes+Mt.ColorSizeBytes,4),c=new e.Quaternion((l[1]-128)/128,(l[2]-128)/128,(l[3]-128)/128,(l[0]-128)/128);c.normalize(),s.addSplatFromComonents(i[0],i[1],i[2],o[0],o[1],o[2],c.w,c.x,c.y,c.z,a[0],a[1],a[2],a[3])}return s}}function Ft(t,n,s,r,i,o,a,l){if(n){return at.getStandardGenerator(s,r,i,o,a,l).generateFromUncompressedSplatArray(t)}return U.generateFromUncompressedSplatArrays([t],s,0,new e.Vector3)}class Rt{static loadFromURL(t,n,s,r,i,o,a=!0,l,c,h,d,p){let u=s?pt:ut;a&&(u=ut);const A=U.HeaderSizeBytes+U.SectionHeaderSizeBytes,f=b.ProgressiveLoadSectionSize;let g,C,x,v,I=0,B=0;const D=y();let T=0,E=0,M=[];return n&&n(0,"0%",lt),m(t,((t,i,o,a)=>{const l=t>=100;if(o&&M.push(o),u!==mt)if(a){if(!g){I=a/Mt.RowSizeBytes,g=new ArrayBuffer(a);const t=U.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;u===pt?(C=new ArrayBuffer(A+t*I),U.writeHeaderToBuffer({versionMajor:U.CurrentMajorVersion,versionMinor:U.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:I,splatCount:B,compressionLevel:0,sceneCenter:new e.Vector3},C)):v=new w(0)}if(o){new Uint8Array(g,E,o.byteLength).set(new Uint8Array(o)),E+=o.byteLength;const e=E-T;if(e>f||l){const t=(l?e:f)/Mt.RowSizeBytes,n=B+t;u===pt?Mt.parseToUncompressedSplatBufferSection(B,n-1,g,0,C,A):Mt.parseToUncompressedSplatArraySection(B,n-1,g,0,v),B=n,u===pt&&(x||(U.writeSectionHeaderToBuffer({maxSplatCount:I,splatCount:B,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0},0,C,U.HeaderSizeBytes),x=new U(C,!1)),x.updateLoadedCounts(1,B),r&&r(x,l)),T+=f}}l&&(u===pt?D.resolve(x):D.resolve(v)),n&&n(t,i,lt)}else{if(s)throw new dt("Cannon directly load .splat because no file size info is available.");u=mt}else l&&D.resolve(M)}),!1,l).then((()=>(n&&n(0,"0%",ct),D.promise.then((e=>(n&&n(100,"100%",ht),u===mt?new Blob(M).arrayBuffer().then((e=>Rt.loadFromFileData(e,i,o,a,c,h,d,p))):u===pt?e:S((()=>Ft(e,a,i,o,c,h,d,p)))))))))}static loadFromFileData(e,t,n,s,r,i,o,a){return S((()=>Ft(Mt.parseStandardSplatToUncompressedSplatArray(e),s,t,n,r,i,o,a)))}}class Pt{static checkVersion(e){const t=U.CurrentMajorVersion,n=U.CurrentMinorVersion,s=U.parseHeader(e);if(s.versionMajor===t&&s.versionMinor>=n||s.versionMajor>t)return!0;throw new Error(`KSplat version not supported: v${s.versionMajor}.${s.versionMinor}. Minimum required: v${t}.${n}`)}static loadFromURL(e,t,n,s,r){let i,o,a,l,c,h=!1,d=!1,p=[],u=!1,A=!1,f=0,g=0,S=0,C=!1,x=!1,v=!1,I=[];const B=y();let w=0;const D=()=>{const e=()=>{A=!0;new Blob(I).arrayBuffer().then((e=>{A=!1,u=!0,c=new ArrayBuffer(l.maxSectionCount*U.SectionHeaderSizeBytes),new Uint8Array(c).set(new Uint8Array(e,U.HeaderSizeBytes,l.maxSectionCount*U.SectionHeaderSizeBytes)),p=U.parseSectionHeaders(l,c,0,!1);let t=0;for(let e=0;e<l.maxSectionCount;e++)t+=p[e].storageSizeBytes;const n=U.HeaderSizeBytes+l.maxSectionCount*U.SectionHeaderSizeBytes+t;if(!i){i=new ArrayBuffer(n);let e=0;for(let t=0;t<I.length;t++){const n=I[t];new Uint8Array(i,e,n.byteLength).set(new Uint8Array(n)),e+=n.byteLength}}S=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*l.maxSectionCount;for(let e=0;e<=p.length&&e<l.maxSectionCount;e++)S+=p[e].storageSizeBytes;0===w&&(w++,window.setTimeout((()=>{w--,T()}),1))}))};!A&&!u&&h&&f>=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*l.maxSectionCount&&e()},T=()=>{if(v)return;v=!0;window.setTimeout((()=>{if(v=!1,u){if(x)return;if(C=f>=S,f-g>b.ProgressiveLoadSectionSize||C){g+=b.ProgressiveLoadSectionSize,x=g>=S,o||(o=new U(i,!1));const e=U.HeaderSizeBytes+U.SectionHeaderSizeBytes*l.maxSectionCount;let n=0,r=0,a=0;for(let t=0;t<l.maxSectionCount;t++){const s=p[t],i=e+(n+4*s.partiallyFilledBucketCount+s.bucketStorageSizeBytes*s.bucketCount);if(!(g>=i))break;{r++;const e=g-i,n=U.CompressionLevels[l.compressionLevel].SphericalHarmonicsDegrees[s.sphericalHarmonicsDegree].BytesPerSplat;let c=Math.floor(e/n);c=Math.min(c,s.maxSplatCount),a+=c,o.updateLoadedCounts(r,a),o.updateSectionLoadedCounts(t,c)}n+=s.storageSizeBytes}s(o,x);const c=g/S*100,h=c.toFixed(2)+"%";t&&t(c,h,lt),x?B.resolve(o):T()}}}),b.ProgressiveLoadSectionDelayDuration)};return m(e,((e,s,r)=>{r&&(I.push(r),i&&new Uint8Array(i,f,r.byteLength).set(new Uint8Array(r)),f+=r.byteLength),n?(!h&&!d&&f>=U.HeaderSizeBytes&&(d=!0,new Blob(I).arrayBuffer().then((e=>{a=new ArrayBuffer(U.HeaderSizeBytes),new Uint8Array(a).set(new Uint8Array(e,0,U.HeaderSizeBytes)),Pt.checkVersion(a),d=!1,h=!0,l=U.parseHeader(a),window.setTimeout((()=>{D()}),1)}))),D(),T()):t&&t(e,s,lt)}),!n,r).then((e=>{t&&t(0,"0%",ct);return(n?B.promise:Pt.loadFromFileData(e)).then((e=>(t&&t(100,"100%",ht),e)))}))}static loadFromFileData(e){return S((()=>(Pt.checkVersion(e),new U(e))))}static downloadFile=function(){let e;return function(t,n){const s=new Blob([t.bufferData],{type:"application/octet-stream"});e||(e=document.createElement("a"),document.body.appendChild(e)),e.download=n,e.href=URL.createObjectURL(s),e.click()}}()}const Ht=0,kt=1,Lt=2,Ot=3,Ut=e=>e.endsWith(".ply")?Lt:e.endsWith(".splat")?Ht:e.endsWith(".ksplat")?kt:e.endsWith(".spz")?Ot:null,zt={type:"change"},_t={type:"start"},Qt={type:"end"},Vt=new t,Nt=new n,Gt=Math.cos(70*s.DEG2RAD);class Kt extends r{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new i,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"KeyA",UP:"KeyW",RIGHT:"KeyD",BOTTOM:"KeyS"},this.mouseButtons={LEFT:o.ROTATE,MIDDLE:o.DOLLY,RIGHT:o.PAN},this.touches={ONE:a.ROTATE,TWO:a.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return p.phi},this.getAzimuthalAngle=function(){return p.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(e){e.addEventListener("keydown",Z),this._domElementKeyEvents=e},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Z),this._domElementKeyEvents=null},this.saveState=function(){n.target0.copy(n.target),n.position0.copy(n.object.position),n.zoom0=n.object.zoom},this.reset=function(){n.target.copy(n.target0),n.object.position.copy(n.position0),n.object.zoom=n.zoom0,this.clearDampedRotation(),this.clearDampedPan(),n.object.updateProjectionMatrix(),n.dispatchEvent(zt),n.update(),r=s.NONE},this.clearDampedRotation=function(){u.theta=0,u.phi=0},this.clearDampedPan=function(){A.set(0,0,0)},this.update=function(){const t=new i,o=(new l).setFromUnitVectors(e.up,new i(0,1,0)),a=o.clone().invert(),c=new i,h=new l,f=new i,g=2*Math.PI;return function(){o.setFromUnitVectors(e.up,new i(0,1,0)),a.copy(o).invert();const l=n.object.position;t.copy(l).sub(n.target),t.applyQuaternion(o),p.setFromVector3(t),n.autoRotate&&r===s.NONE&&F(2*Math.PI/60/60*n.autoRotateSpeed),n.enableDamping?(p.theta+=u.theta*n.dampingFactor,p.phi+=u.phi*n.dampingFactor):(p.theta+=u.theta,p.phi+=u.phi);let S=n.minAzimuthAngle,C=n.maxAzimuthAngle;isFinite(S)&&isFinite(C)&&(S<-Math.PI?S+=g:S>Math.PI&&(S-=g),C<-Math.PI?C+=g:C>Math.PI&&(C-=g),p.theta=S<=C?Math.max(S,Math.min(C,p.theta)):p.theta>(S+C)/2?Math.max(S,p.theta):Math.min(C,p.theta)),p.phi=Math.max(n.minPolarAngle,Math.min(n.maxPolarAngle,p.phi)),p.makeSafe(),!0===n.enableDamping?n.target.addScaledVector(A,n.dampingFactor):n.target.add(A),n.zoomToCursor&&D||n.object.isOrthographicCamera?p.radius=z(p.radius):p.radius=z(p.radius*m),t.setFromSpherical(p),t.applyQuaternion(a),l.copy(n.target).add(t),n.object.lookAt(n.target),!0===n.enableDamping?(u.theta*=1-n.dampingFactor,u.phi*=1-n.dampingFactor,A.multiplyScalar(1-n.dampingFactor)):(u.set(0,0,0),A.set(0,0,0));let y=!1;if(n.zoomToCursor&&D){let s=null;if(n.object.isPerspectiveCamera){const e=t.length();s=z(e*m);const r=e-s;n.object.position.addScaledVector(w,r),n.object.updateMatrixWorld()}else if(n.object.isOrthographicCamera){const e=new i(b.x,b.y,0);e.unproject(n.object),n.object.zoom=Math.max(n.minZoom,Math.min(n.maxZoom,n.object.zoom/m)),n.object.updateProjectionMatrix(),y=!0;const r=new i(b.x,b.y,0);r.unproject(n.object),n.object.position.sub(r).add(e),n.object.updateMatrixWorld(),s=t.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),n.zoomToCursor=!1;null!==s&&(this.screenSpacePanning?n.target.set(0,0,-1).transformDirection(n.object.matrix).multiplyScalar(s).add(n.object.position):(Vt.origin.copy(n.object.position),Vt.direction.set(0,0,-1).transformDirection(n.object.matrix),Math.abs(n.object.up.dot(Vt.direction))<Gt?e.lookAt(n.target):(Nt.setFromNormalAndCoplanarPoint(n.object.up,n.target),Vt.intersectPlane(Nt,n.target))))}else n.object.isOrthographicCamera&&(n.object.zoom=Math.max(n.minZoom,Math.min(n.maxZoom,n.object.zoom/m)),n.object.updateProjectionMatrix(),y=!0);return m=1,D=!1,!!(y||c.distanceToSquared(n.object.position)>d||8*(1-h.dot(n.object.quaternion))>d||f.distanceToSquared(n.target)>0)&&(n.dispatchEvent(zt),c.copy(n.object.position),h.copy(n.object.quaternion),f.copy(n.target),y=!1,!0)}}(),this.dispose=function(){n.domElement.removeEventListener("contextmenu",$),n.domElement.removeEventListener("pointerdown",j),n.domElement.removeEventListener("pointercancel",X),n.domElement.removeEventListener("wheel",J),n.domElement.removeEventListener("pointermove",Y),n.domElement.removeEventListener("pointerup",X),null!==n._domElementKeyEvents&&(n._domElementKeyEvents.removeEventListener("keydown",Z),n._domElementKeyEvents=null)};const n=this,s={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=s.NONE;const d=1e-6,p=new c,u=new c;let m=1;const A=new i,f=new h,g=new h,S=new h,C=new h,y=new h,x=new h,v=new h,I=new h,B=new h,w=new i,b=new h;let D=!1;const T=[],E={};function M(){return Math.pow(.95,n.zoomSpeed)}function F(e){u.theta-=e}function R(e){u.phi-=e}const P=function(){const e=new i;return function(t,n){e.setFromMatrixColumn(n,0),e.multiplyScalar(-t),A.add(e)}}(),H=function(){const e=new i;return function(t,s){!0===n.screenSpacePanning?e.setFromMatrixColumn(s,1):(e.setFromMatrixColumn(s,0),e.crossVectors(n.object.up,e)),e.multiplyScalar(t),A.add(e)}}(),k=function(){const e=new i;return function(t,s){const r=n.domElement;if(n.object.isPerspectiveCamera){const i=n.object.position;e.copy(i).sub(n.target);let o=e.length();o*=Math.tan(n.object.fov/2*Math.PI/180),P(2*t*o/r.clientHeight,n.object.matrix),H(2*s*o/r.clientHeight,n.object.matrix)}else n.object.isOrthographicCamera?(P(t*(n.object.right-n.object.left)/n.object.zoom/r.clientWidth,n.object.matrix),H(s*(n.object.top-n.object.bottom)/n.object.zoom/r.clientHeight,n.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),n.enablePan=!1)}}();function L(e){n.object.isPerspectiveCamera||n.object.isOrthographicCamera?m/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),n.enableZoom=!1)}function O(e){n.object.isPerspectiveCamera||n.object.isOrthographicCamera?m*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),n.enableZoom=!1)}function U(t){if(!n.zoomToCursor)return;D=!0;const s=n.domElement.getBoundingClientRect(),r=t.clientX-s.left,i=t.clientY-s.top,o=s.width,a=s.height;b.x=r/o*2-1,b.y=-i/a*2+1,w.set(b.x,b.y,1).unproject(e).sub(e.position).normalize()}function z(e){return Math.max(n.minDistance,Math.min(n.maxDistance,e))}function _(e){f.set(e.clientX,e.clientY)}function Q(e){C.set(e.clientX,e.clientY)}function V(){if(1===T.length)f.set(T[0].pageX,T[0].pageY);else{const e=.5*(T[0].pageX+T[1].pageX),t=.5*(T[0].pageY+T[1].pageY);f.set(e,t)}}function N(){if(1===T.length)C.set(T[0].pageX,T[0].pageY);else{const e=.5*(T[0].pageX+T[1].pageX),t=.5*(T[0].pageY+T[1].pageY);C.set(e,t)}}function G(){const e=T[0].pageX-T[1].pageX,t=T[0].pageY-T[1].pageY,n=Math.sqrt(e*e+t*t);v.set(0,n)}function K(e){if(1==T.length)g.set(e.pageX,e.pageY);else{const t=te(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);g.set(n,s)}S.subVectors(g,f).multiplyScalar(n.rotateSpeed);const t=n.domElement;F(2*Math.PI*S.x/t.clientHeight),R(2*Math.PI*S.y/t.clientHeight),f.copy(g)}function q(e){if(1===T.length)y.set(e.pageX,e.pageY);else{const t=te(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);y.set(n,s)}x.subVectors(y,C).multiplyScalar(n.panSpeed),k(x.x,x.y),C.copy(y)}function W(e){const t=te(e),s=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(s*s+r*r);I.set(0,i),B.set(0,Math.pow(I.y/v.y,n.zoomSpeed)),L(B.y),v.copy(I)}function j(e){!1!==n.enabled&&(0===T.length&&(n.domElement.setPointerCapture(e.pointerId),n.domElement.addEventListener("pointermove",Y),n.domElement.addEventListener("pointerup",X)),function(e){T.push(e)}(e),"touch"===e.pointerType?function(e){switch(ee(e),T.length){case 1:switch(n.touches.ONE){case a.ROTATE:if(!1===n.enableRotate)return;V(),r=s.TOUCH_ROTATE;break;case a.PAN:if(!1===n.enablePan)return;N(),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(n.touches.TWO){case a.DOLLY_PAN:if(!1===n.enableZoom&&!1===n.enablePan)return;n.enableZoom&&G(),n.enablePan&&N(),r=s.TOUCH_DOLLY_PAN;break;case a.DOLLY_ROTATE:if(!1===n.enableZoom&&!1===n.enableRotate)return;n.enableZoom&&G(),n.enableRotate&&V(),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&n.dispatchEvent(_t)}(e):function(e){let t;switch(e.button){case 0:t=n.mouseButtons.LEFT;break;case 1:t=n.mouseButtons.MIDDLE;break;case 2:t=n.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o.DOLLY:if(!1===n.enableZoom)return;!function(e){U(e),v.set(e.clientX,e.clientY)}(e),r=s.DOLLY;break;case o.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===n.enablePan)return;Q(e),r=s.PAN}else{if(!1===n.enableRotate)return;_(e),r=s.ROTATE}break;case o.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===n.enableRotate)return;_(e),r=s.ROTATE}else{if(!1===n.enablePan)return;Q(e),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&n.dispatchEvent(_t)}(e))}function Y(e){!1!==n.enabled&&("touch"===e.pointerType?function(e){switch(ee(e),r){case s.TOUCH_ROTATE:if(!1===n.enableRotate)return;K(e),n.update();break;case s.TOUCH_PAN:if(!1===n.enablePan)return;q(e),n.update();break;case s.TOUCH_DOLLY_PAN:if(!1===n.enableZoom&&!1===n.enablePan)return;!function(e){n.enableZoom&&W(e),n.enablePan&&q(e)}(e),n.update();break;case s.TOUCH_DOLLY_ROTATE:if(!1===n.enableZoom&&!1===n.enableRotate)return;!function(e){n.enableZoom&&W(e),n.enableRotate&&K(e)}(e),n.update();break;default:r=s.NONE}}(e):function(e){switch(r){case s.ROTATE:if(!1===n.enableRotate)return;!function(e){g.set(e.clientX,e.clientY),S.subVectors(g,f).multiplyScalar(n.rotateSpeed);const t=n.domElement;F(2*Math.PI*S.x/t.clientHeight),R(2*Math.PI*S.y/t.clientHeight),f.copy(g),n.update()}(e);break;case s.DOLLY:if(!1===n.enableZoom)return;!function(e){I.set(e.clientX,e.clientY),B.subVectors(I,v),B.y>0?L(M()):B.y<0&&O(M()),v.copy(I),n.update()}(e);break;case s.PAN:if(!1===n.enablePan)return;!function(e){y.set(e.clientX,e.clientY),x.subVectors(y,C).multiplyScalar(n.panSpeed),k(x.x,x.y),C.copy(y),n.update()}(e)}}(e))}function X(e){!function(e){delete E[e.pointerId];for(let t=0;t<T.length;t++)if(T[t].pointerId==e.pointerId)return void T.splice(t,1)}(e),0===T.length&&(n.domElement.releasePointerCapture(e.pointerId),n.domElement.removeEventListener("pointermove",Y),n.domElement.removeEventListener("pointerup",X)),n.dispatchEvent(Qt),r=s.NONE}function J(e){!1!==n.enabled&&!1!==n.enableZoom&&r===s.NONE&&(e.preventDefault(),n.dispatchEvent(_t),function(e){U(e),e.deltaY<0?O(M()):e.deltaY>0&&L(M()),n.update()}(e),n.dispatchEvent(Qt))}function Z(e){!1!==n.enabled&&!1!==n.enablePan&&function(e){let t=!1;switch(e.code){case n.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?R(2*Math.PI*n.rotateSpeed/n.domElement.clientHeight):k(0,n.keyPanSpeed),t=!0;break;case n.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?R(-2*Math.PI*n.rotateSpeed/n.domElement.clientHeight):k(0,-n.keyPanSpeed),t=!0;break;case n.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?F(2*Math.PI*n.rotateSpeed/n.domElement.clientHeight):k(n.keyPanSpeed,0),t=!0;break;case n.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?F(-2*Math.PI*n.rotateSpeed/n.domElement.clientHeight):k(-n.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),n.update())}(e)}function $(e){!1!==n.enabled&&e.preventDefault()}function ee(e){let t=E[e.pointerId];void 0===t&&(t=new h,E[e.pointerId]=t),t.set(e.pageX,e.pageY)}function te(e){const t=e.pointerId===T[0].pointerId?T[1]:T[0];return E[t.pointerId]}n.domElement.addEventListener("contextmenu",$),n.domElement.addEventListener("pointerdown",j),n.domElement.addEventListener("pointercancel",X),n.domElement.addEventListener("wheel",J,{passive:!1}),this.update()}}class qt{static elementIDGen=0;constructor(e,t){this.taskIDGen=0,this.elementID=qt.elementIDGen++,this.tasks=[],this.message=e||"Loading...",this.container=t||document.body,this.spinnerContainerOuter=document.createElement("div"),this.spinnerContainerOuter.className=`spinnerOuterContainer${this.elementID}`,this.spinnerContainerOuter.style.display="none",this.spinnerContainerPrimary=document.createElement("div"),this.spinnerContainerPrimary.className=`spinnerContainerPrimary${this.elementID}`,this.spinnerPrimary=document.createElement("div"),this.spinnerPrimary.classList.add(`spinner${this.elementID}`,`spinnerPrimary${this.elementID}`),this.messageContainerPrimary=document.createElement("div"),this.messageContainerPrimary.classList.add(`messageContainer${this.elementID}`,`messageContainerPrimary${this.elementID}`),this.messageContainerPrimary.innerHTML=this.message,this.spinnerContainerMin=document.createElement("div"),this.spinnerContainerMin.className=`spinnerContainerMin${this.elementID}`,this.spinnerMin=document.createElement("div"),this.spinnerMin.classList.add(`spinner${this.elementID}`,`spinnerMin${this.elementID}`),this.messageContainerMin=document.createElement("div"),this.messageContainerMin.classList.add(`messageContainer${this.elementID}`,`messageContainerMin${this.elementID}`),this.messageContainerMin.innerHTML=this.message,this.spinnerContainerPrimary.appendChild(this.spinnerPrimary),this.spinnerContainerPrimary.appendChild(this.messageContainerPrimary),this.spinnerContainerOuter.appendChild(this.spinnerContainerPrimary),this.spinnerContainerMin.appendChild(this.spinnerMin),this.spinnerContainerMin.appendChild(this.messageContainerMin),this.spinnerContainerOuter.appendChild(this.spinnerContainerMin);const n=document.createElement("style");n.innerHTML=`\n\n .spinnerOuterContainer${this.elementID} {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .messageContainer${this.elementID} {\n height: 20px;\n font-family: arial;\n font-size: 12pt;\n color: #ffffff;\n text-align: center;\n vertical-align: middle;\n }\n\n .spinner${this.elementID} {\n padding: 15px;\n background: #07e8d6;\n z-index:99999;\n \n aspect-ratio: 1;\n border-radius: 50%;\n --_m: \n conic-gradient(#0000,#000),\n linear-gradient(#000 0 0) content-box;\n -webkit-mask: var(--_m);\n mask: var(--_m);\n -webkit-mask-composite: source-out;\n mask-composite: subtract;\n box-sizing: border-box;\n animation: load 1s linear infinite;\n }\n\n .spinnerContainerPrimary${this.elementID} {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 10px;\n margin: 0;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-80px, -80px);\n width: 180px;\n pointer-events: auto;\n }\n\n .spinnerPrimary${this.elementID} {\n width: 120px;\n margin-left: 30px;\n }\n\n .messageContainerPrimary${this.elementID} {\n padding-top: 15px;\n }\n\n .spinnerContainerMin${this.elementID} {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n display: flex;\n flex-direction: left;\n pointer-events: auto;\n min-width: 250px;\n }\n\n .messageContainerMin${this.elementID} {\n margin-right: 15px;\n }\n\n .spinnerMin${this.elementID} {\n width: 50px;\n height: 50px;\n margin-left: 15px;\n margin-right: 25px;\n }\n\n .messageContainerMin${this.elementID} {\n padding-top: 15px;\n }\n \n @keyframes load {\n to{transform: rotate(1turn)}\n }\n\n `,this.spinnerContainerOuter.appendChild(n),this.container.appendChild(this.spinnerContainerOuter),this.setMinimized(!1,!0),this.fadeTransitions=[]}addTask(e){const t={message:e,id:this.taskIDGen++};return this.tasks.push(t),this.update(),t.id}removeTask(e){let t=0;for(let n of this.tasks){if(n.id===e){this.tasks.splice(t,1);break}t++}this.update()}removeAllTasks(){this.tasks=[],this.update()}setMessageForTask(e,t){for(let n of this.tasks)if(n.id===e){n.message=t;break}this.update()}update(){this.tasks.length>0?(this.show(),this.setMessage(this.tasks[this.tasks.length-1].message)):this.hide()}show(){this.spinnerContainerOuter.style.display="block",this.visible=!0}hide(){this.spinnerContainerOuter.style.display="none",this.visible=!1}setContainer(e){this.container&&this.spinnerContainerOuter.parentElement===this.container&&this.container.removeChild(this.spinnerContainerOuter),e&&(this.container=e,this.container.appendChild(this.spinnerContainerOuter),this.spinnerContainerOuter.style.zIndex=this.container.style.zIndex+1)}setMinimized(e,t){const n=(e,t,n,s,r)=>{n?e.style.display=t?s:"none":this.fadeTransitions[r]=((e,t,n,s,r)=>{const i=performance.now();let o="none"===e.style.display?0:parseFloat(e.style.opacity);isNaN(o)&&(o=1);const a=window.setInterval((()=>{const l=performance.now()-i;let c,h=Math.min(l/s,1);h>.999&&(h=1),t?(c=(1-h)*o,c<1e-4&&(c=0)):c=(1-o)*h+o,c>0?(e.style.display=n,e.style.opacity=c):e.style.display="none",h>=1&&(r&&r(),window.clearInterval(a))}),16);return a})(e,!t,s,500,(()=>{this.fadeTransitions[r]=null}))};n(this.spinnerContainerPrimary,!e,t,"block",0),n(this.spinnerContainerMin,e,t,"flex",1),this.minimized=e}setMessage(e){this.messageContainerPrimary.innerHTML=e,this.messageContainerMin.innerHTML=e}}class Wt{constructor(e){this.idGen=0,this.tasks=[],this.container=e||document.body,this.progressBarContainerOuter=document.createElement("div"),this.progressBarContainerOuter.className="progressBarOuterContainer",this.progressBarContainerOuter.style.display="none",this.progressBarBox=document.createElement("div"),this.progressBarBox.className="progressBarBox",this.progressBarBackground=document.createElement("div"),this.progressBarBackground.className="progressBarBackground",this.progressBar=document.createElement("div"),this.progressBar.className="progressBar",this.progressBarBackground.appendChild(this.progressBar),this.progressBarBox.appendChild(this.progressBarBackground),this.progressBarContainerOuter.appendChild(this.progressBarBox);const t=document.createElement("style");t.innerHTML="\n\n .progressBarOuterContainer {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .progressBarBox {\n z-index:99999;\n padding: 7px 9px 5px 7px;\n background-color: rgba(190, 190, 190, 0.75);\n border: #555555 1px solid;\n border-radius: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n width: 180px;\n height: 30px;\n pointer-events: auto;\n }\n\n .progressBarBackground {\n width: 100%;\n height: 25px;\n border-radius:10px;\n background-color: rgba(128, 128, 128, 0.75);\n border: #444444 1px solid;\n box-shadow: inset 0 0 10px #333333;\n }\n\n .progressBar {\n height: 25px;\n width: 0px;\n border-radius:10px;\n background-color: rgba(0, 200, 0, 0.75);\n box-shadow: inset 0 0 10px #003300;\n }\n\n ",this.progressBarContainerOuter.appendChild(t),this.container.appendChild(this.progressBarContainerOuter)}show(){this.progressBarContainerOuter.style.display="block"}hide(){this.progressBarContainerOuter.style.display="none"}setProgress(e){this.progressBar.style.width=e+"%"}setContainer(e){this.container&&this.progressBarContainerOuter.parentElement===this.container&&this.container.removeChild(this.progressBarContainerOuter),e&&(this.container=e,this.container.appendChild(this.progressBarContainerOuter),this.progressBarContainerOuter.style.zIndex=this.container.style.zIndex+1)}}class jt{constructor(e){this.container=e||document.body,this.infoCells={};const t=[["Camera position","cameraPosition"],["Camera look-at","cameraLookAt"],["Camera up","cameraUp"],["Camera mode","orthographicCamera"],["Cursor position","cursorPosition"],["FPS","fps"],["Rendering:","renderSplatCount"],["Sort time","sortTime"],["Render window","renderWindow"],["Focal adjustment","focalAdjustment"],["Splat scale","splatScale"],["Point cloud mode","pointCloudMode"]];this.infoPanelContainer=document.createElement("div");const n=document.createElement("style");n.innerHTML="\n\n .infoPanel {\n width: 430px;\n padding: 10px;\n background-color: rgba(50, 50, 50, 0.85);\n border: #555555 2px solid;\n color: #dddddd;\n border-radius: 10px;\n z-index: 9999;\n font-family: arial;\n font-size: 11pt;\n text-align: left;\n margin: 0;\n top: 10px;\n left:10px;\n position: absolute;\n pointer-events: auto;\n }\n\n .info-panel-cell {\n margin-bottom: 5px;\n padding-bottom: 2px;\n }\n\n .label-cell {\n font-weight: bold;\n font-size: 12pt;\n width: 140px;\n }\n\n ",this.infoPanelContainer.append(n),this.infoPanel=document.createElement("div"),this.infoPanel.className="infoPanel";const s=document.createElement("div");s.style.display="table";for(let e of t){const t=document.createElement("div");t.style.display="table-row",t.className="info-panel-row";const n=document.createElement("div");n.style.display="table-cell",n.innerHTML=`${e[0]}: `,n.classList.add("info-panel-cell","label-cell");const r=document.createElement("div");r.style.display="table-cell",r.style.width="10px",r.innerHTML=" ",r.className="info-panel-cell";const i=document.createElement("div");i.style.display="table-cell",i.innerHTML="",i.className="info-panel-cell",this.infoCells[e[1]]=i,t.appendChild(n),t.appendChild(r),t.appendChild(i),s.appendChild(t)}this.infoPanel.appendChild(s),this.infoPanelContainer.append(this.infoPanel),this.infoPanelContainer.style.display="none",this.container.appendChild(this.infoPanelContainer),this.visible=!1}update=function(e,t,n,s,r,i,o,a,l,c,h,d,p,u){const m=`${t.x.toFixed(5)}, ${t.y.toFixed(5)}, ${t.z.toFixed(5)}`;if(this.infoCells.cameraPosition.innerHTML!==m&&(this.infoCells.cameraPosition.innerHTML=m),n){const e=n,t=`${e.x.toFixed(5)}, ${e.y.toFixed(5)}, ${e.z.toFixed(5)}`;this.infoCells.cameraLookAt.innerHTML!==t&&(this.infoCells.cameraLookAt.innerHTML=t)}const A=`${s.x.toFixed(5)}, ${s.y.toFixed(5)}, ${s.z.toFixed(5)}`;if(this.infoCells.cameraUp.innerHTML!==A&&(this.infoCells.cameraUp.innerHTML=A),this.infoCells.orthographicCamera.innerHTML=r?"Orthographic":"Perspective",i){const e=i,t=`${e.x.toFixed(5)}, ${e.y.toFixed(5)}, ${e.z.toFixed(5)}`;this.infoCells.cursorPosition.innerHTML=t}else this.infoCells.cursorPosition.innerHTML="N/A";this.infoCells.fps.innerHTML=o,this.infoCells.renderWindow.innerHTML=`${e.x} x ${e.y}`,this.infoCells.renderSplatCount.innerHTML=`${l} splats out of ${a} (${c.toFixed(2)}%)`,this.infoCells.sortTime.innerHTML=`${h.toFixed(3)} ms`,this.infoCells.focalAdjustment.innerHTML=`${d.toFixed(3)}`,this.infoCells.splatScale.innerHTML=`${p.toFixed(3)}`,this.infoCells.pointCloudMode.innerHTML=`${u}`};setContainer(e){this.container&&this.infoPanelContainer.parentElement===this.container&&this.container.removeChild(this.infoPanelContainer),e&&(this.container=e,this.container.appendChild(this.infoPanelContainer),this.infoPanelContainer.style.zIndex=this.container.style.zIndex+1)}show(){this.infoPanelContainer.style.display="block",this.visible=!0}hide(){this.infoPanelContainer.style.display="none",this.visible=!1}}const Yt=new e.Vector3;class Xt extends e.Object3D{constructor(t=new e.Vector3(0,0,1),n=new e.Vector3(0,0,0),s=1,r=.1,i=16776960,o=.2*s,a=.2*o){super(),this.type="ArrowHelper";const l=new e.CylinderGeometry(r,r,s,32);l.translate(0,s/2,0);const c=new e.CylinderGeometry(0,a,o,32);c.translate(0,s,0),this.position.copy(n),this.line=new e.Mesh(l,new e.MeshBasicMaterial({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new e.Mesh(c,new e.MeshBasicMaterial({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(t)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Yt.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Yt,t)}}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class Jt{constructor(e){this.threeScene=e,this.splatRenderTarget=null,this.renderTargetCopyQuad=null,this.renderTargetCopyCamera=null,this.meshCursor=null,this.focusMarker=null,this.controlPlane=null,this.debugRoot=null,this.secondaryDebugRoot=null}updateSplatRenderTargetForRenderDimensions(t,n){this.destroySplatRendertarget(),this.splatRenderTarget=new e.WebGLRenderTarget(t,n,{format:e.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}),this.splatRenderTarget.depthTexture=new e.DepthTexture(t,n),this.splatRenderTarget.depthTexture.format=e.DepthFormat,this.splatRenderTarget.depthTexture.type=e.UnsignedIntType}destroySplatRendertarget(){this.splatRenderTarget&&(this.splatRenderTarget=null)}setupRenderTargetCopyObjects(){const t=new e.ShaderMaterial({vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = vec4( position.xy, 0.0, 1.0 ); \n }\n ",fragmentShader:"\n #include <common>\n #include <packing>\n varying vec2 vUv;\n uniform sampler2D sourceColorTexture;\n uniform sampler2D sourceDepthTexture;\n void main() {\n vec4 color = texture2D(sourceColorTexture, vUv);\n float fragDepth = texture2D(sourceDepthTexture, vUv).x;\n gl_FragDepth = fragDepth;\n gl_FragColor = vec4(color.rgb, color.a * 2.0);\n }\n ",uniforms:{sourceColorTexture:{type:"t",value:null},sourceDepthTexture:{type:"t",value:null}},depthWrite:!1,depthTest:!1,transparent:!0,blending:e.CustomBlending,blendSrc:e.SrcAlphaFactor,blendSrcAlpha:e.SrcAlphaFactor,blendDst:e.OneMinusSrcAlphaFactor,blendDstAlpha:e.OneMinusSrcAlphaFactor});t.extensions.fragDepth=!0,this.renderTargetCopyQuad=new e.Mesh(new e.PlaneGeometry(2,2),t),this.renderTargetCopyCamera=new e.OrthographicCamera(-1,1,1,-1,0,1)}destroyRenderTargetCopyObjects(){this.renderTargetCopyQuad&&(g(this.renderTargetCopyQuad),this.renderTargetCopyQuad=null)}setupMeshCursor(){if(!this.meshCursor){const t=new e.ConeGeometry(.5,1.5,32),n=new e.MeshBasicMaterial({color:16777215}),s=new e.Mesh(t,n);s.rotation.set(0,0,Math.PI),s.position.set(0,1,0);const r=new e.Mesh(t,n);r.position.set(0,-1,0);const i=new e.Mesh(t,n);i.rotation.set(0,0,Math.PI/2),i.position.set(1,0,0);const o=new e.Mesh(t,n);o.rotation.set(0,0,-Math.PI/2),o.position.set(-1,0,0),this.meshCursor=new e.Object3D,this.meshCursor.add(s),this.meshCursor.add(r),this.meshCursor.add(i),this.meshCursor.add(o),this.meshCursor.scale.set(.1,.1,.1),this.threeScene.add(this.meshCursor),this.meshCursor.visible=!1}}destroyMeshCursor(){this.meshCursor&&(g(this.meshCursor),this.threeScene.remove(this.meshCursor),this.meshCursor=null)}setMeshCursorVisibility(e){this.meshCursor.visible=e}getMeschCursorVisibility(){return this.meshCursor.visible}setMeshCursorPosition(e){this.meshCursor.position.copy(e)}positionAndOrientMeshCursor(e,t){this.meshCursor.position.copy(e),this.meshCursor.up.copy(t.up),this.meshCursor.lookAt(t.position)}setupFocusMarker(){if(!this.focusMarker){const t=new e.SphereGeometry(.5,32,32),n=Jt.buildFocusMarkerMaterial();n.depthTest=!1,n.depthWrite=!1,n.transparent=!0,this.focusMarker=new e.Mesh(t,n)}}destroyFocusMarker(){this.focusMarker&&(g(this.focusMarker),this.focusMarker=null)}updateFocusMarker=function(){const t=new e.Vector3,n=new e.Matrix4,s=new e.Vector3;return function(e,r,i){n.copy(r.matrixWorld).invert(),t.copy(e).applyMatrix4(n),t.normalize().multiplyScalar(10),t.applyMatrix4(r.matrixWorld),s.copy(r.position).sub(e);const o=s.length();this.focusMarker.position.copy(e),this.focusMarker.scale.set(o,o,o),this.focusMarker.material.uniforms.realFocusPosition.value.copy(e),this.focusMarker.material.uniforms.viewport.value.copy(i),this.focusMarker.material.uniformsNeedUpdate=!0}}();setFocusMarkerVisibility(e){this.focusMarker.visible=e}setFocusMarkerOpacity(e){this.focusMarker.material.uniforms.opacity.value=e,this.focusMarker.material.uniformsNeedUpdate=!0}getFocusMarkerOpacity(){return this.focusMarker.material.uniforms.opacity.value}setupControlPlane(){if(!this.controlPlane){const t=new e.PlaneGeometry(1,1);t.rotateX(-Math.PI/2);const n=new e.MeshBasicMaterial({color:16777215});n.transparent=!0,n.opacity=.6,n.depthTest=!1,n.depthWrite=!1,n.side=e.DoubleSide;const s=new e.Mesh(t,n),r=new e.Vector3(0,1,0);r.normalize();const i=new e.Vector3(0,0,0),o=new Xt(r,i,.5,.01,56576,.1,.03);this.controlPlane=new e.Object3D,this.controlPlane.add(s),this.controlPlane.add(o)}}destroyControlPlane(){this.controlPlane&&(g(this.controlPlane),this.controlPlane=null)}setControlPlaneVisibility(e){this.controlPlane.visible=e}positionAndOrientControlPlane=function(){const t=new e.Quaternion,n=new e.Vector3(0,1,0);return function(e,s){t.setFromUnitVectors(n,s),this.controlPlane.position.copy(e),this.controlPlane.quaternion.copy(t)}}();addDebugMeshes(){this.debugRoot=this.createDebugMeshes(),this.secondaryDebugRoot=this.createSecondaryDebugMeshes(),this.threeScene.add(this.debugRoot),this.threeScene.add(this.secondaryDebugRoot)}destroyDebugMeshes(){for(let e of[this.debugRoot,this.secondaryDebugRoot])e&&(g(e),this.threeScene.remove(e));this.debugRoot=null,this.secondaryDebugRoot=null}createDebugMeshes(t){const n=new e.SphereGeometry(1,32,32),s=new e.Object3D,r=(r,i)=>{let o=new e.Mesh(n,Jt.buildDebugMaterial(r));o.renderOrder=t,s.add(o),o.position.fromArray(i)};return r(16711680,[-50,0,0]),r(16711680,[50,0,0]),r(65280,[0,0,-50]),r(65280,[0,0,50]),r(16755200,[5,0,5]),s}createSecondaryDebugMeshes(t){const n=new e.BoxGeometry(3,3,3),s=new e.Object3D;const r=r=>{let i=new e.Mesh(n,Jt.buildDebugMaterial(12303291));i.renderOrder=t,s.add(i),i.position.fromArray(r)};let i=10;return r([-10,0,-10]),r([-10,0,i]),r([i,0,-10]),r([i,0,i]),s}static buildDebugMaterial(t){const n={color:{type:"v3",value:new e.Color(t)}},s=new e.ShaderMaterial({uniforms:n,vertexShader:"\n #include <common>\n varying float ndcDepth;\n\n void main() {\n gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position.xyz, 1.0);\n ndcDepth = gl_Position.z / gl_Position.w;\n gl_Position.x = gl_Position.x / gl_Position.w;\n gl_Position.y = gl_Position.y / gl_Position.w;\n gl_Position.z = 0.0;\n gl_Position.w = 1.0;\n \n }\n ",fragmentShader:"\n #include <common>\n uniform vec3 color;\n varying float ndcDepth;\n void main() {\n gl_FragDepth = (ndcDepth + 1.0) / 2.0;\n gl_FragColor = vec4(color.rgb, 0.0);\n }\n ",transparent:!1,depthTest:!0,depthWrite:!0,side:e.FrontSide});return s.extensions.fragDepth=!0,s}static buildFocusMarkerMaterial(t){const n={color:{type:"v3",value:new e.Color(t)},realFocusPosition:{type:"v3",value:new e.Vector3},viewport:{type:"v2",value:new e.Vector2},opacity:{value:0}};return new e.ShaderMaterial({uniforms:n,vertexShader:"\n #include <common>\n\n uniform vec2 viewport;\n uniform vec3 realFocusPosition;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n float radius = 0.01;\n\n vec4 viewPosition = modelViewMatrix * vec4(position.xyz, 1.0);\n vec4 viewCenter = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);\n\n vec4 viewFocusPosition = modelViewMatrix * vec4(realFocusPosition, 1.0);\n\n ndcPosition = projectionMatrix * viewPosition;\n ndcPosition = ndcPosition * vec4(1.0 / ndcPosition.w);\n ndcCenter = projectionMatrix * viewCenter;\n ndcCenter = ndcCenter * vec4(1.0 / ndcCenter.w);\n\n ndcFocusPosition = projectionMatrix * viewFocusPosition;\n ndcFocusPosition = ndcFocusPosition * vec4(1.0 / ndcFocusPosition.w);\n\n gl_Position = projectionMatrix * viewPosition;\n\n }\n ",fragmentShader:"\n #include <common>\n uniform vec3 color;\n uniform vec2 viewport;\n uniform float opacity;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n vec2 screenPosition = vec2(ndcPosition) * viewport;\n vec2 screenCenter = vec2(ndcCenter) * viewport;\n\n vec2 screenVec = screenPosition - screenCenter;\n\n float projectedRadius = length(screenVec);\n\n float lineWidth = 0.0005 * viewport.y;\n float aaRange = 0.0025 * viewport.y;\n float radius = 0.06 * viewport.y;\n float radDiff = abs(projectedRadius - radius) - lineWidth;\n float alpha = 1.0 - clamp(radDiff / 5.0, 0.0, 1.0); \n\n gl_FragColor = vec4(color.rgb, alpha * opacity);\n }\n ",transparent:!0,depthTest:!1,depthWrite:!1,side:e.FrontSide})}dispose(){this.destroyMeshCursor(),this.destroyFocusMarker(),this.destroyDebugMeshes(),this.destroyControlPlane(),this.destroyRenderTargetCopyObjects(),this.destroySplatRendertarget()}}const Zt=new e.Vector3(1,0,0),$t=new e.Vector3(0,1,0),en=new e.Vector3(0,0,1);class tn{constructor(t=new e.Vector3,n=new e.Vector3){this.origin=new e.Vector3,this.direction=new e.Vector3,this.setParameters(t,n)}setParameters(e,t){this.origin.copy(e),this.direction.copy(t).normalize()}boxContainsPoint(e,t,n){return!(t.x<e.min.x-n||t.x>e.max.x+n||t.y<e.min.y-n||t.y>e.max.y+n||t.z<e.min.z-n||t.z>e.max.z+n)}intersectBox=function(){const t=new e.Vector3,n=[],s=[],r=[];return function(e,i){if(s[0]=this.origin.x,s[1]=this.origin.y,s[2]=this.origin.z,r[0]=this.direction.x,r[1]=this.direction.y,r[2]=this.direction.z,this.boxContainsPoint(e,this.origin,1e-4))return i&&(i.origin.copy(this.origin),i.normal.set(0,0,0),i.distance=-1),!0;for(let o=0;o<3;o++){if(0==r[o])continue;const a=0==o?Zt:1==o?$t:en,l=r[o]<0?e.max:e.min;let c=-Math.sign(r[o]);n[0]=0==o?l.x:1==o?l.y:l.z;let h=n[0]-s[o];if(h*c<0){const l=(o+1)%3,d=(o+2)%3;if(n[2]=r[l]/r[o]*h+s[l],n[1]=r[d]/r[o]*h+s[d],t.set(n[o],n[d],n[l]),this.boxContainsPoint(e,t,1e-4))return i&&(i.origin.copy(t),i.normal.copy(a).multiplyScalar(c),i.distance=t.sub(this.origin).length()),!0}}return!1}}();intersectSphere=function(){const t=new e.Vector3;return function(e,n,s){t.copy(e).sub(this.origin);const r=t.dot(this.direction),i=r*r,o=t.dot(t)-i,a=n*n;if(o>a)return!1;const l=Math.sqrt(a-o),c=r-l,h=r+l;if(h<0)return!1;let d=c<0?h:c;return s&&(s.origin.copy(this.origin).addScaledVector(this.direction,d),s.normal.copy(s.origin).sub(e).normalize(),s.distance=d),!0}}()}class nn{constructor(){this.origin=new e.Vector3,this.normal=new e.Vector3,this.distance=0,this.splatIndex=0}set(e,t,n,s){this.origin.copy(e),this.normal.copy(t),this.distance=n,this.splatIndex=s}clone(){const e=new nn;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}const sn=0,rn=1;class on{constructor(e,t,n=!1){this.ray=new tn(e,t),this.raycastAgainstTrueSplatEllipsoid=n}setFromCameraAndScreenPosition=function(){const t=new e.Vector2;return function(e,n,s){if(t.x=n.x/s.x*2-1,t.y=(s.y-n.y)/s.y*2-1,e.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e;else{if(!e.isOrthographicCamera)throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type");this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e}}}();intersectSplatMesh=function(){const t=new e.Matrix4,n=new e.Matrix4,s=new e.Matrix4,r=new tn,i=new e.Vector3;return function(e,o=[]){const a=e.getSplatTree();if(a){for(let l=0;l<a.subTrees.length;l++){const c=a.subTrees[l];n.copy(e.matrixWorld),e.dynamicMode&&(e.getSceneTransform(l,s),n.multiply(s)),t.copy(n).invert(),r.origin.copy(this.ray.origin).applyMatrix4(t),r.direction.copy(this.ray.origin).add(this.ray.direction),r.direction.applyMatrix4(t).sub(r.origin).normalize();const h=[];c.rootNode&&this.castRayAtSplatTreeNode(r,a,c.rootNode,h),h.forEach((e=>{e.origin.applyMatrix4(n),e.normal.applyMatrix4(n).normalize(),e.distance=i.copy(e.origin).sub(this.ray.origin).length()})),o.push(...h)}return o.sort(((e,t)=>e.distance>t.distance?1:-1)),o}}}();castRayAtSplatTreeNode=function(){const t=new e.Vector4,n=new e.Vector3,s=new e.Vector3,r=new e.Quaternion,i=new nn,o=1e-7,a=new e.Vector3(0,0,0),l=new e.Matrix4,c=new e.Matrix4,h=new e.Matrix4,d=new e.Matrix4,p=new e.Matrix4,u=new tn;return function(e,m,A,f=[]){if(e.intersectBox(A.boundingBox)){if(A.data&&A.data.indexes&&A.data.indexes.length>0)for(let g=0;g<A.data.indexes.length;g++){const S=A.data.indexes[g],C=m.splatMesh.getSceneIndexForSplat(S);if(m.splatMesh.getScene(C).visible&&(m.splatMesh.getSplatColor(S,t),m.splatMesh.getSplatCenter(S,n),m.splatMesh.getSplatScaleAndRotation(S,s,r),!(s.x<=o||s.y<=o||m.splatMesh.splatRenderMode===sn&&s.z<=o)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(s.x,s.y,s.z),h.makeRotationFromQuaternion(r);const o=2*Math.log10(t.w);if(l.makeScale(o,o,o),p.copy(l).multiply(h).multiply(c),d.copy(p).invert(),u.origin.copy(e.origin).sub(n).applyMatrix4(d),u.direction.copy(e.origin).add(e.direction).sub(n),u.direction.applyMatrix4(d).sub(u.origin).normalize(),u.intersectSphere(a,1,i)){const e=i.clone();e.splatIndex=S,e.origin.applyMatrix4(p).add(n),f.push(e)}}else{let t=s.x+s.y,r=2;if(m.splatMesh.splatRenderMode===sn&&(t+=s.z,r=3),t/=r,e.intersectSphere(n,t,i)){const e=i.clone();e.splatIndex=S,f.push(e)}}}if(A.children&&A.children.length>0)for(let t of A.children)this.castRayAtSplatTreeNode(e,m,t,f);return f}}}()}class an{static buildVertexShaderBase(e=!1,t=!1,n=0,s=""){let r="\n precision highp float;\n #include <common>\n\n attribute uint splatIndex;\n uniform highp usampler2D centersColorsTexture;\n uniform highp sampler2D sphericalHarmonicsTexture;\n uniform highp sampler2D sphericalHarmonicsTextureR;\n uniform highp sampler2D sphericalHarmonicsTextureG;\n uniform highp sampler2D sphericalHarmonicsTextureB;\n\n uniform highp usampler2D sceneIndexesTexture;\n uniform vec2 sceneIndexesTextureSize;\n uniform int sceneCount;\n ";return t&&(r+=`\n uniform float sceneOpacity[${b.MaxScenes}];\n uniform int sceneVisibility[${b.MaxScenes}];\n `),e&&(r+=`\n uniform highp mat4 transforms[${b.MaxScenes}];\n `),r+=`\n ${s}\n uniform vec2 focal;\n uniform float orthoZoom;\n uniform int orthographicMode;\n uniform int pointCloudModeEnabled;\n uniform float inverseFocalAdjustment;\n uniform vec2 viewport;\n uniform vec2 basisViewport;\n uniform vec2 centersColorsTextureSize;\n uniform int sphericalHarmonicsDegree;\n uniform vec2 sphericalHarmonicsTextureSize;\n uniform int sphericalHarmonics8BitMode;\n uniform int sphericalHarmonicsMultiTextureMode;\n uniform float visibleRegionRadius;\n uniform float visibleRegionFadeStartRadius;\n uniform float firstRenderTime;\n uniform float currentTime;\n uniform int fadeInComplete;\n uniform vec3 sceneCenter;\n uniform float splatScale;\n uniform float sphericalHarmonics8BitCompressionRangeMin[${b.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${b.MaxScenes}];\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n\n mat3 quaternionToRotationMatrix(float x, float y, float z, float w) {\n float s = 1.0 / sqrt(w * w + x * x + y * y + z * z);\n \n return mat3(\n 1. - 2. * (y * y + z * z),\n 2. * (x * y + w * z),\n 2. * (x * z - w * y),\n 2. * (x * y - w * z),\n 1. - 2. * (x * x + z * z),\n 2. * (y * z + w * x),\n 2. * (x * z + w * y),\n 2. * (y * z - w * x),\n 1. - 2. * (x * x + y * y)\n );\n }\n\n const float sqrt8 = sqrt(8.0);\n const float minAlpha = 1.0 / 255.0;\n\n const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));\n const uvec4 shift4 = uvec4(0, 8, 16, 24);\n vec4 uintToRGBAVec (uint u) {\n uvec4 urgba = mask4 & u;\n urgba = urgba >> shift4;\n vec4 rgba = vec4(urgba) * encodeNorm4;\n return rgba;\n }\n\n vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(float(sIndex) * stride) + offset) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n const float SH_C1 = 0.4886025119029199f;\n const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);\n\n void main () {\n\n uint oddOffset = splatIndex & uint(0x00000001);\n uint doubleOddOffset = oddOffset * uint(2);\n bool isEven = oddOffset == uint(0);\n uint nearestEvenIndex = splatIndex - oddOffset;\n float fOddOffset = float(oddOffset);\n\n uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));\n vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));\n\n uint sceneIndex = uint(0);\n if (sceneCount > 1) {\n sceneIndex = texture(sceneIndexesTexture, getDataUV(1, 0, sceneIndexesTextureSize)).r;\n }\n `,t&&(r+="\n float splatOpacityFromScene = sceneOpacity[sceneIndex];\n int sceneVisible = sceneVisibility[sceneIndex];\n if (splatOpacityFromScene <= 0.01 || sceneVisible == 0) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n "),r+=e?"\n mat4 transform = transforms[sceneIndex];\n mat4 transformModelViewMatrix = viewMatrix * transform;\n ":"mat4 transformModelViewMatrix = modelViewMatrix;",r+="\n float sh8BitCompressionRangeMinForScene = sphericalHarmonics8BitCompressionRangeMin[sceneIndex];\n float sh8BitCompressionRangeMaxForScene = sphericalHarmonics8BitCompressionRangeMax[sceneIndex];\n float sh8BitCompressionRangeForScene = sh8BitCompressionRangeMaxForScene - sh8BitCompressionRangeMinForScene;\n float sh8BitCompressionHalfRangeForScene = sh8BitCompressionRangeForScene / 2.0;\n vec3 vec8BitSHShift = vec3(sh8BitCompressionRangeMinForScene);\n\n vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);\n\n vec4 clipCenter = projectionMatrix * viewCenter;\n\n float clip = 1.2 * clipCenter.w;\n if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n\n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n vPosition = position.xy;\n vColor = uintToRGBAVec(sampledCenterColor.r);\n ",n>=1&&(r+=" \n if (sphericalHarmonicsDegree >= 1) {\n ",r+=e?"\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));\n ":"\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n ",r+="\n vec3 sh1;\n vec3 sh2;\n vec3 sh3;\n ",n>=2&&(r+="\n vec3 sh4;\n vec3 sh5;\n vec3 sh6;\n vec3 sh7;\n vec3 sh8;\n "),1===n?r+="\n if (sphericalHarmonicsMultiTextureMode == 0) {\n vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);\n sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;\n sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;\n sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;\n } else {\n vec2 sampledSH01R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH01G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH01B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize)).rg;\n vec2 sampledSH23B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize)).rg;\n sh1 = vec3(sampledSH01R.rg, sampledSH23R.r);\n sh2 = vec3(sampledSH01G.rg, sampledSH23G.r);\n sh3 = vec3(sampledSH01B.rg, sampledSH23B.r);\n }\n ":2===n&&(r+="\n vec4 sampledSH0123;\n vec4 sampledSH4567;\n vec4 sampledSH891011;\n\n vec4 sampledSH0123R;\n vec4 sampledSH0123G;\n vec4 sampledSH0123B;\n\n if (sphericalHarmonicsMultiTextureMode == 0) {\n sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));\n sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));\n sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));\n sh1 = sampledSH0123.rgb;\n sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);\n sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);\n } else {\n sampledSH0123R = texture(sphericalHarmonicsTextureR, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sampledSH0123G = texture(sphericalHarmonicsTextureG, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sampledSH0123B = texture(sphericalHarmonicsTextureB, getDataUV(2, 0, sphericalHarmonicsTextureSize));\n sh1 = vec3(sampledSH0123R.rgb);\n sh2 = vec3(sampledSH0123G.rgb);\n sh3 = vec3(sampledSH0123B.rgb);\n }\n "),r+="\n if (sphericalHarmonics8BitMode == 1) {\n sh1 = sh1 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh2 = sh2 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh3 = sh3 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n }\n float x = worldViewDir.x;\n float y = worldViewDir.y;\n float z = worldViewDir.z;\n vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);\n ",n>=2&&(r+="\n if (sphericalHarmonicsDegree >= 2) {\n float xx = x * x;\n float yy = y * y;\n float zz = z * z;\n float xy = x * y;\n float yz = y * z;\n float xz = x * z;\n ",2===n&&(r+="\n if (sphericalHarmonicsMultiTextureMode == 0) {\n vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));\n vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));\n vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));\n sh4 = sampledSH891011.gba;\n sh5 = sampledSH12131415.rgb;\n sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);\n sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);\n sh8 = sampledSH20212223.gba;\n } else {\n vec4 sampledSH4567R = texture(sphericalHarmonicsTextureR, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567G = texture(sphericalHarmonicsTextureG, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567B = texture(sphericalHarmonicsTextureB, getDataUV(2, 1, sphericalHarmonicsTextureSize));\n sh4 = vec3(sampledSH0123R.a, sampledSH4567R.rg);\n sh5 = vec3(sampledSH4567R.ba, sampledSH0123G.a);\n sh6 = vec3(sampledSH4567G.rgb);\n sh7 = vec3(sampledSH4567G.a, sampledSH0123B.a, sampledSH4567B.r);\n sh8 = vec3(sampledSH4567B.gba);\n }\n "),r+="\n if (sphericalHarmonics8BitMode == 1) {\n sh4 = sh4 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh5 = sh5 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh6 = sh6 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh7 = sh7 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n sh8 = sh8 * sh8BitCompressionRangeForScene + vec8BitSHShift;\n }\n\n vColor.rgb +=\n (SH_C2[0] * xy) * sh4 +\n (SH_C2[1] * yz) * sh5 +\n (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +\n (SH_C2[3] * xz) * sh7 +\n (SH_C2[4] * (xx - yy)) * sh8;\n }\n "),r+="\n\n vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));\n\n }\n\n "),r}static getVertexShaderFadeIn(){return"\n if (fadeInComplete == 0) {\n float opacityAdjust = 1.0;\n float centerDist = length(splatCenter - sceneCenter);\n float renderTime = max(currentTime - firstRenderTime, 0.0);\n\n float fadeDistance = 0.75;\n float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);\n distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +\n (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *\n distanceLoadFadeInFactor;\n opacityAdjust *= distanceLoadFadeInFactor;\n vColor.a *= opacityAdjust;\n }\n "}static getUniforms(t=!1,n=!1,s=0,r=1,i=!1){const o={sceneCenter:{type:"v3",value:new e.Vector3},fadeInComplete:{type:"i",value:0},orthographicMode:{type:"i",value:0},visibleRegionFadeStartRadius:{type:"f",value:0},visibleRegionRadius:{type:"f",value:0},currentTime:{type:"f",value:0},firstRenderTime:{type:"f",value:0},centersColorsTexture:{type:"t",value:null},sphericalHarmonicsTexture:{type:"t",value:null},sphericalHarmonicsTextureR:{type:"t",value:null},sphericalHarmonicsTextureG:{type:"t",value:null},sphericalHarmonicsTextureB:{type:"t",value:null},sphericalHarmonics8BitCompressionRangeMin:{type:"f",value:[]},sphericalHarmonics8BitCompressionRangeMax:{type:"f",value:[]},focal:{type:"v2",value:new e.Vector2},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new e.Vector2},basisViewport:{type:"v2",value:new e.Vector2},debugColor:{type:"v3",value:new e.Color},centersColorsTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sphericalHarmonicsDegree:{type:"i",value:s},sphericalHarmonicsTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:r},pointCloudModeEnabled:{type:"i",value:i?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new e.Vector2(1024,1024)},sceneCount:{type:"i",value:1}};for(let e=0;e<b.MaxScenes;e++)o.sphericalHarmonics8BitCompressionRangeMin.value.push(-b.SphericalHarmonics8BitCompressionRange/2),o.sphericalHarmonics8BitCompressionRangeMax.value.push(b.SphericalHarmonics8BitCompressionRange/2);if(n){const e=[];for(let t=0;t<b.MaxScenes;t++)e.push(1);o.sceneOpacity={type:"f",value:e};const t=[];for(let e=0;e<b.MaxScenes;e++)t.push(1);o.sceneVisibility={type:"i",value:t}}if(t){const t=[];for(let n=0;n<b.MaxScenes;n++)t.push(new e.Matrix4);o.transforms={type:"mat4",value:t}}return o}}class ln{static build(t=!1,n=!1,s=!1,r=2048,i=1,o=!1,a=0,l=.3){let c=an.buildVertexShaderBase(t,n,a,"\n uniform vec2 covariancesTextureSize;\n uniform highp sampler2D covariancesTexture;\n uniform highp usampler2D covariancesTextureHalfFloat;\n uniform int covariancesAreHalfFloat;\n\n void fromCovarianceHalfFloatV4(uvec4 val, out vec4 first, out vec4 second) {\n vec2 r = unpackHalf2x16(val.r);\n vec2 g = unpackHalf2x16(val.g);\n vec2 b = unpackHalf2x16(val.b);\n\n first = vec4(r.x, r.y, g.x, g.y);\n second = vec4(b.x, b.y, 0.0, 0.0);\n }\n ");c+=ln.buildVertexShaderProjection(s,n,r,l);const h=ln.buildFragmentShader(),d=an.getUniforms(t,n,a,i,o);d.covariancesTextureSize={type:"v2",value:new e.Vector2(1024,1024)},d.covariancesTexture={type:"t",value:null},d.covariancesTextureHalfFloat={type:"t",value:null},d.covariancesAreHalfFloat={type:"i",value:0};return new e.ShaderMaterial({uniforms:d,vertexShader:c,fragmentShader:h,transparent:!0,alphaTest:1,blending:e.NormalBlending,depthTest:!0,depthWrite:!1,side:e.DoubleSide})}static buildVertexShaderProjection(e,t,n,s){let r="\n\n vec4 sampledCovarianceA;\n vec4 sampledCovarianceB;\n vec3 cov3D_M11_M12_M13;\n vec3 cov3D_M22_M23_M33;\n if (covariancesAreHalfFloat == 0) {\n sampledCovarianceA = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset,\n covariancesTextureSize));\n sampledCovarianceB = texture(covariancesTexture, getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1),\n covariancesTextureSize));\n\n cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;\n cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceB.gba) * fOddOffset;\n } else {\n uvec4 sampledCovarianceU = texture(covariancesTextureHalfFloat, getDataUV(1, 0, covariancesTextureSize));\n fromCovarianceHalfFloatV4(sampledCovarianceU, sampledCovarianceA, sampledCovarianceB);\n cov3D_M11_M12_M13 = sampledCovarianceA.rgb;\n cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg);\n }\n \n // Construct the 3D covariance matrix\n mat3 Vrk = mat3(\n cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,\n cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,\n cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z\n );\n\n mat3 J;\n if (orthographicMode == 1) {\n // Since the projection is linear, we don't need an approximation\n J = transpose(mat3(orthoZoom, 0.0, 0.0,\n 0.0, orthoZoom, 0.0,\n 0.0, 0.0, 0.0));\n } else {\n // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result.\n float s = 1.0 / (viewCenter.z * viewCenter.z);\n J = mat3(\n focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,\n 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,\n 0., 0., 0.\n );\n }\n\n // Concatenate the projection approximation with the model-view transformation\n mat3 W = transpose(mat3(transformModelViewMatrix));\n mat3 T = W * J;\n\n // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix\n mat3 cov2Dm = transpose(T) * Vrk * T;\n ";return r+=e?`\n float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n cov2Dm[0][0] += ${s};\n cov2Dm[1][1] += ${s};\n float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n vColor.a *= sqrt(max(detOrig / detBlur, 0.0));\n if (vColor.a < minAlpha) return;\n `:`\n cov2Dm[0][0] += ${s};\n cov2Dm[1][1] += ${s};\n `,r+=`\n\n // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because\n // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],\n // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't\n // need cov2Dm[1][0] because it is a symetric matrix.\n vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);\n\n // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix\n // so that we can determine the 2D basis for the splat. This is done using the method described\n // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html\n // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat\n // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * sqrt(eigen-value)), which is\n // equal to scaling them by sqrt(8) standard deviations.\n //\n // This is a different approach than in the original work at INRIA. In that work they compute the\n // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle\n // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0\n // times the square root of the maximum eigen-value, or 3 standard deviations. They then use the inverse\n // 2D covariance matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by\n // calculating the full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity\n float a = cov2Dv.x;\n float d = cov2Dv.z;\n float b = cov2Dv.y;\n float D = a * d - b * b;\n float trace = a + d;\n float traceOver2 = 0.5 * trace;\n float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));\n float eigenValue1 = traceOver2 + term2;\n float eigenValue2 = traceOver2 - term2;\n\n if (pointCloudModeEnabled == 1) {\n eigenValue1 = eigenValue2 = 0.2;\n }\n\n if (eigenValue2 <= 0.0) return;\n\n vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));\n // since the eigen vectors are orthogonal, we derive the second one from the first\n vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);\n\n // We use sqrt(8) standard deviations instead of 3 to eliminate more of the splat with a very low opacity.\n vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ${parseInt(n)}.0);\n vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ${parseInt(n)}.0);\n `,t&&(r+="\n vColor.a *= splatOpacityFromScene;\n "),r+="\n vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *\n basisViewport * 2.0 * inverseFocalAdjustment;\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n // Scale the position data we send to the fragment shader\n vPosition *= sqrt8;\n ",r+=an.getVertexShaderFadeIn(),r+="}",r}static buildFragmentShader(){let e="\n precision highp float;\n #include <common>\n \n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n ";return e+="\n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n if (A > 8.0) discard;\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp(-0.5 * A) * vColor.a;\n\n gl_FragColor = vec4(color.rgb, opacity);\n }\n ","\n precision highp float;\n #include <common>\n \n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n \n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n if (A > 8.0) discard;\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp(-0.5 * A) * vColor.a;\n\n gl_FragColor = vec4(color.rgb, opacity);\n }\n "}}class cn{static build(t=!1,n=!1,s=1,r=!1,i=0){let o=an.buildVertexShaderBase(t,n,i,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");o+=cn.buildVertexShaderProjection();const a=cn.buildFragmentShader(),l=an.getUniforms(t,n,i,s,r);l.scaleRotationsTexture={type:"t",value:null},l.scaleRotationsTextureSize={type:"v2",value:new e.Vector2(1024,1024)};return new e.ShaderMaterial({uniforms:l,vertexShader:o,fragmentShader:a,transparent:!0,alphaTest:1,blending:e.NormalBlending,depthTest:!0,depthWrite:!1,side:e.DoubleSide})}static buildVertexShaderProjection(){let e="\n\n vec4 scaleRotationA = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,\n oddOffset, scaleRotationsTextureSize));\n vec4 scaleRotationB = texture(scaleRotationsTexture, getDataUVF(nearestEvenIndex, 1.5,\n oddOffset + uint(1), scaleRotationsTextureSize));\n\n vec3 scaleRotation123 = vec3(scaleRotationA.rgb) * (1.0 - fOddOffset) +\n vec3(scaleRotationA.ba, scaleRotationB.r) * fOddOffset;\n vec3 scaleRotation456 = vec3(scaleRotationA.a, scaleRotationB.rg) * (1.0 - fOddOffset) +\n vec3(scaleRotationB.gba) * fOddOffset;\n\n float missingW = sqrt(1.0 - scaleRotation456.x * scaleRotation456.x - scaleRotation456.y *\n scaleRotation456.y - scaleRotation456.z * scaleRotation456.z);\n mat3 R = quaternionToRotationMatrix(scaleRotation456.r, scaleRotation456.g, scaleRotation456.b, missingW);\n mat3 S = mat3(scaleRotation123.r, 0.0, 0.0,\n 0.0, scaleRotation123.g, 0.0,\n 0.0, 0.0, scaleRotation123.b);\n \n mat3 L = R * S;\n\n mat3x4 splat2World = mat3x4(vec4(L[0], 0.0),\n vec4(L[1], 0.0),\n vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));\n\n mat4 world2ndc = transpose(projectionMatrix * transformModelViewMatrix);\n\n mat3x4 ndc2pix = mat3x4(vec4(viewport.x / 2.0, 0.0, 0.0, (viewport.x - 1.0) / 2.0),\n vec4(0.0, viewport.y / 2.0, 0.0, (viewport.y - 1.0) / 2.0),\n vec4(0.0, 0.0, 0.0, 1.0));\n\n mat3 T = transpose(splat2World) * world2ndc * ndc2pix;\n vec3 normal = vec3(viewMatrix * vec4(L[0][2], L[1][2], L[2][2], 0.0));\n ";return e+="\n\n mat4 splat2World4 = mat4(vec4(L[0], 0.0),\n vec4(L[1], 0.0),\n vec4(L[2], 0.0),\n vec4(splatCenter.x, splatCenter.y, splatCenter.z, 1.0));\n\n mat4 Tt = transpose(transpose(splat2World4) * world2ndc);\n\n vec4 tempPoint1 = Tt * vec4(1.0, 0.0, 0.0, 1.0);\n tempPoint1 /= tempPoint1.w;\n\n vec4 tempPoint2 = Tt * vec4(0.0, 1.0, 0.0, 1.0);\n tempPoint2 /= tempPoint2.w;\n\n vec4 center = Tt * vec4(0.0, 0.0, 0.0, 1.0);\n center /= center.w;\n\n vec2 basisVector1 = tempPoint1.xy - center.xy;\n vec2 basisVector2 = tempPoint2.xy - center.xy;\n\n vec2 basisVector1Screen = basisVector1 * 0.5 * viewport;\n vec2 basisVector2Screen = basisVector2 * 0.5 * viewport;\n\n const float minPix = 1.;\n if (length(basisVector1Screen) < minPix || length(basisVector2Screen) < minPix) {\n \n vec3 T0 = vec3(T[0][0], T[0][1], T[0][2]);\n vec3 T1 = vec3(T[1][0], T[1][1], T[1][2]);\n vec3 T3 = vec3(T[2][0], T[2][1], T[2][2]);\n\n vec3 tempPoint = vec3(1.0, 1.0, -1.0);\n float distance = (T3.x * T3.x * tempPoint.x) + (T3.y * T3.y * tempPoint.y) + (T3.z * T3.z * tempPoint.z);\n vec3 f = (1.0 / distance) * tempPoint;\n if (abs(distance) < 0.00001) return;\n\n float pointImageX = (T0.x * T3.x * f.x) + (T0.y * T3.y * f.y) + (T0.z * T3.z * f.z);\n float pointImageY = (T1.x * T3.x * f.x) + (T1.y * T3.y * f.y) + (T1.z * T3.z * f.z);\n vec2 pointImage = vec2(pointImageX, pointImageY);\n\n float tempX = (T0.x * T0.x * f.x) + (T0.y * T0.y * f.y) + (T0.z * T0.z * f.z);\n float tempY = (T1.x * T1.x * f.x) + (T1.y * T1.y * f.y) + (T1.z * T1.z * f.z);\n vec2 temp = vec2(tempX, tempY);\n\n vec2 halfExtend = pointImage * pointImage - temp;\n vec2 extent = sqrt(max(vec2(0.0001), halfExtend));\n float radius = max(extent.x, extent.y);\n\n vec2 ndcOffset = ((position.xy * radius * 3.0) * basisViewport * 2.0);\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n vT = T;\n vQuadCenter = pointImage;\n vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;\n \n } else {\n vec2 ndcOffset = vec2(position.x * basisVector1 + position.y * basisVector2) * 3.0 * inverseFocalAdjustment;\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z, 1.0);\n gl_Position = quadPos;\n\n vT = T;\n vQuadCenter = center.xy;\n vFragCoord = (quadPos.xy * 0.5 + 0.5) * viewport;\n }\n ",e+=an.getVertexShaderFadeIn(),e+="}",e}static buildFragmentShader(){return"\n precision highp float;\n #include <common>\n\n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n\n void main () {\n\n const float FilterInvSquare = 2.0;\n const float near_n = 0.2;\n const float T = 1.0;\n\n vec2 xy = vQuadCenter;\n vec3 Tu = vT[0];\n vec3 Tv = vT[1];\n vec3 Tw = vT[2];\n vec3 k = vFragCoord.x * Tw - Tu;\n vec3 l = vFragCoord.y * Tw - Tv;\n vec3 p = cross(k, l);\n if (p.z == 0.0) discard;\n vec2 s = vec2(p.x / p.z, p.y / p.z);\n float rho3d = (s.x * s.x + s.y * s.y); \n vec2 d = vec2(xy.x - vFragCoord.x, xy.y - vFragCoord.y);\n float rho2d = FilterInvSquare * (d.x * d.x + d.y * d.y); \n\n // compute intersection and depth\n float rho = min(rho3d, rho2d);\n float depth = (rho3d <= rho2d) ? (s.x * Tw.x + s.y * Tw.y) + Tw.z : Tw.z; \n if (depth < near_n) discard;\n // vec4 nor_o = collected_normal_opacity[j];\n // float normal[3] = {nor_o.x, nor_o.y, nor_o.z};\n float opa = vColor.a;\n\n float power = -0.5f * rho;\n if (power > 0.0f) discard;\n\n // Eq. (2) from 3D Gaussian splatting paper.\n // Obtain alpha by multiplying with Gaussian opacity\n // and its exponential falloff from mean.\n // Avoid numerical instabilities (see paper appendix). \n float alpha = min(0.99f, opa * exp(power));\n if (alpha < 1.0f / 255.0f) discard;\n float test_T = T * (1.0 - alpha);\n if (test_T < 0.0001)discard;\n\n float w = alpha * T;\n gl_FragColor = vec4(vColor.rgb, w);\n }\n "}}class hn{static build(t){const n=new e.BufferGeometry;n.setIndex([0,1,2,0,2,3]);const s=new Float32Array(12),r=new e.BufferAttribute(s,3);n.setAttribute("position",r),r.setXYZ(0,-1,-1,0),r.setXYZ(1,-1,1,0),r.setXYZ(2,1,1,0),r.setXYZ(3,1,-1,0),r.needsUpdate=!0;const i=(new e.InstancedBufferGeometry).copy(n),o=new Uint32Array(t),a=new e.InstancedBufferAttribute(o,1,!1);return a.setUsage(e.DynamicDrawUsage),i.setAttribute("splatIndex",a),i.instanceCount=0,i}}class dn extends e.Object3D{constructor(t,n=new e.Vector3,s=new e.Quaternion,r=new e.Vector3(1,1,1),i=1,o=1,a=!0){super(),this.splatBuffer=t,this.position.copy(n),this.quaternion.copy(s),this.scale.copy(r),this.transform=new e.Matrix4,this.minimumAlpha=i,this.opacity=o,this.visible=a}copyTransformData(e){this.position.copy(e.position),this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.transform.copy(e.transform)}updateTransform(e){e?(this.matrixWorldAutoUpdate&&this.updateWorldMatrix(!0,!1),this.transform.copy(this.matrixWorld)):(this.matrixAutoUpdate&&this.updateMatrix(),this.transform.copy(this.matrix))}}class pn{static idGen=0;constructor(t,n,s,r){this.min=(new e.Vector3).copy(t),this.max=(new e.Vector3).copy(n),this.boundingBox=new e.Box3(this.min,this.max),this.center=(new e.Vector3).copy(this.max).sub(this.min).multiplyScalar(.5).add(this.min),this.depth=s,this.children=[],this.data=null,this.id=r||pn.idGen++}}class un{constructor(t,n){this.maxDepth=t,this.maxCentersPerNode=n,this.sceneDimensions=new e.Vector3,this.sceneMin=new e.Vector3,this.sceneMax=new e.Vector3,this.rootNode=null,this.nodesWithIndexes=[],this.splatMesh=null}static convertWorkerSubTreeNode(t){const n=(new e.Vector3).fromArray(t.min),s=(new e.Vector3).fromArray(t.max),r=new pn(n,s,t.depth,t.id);if(t.data.indexes){r.data={indexes:[]};for(let e of t.data.indexes)r.data.indexes.push(e)}if(t.children)for(let e of t.children)r.children.push(un.convertWorkerSubTreeNode(e));return r}static convertWorkerSubTree(t,n){const s=new un(t.maxDepth,t.maxCentersPerNode);s.sceneMin=(new e.Vector3).fromArray(t.sceneMin),s.sceneMax=(new e.Vector3).fromArray(t.sceneMax),s.splatMesh=n,s.rootNode=un.convertWorkerSubTreeNode(t.rootNode);const r=(e,t)=>{0===e.children.length&&t(e);for(let n of e.children)r(n,t)};return s.nodesWithIndexes=[],r(s.rootNode,(e=>{e.data&&e.data.indexes&&e.data.indexes.length>0&&s.nodesWithIndexes.push(e)})),s}}function mn(e){let t=0;class n{constructor(e,t){this.min=[e[0],e[1],e[2]],this.max=[t[0],t[1],t[2]]}containsPoint(e){return e[0]>=this.min[0]&&e[0]<=this.max[0]&&e[1]>=this.min[1]&&e[1]<=this.max[1]&&e[2]>=this.min[2]&&e[2]<=this.max[2]}}class s{constructor(e,t){this.maxDepth=e,this.maxCentersPerNode=t,this.sceneDimensions=[],this.sceneMin=[],this.sceneMax=[],this.rootNode=null,this.addedIndexes={},this.nodesWithIndexes=[],this.splatMesh=null,this.disposed=!1}}class r{constructor(e,n,s,r){this.min=[e[0],e[1],e[2]],this.max=[n[0],n[1],n[2]],this.center=[.5*(n[0]-e[0])+e[0],.5*(n[1]-e[1])+e[1],.5*(n[2]-e[2])+e[2]],this.depth=s,this.children=[],this.data=null,this.id=r||t++}}processSplatTreeNode=function(e,t,s,i){const o=t.data.indexes.length;if(o<e.maxCentersPerNode||t.depth>e.maxDepth){const n=[];for(let s=0;s<t.data.indexes.length;s++)e.addedIndexes[t.data.indexes[s]]||(n.push(t.data.indexes[s]),e.addedIndexes[t.data.indexes[s]]=!0);return t.data.indexes=n,t.data.indexes.sort(((e,t)=>e>t?1:-1)),void e.nodesWithIndexes.push(t)}const a=[t.max[0]-t.min[0],t.max[1]-t.min[1],t.max[2]-t.min[2]],l=[.5*a[0],.5*a[1],.5*a[2]],c=[t.min[0]+l[0],t.min[1]+l[1],t.min[2]+l[2]],h=[new n([c[0]-l[0],c[1],c[2]-l[2]],[c[0],c[1]+l[1],c[2]]),new n([c[0],c[1],c[2]-l[2]],[c[0]+l[0],c[1]+l[1],c[2]]),new n([c[0],c[1],c[2]],[c[0]+l[0],c[1]+l[1],c[2]+l[2]]),new n([c[0]-l[0],c[1],c[2]],[c[0],c[1]+l[1],c[2]+l[2]]),new n([c[0]-l[0],c[1]-l[1],c[2]-l[2]],[c[0],c[1],c[2]]),new n([c[0],c[1]-l[1],c[2]-l[2]],[c[0]+l[0],c[1],c[2]]),new n([c[0],c[1]-l[1],c[2]],[c[0]+l[0],c[1],c[2]+l[2]]),new n([c[0]-l[0],c[1]-l[1],c[2]],[c[0],c[1],c[2]+l[2]])],d=[];for(let e=0;e<h.length;e++)d[e]=[];const p=[0,0,0];for(let e=0;e<o;e++){const n=t.data.indexes[e],r=s[n];p[0]=i[r],p[1]=i[r+1],p[2]=i[r+2];for(let e=0;e<h.length;e++)h[e].containsPoint(p)&&d[e].push(n)}for(let e=0;e<h.length;e++){const n=new r(h[e].min,h[e].max,t.depth+1);n.data={indexes:d[e]},t.children.push(n)}t.data={};for(let n of t.children)processSplatTreeNode(e,n,s,i)};const i=(e,t,n)=>{const i=[0,0,0],o=[0,0,0],a=[],l=Math.floor(e.length/4);for(let t=0;t<l;t++){const n=4*t,s=e[n],r=e[n+1],l=e[n+2],c=Math.round(e[n+3]);(0===t||s<i[0])&&(i[0]=s),(0===t||s>o[0])&&(o[0]=s),(0===t||r<i[1])&&(i[1]=r),(0===t||r>o[1])&&(o[1]=r),(0===t||l<i[2])&&(i[2]=l),(0===t||l>o[2])&&(o[2]=l),a.push(c)}const c=new s(t,n);return c.sceneMin=i,c.sceneMax=o,c.rootNode=new r(c.sceneMin,c.sceneMax,0),c.rootNode.data={indexes:a},c};e.onmessage=t=>{t.data.process&&function(t,n,s){const r=[];for(let e of t){const t=Math.floor(e.length/4);for(let n=0;n<t;n++){const t=4*n;r[Math.round(e[t+3])]=t}}const o=[];for(let e of t){const t=i(e,n,s);o.push(t),processSplatTreeNode(t,t.rootNode,r,e)}e.postMessage({subTrees:o})}(t.data.process.centers,t.data.process.maxDepth,t.data.process.maxCentersPerNode)}}class An{constructor(e,t){this.maxDepth=e,this.maxCentersPerNode=t,this.subTrees=[],this.splatMesh=null}dispose(){this.diposeSplatTreeWorker(),this.disposed=!0}diposeSplatTreeWorker(){this.splatTreeWorker&&this.splatTreeWorker.terminate(),this.splatTreeWorker=null}processSplatMesh=function(t,n=(()=>!0),s,r){this.splatTreeWorker||(this.splatTreeWorker=new Worker(URL.createObjectURL(new Blob(["(",mn.toString(),")(self)"],{type:"application/javascript"})))),this.splatMesh=t,this.subTrees=[];const i=new e.Vector3,o=(e,s)=>{const r=new Float32Array(4*s);let o=0;for(let a=0;a<s;a++){const s=a+e;if(n(s)){t.getSplatCenter(s,i);const e=4*o;r[e]=i.x,r[e+1]=i.y,r[e+2]=i.z,r[e+3]=s,o++}}return r};return new Promise((e=>{const n=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),e(),!0);s&&s(!1),S((()=>{if(n())return;const i=[];if(t.dynamicMode){let e=0;for(let n=0;n<t.scenes.length;n++){const s=t.getScene(n).splatBuffer.getSplatCount(),r=o(e,s);i.push(r),e+=s}}else{const e=o(0,t.getSplatCount());i.push(e)}this.splatTreeWorker.onmessage=s=>{n()||s.data.subTrees&&(r&&r(!1),S((()=>{if(!n()){for(let e of s.data.subTrees){const n=un.convertWorkerSubTree(e,t);this.subTrees.push(n)}this.diposeSplatTreeWorker(),r&&r(!0),S((()=>{e()}))}})))},S((()=>{if(n())return;s&&s(!0);const e=i.map((e=>e.buffer));!function(e,t,n,s,r){e.postMessage({process:{centers:t,maxDepth:s,maxCentersPerNode:r}},n)}(this.splatTreeWorker,i,e,this.maxDepth,this.maxCentersPerNode)}))}))}))};countLeaves(){let e=0;return this.visitLeaves((()=>{e++})),e}visitLeaves(e){const t=(e,n)=>{0===e.children.length&&n(e);for(let s of e.children)t(s,n)};for(let n of this.subTrees)t(n.rootNode,e)}}function fn(e){const t={};function n(n){if(void 0!==t[n])return t[n];let s;switch(n){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(n)}return t[n]=s,s}return{has:function(e){return null!==n(e)},init:function(e){e.isWebGL2?(n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance")):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture")},get:function(e){const t=n(e);return null===t&&console.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function gn(e,t,n){let s;function r(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const i="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let o=void 0!==n.precision?n.precision:"highp";const a=r(o);a!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",a,"instead."),o=a);const l=i||t.has("WEBGL_draw_buffers"),c=!0===n.logarithmicDepthBuffer,h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),d=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=e.getParameter(e.MAX_TEXTURE_SIZE),u=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),A=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),f=e.getParameter(e.MAX_VARYING_VECTORS),g=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),S=d>0,C=i||t.has("OES_texture_float");return{isWebGL2:i,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==s)return s;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");s=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s},getMaxPrecision:r,precision:o,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:d,maxTextureSize:p,maxCubemapSize:u,maxAttributes:m,maxVertexUniforms:A,maxVaryings:f,maxFragmentUniforms:g,vertexTextures:S,floatFragmentTextures:C,floatVertexTextures:S&&C,maxSamples:i?e.getParameter(e.MAX_SAMPLES):0}}const Sn=0,Cn=2,yn=0,xn=3,vn=new e.BufferGeometry,In=new e.MeshBasicMaterial,Bn=16777216;class wn extends e.Mesh{constructor(t=sn,n=!1,s=!1,r=!1,i=1,o=!0,a=!1,l=!1,c=1024,h=yn,d=0,p=1,u=.3){super(vn,In),this.renderer=void 0,this.splatRenderMode=t,this.dynamicMode=n,this.enableOptionalEffects=s,this.halfPrecisionCovariancesOnGPU=r,this.devicePixelRatio=i,this.enableDistancesComputationOnGPU=o,this.integerBasedDistancesComputation=a,this.antialiased=l,this.kernel2DSize=u,this.maxScreenSpaceSplatSize=c,this.logLevel=h,this.sphericalHarmonicsDegree=d,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=p,this.scenes=[],this.splatTree=null,this.baseSplatTree=null,this.splatDataTextures={},this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new e.Box3,this.calculatedSceneCenter=new e.Vector3,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!1,this.lastRenderer=null,this.visible=!1}static buildScenes(t,n,s){const r=[];r.length=n.length;for(let i=0;i<n.length;i++){const o=n[i],a=s[i]||{};let l=a.position||[0,0,0],c=a.rotation||[0,0,0,1],h=a.scale||[1,1,1];const d=(new e.Vector3).fromArray(l),p=(new e.Quaternion).fromArray(c),u=(new e.Vector3).fromArray(h),m=wn.createScene(o,d,p,u,a.splatAlphaRemovalThreshold||1,a.opacity,a.visible);t.add(m),r[i]=m}return r}static createScene(e,t,n,s,r,i=1,o=!0){return new dn(e,t,n,s,r,i,o)}static buildSplatIndexMaps(e){const t=[],n=[];let s=0;for(let r=0;r<e.length;r++){const i=e[r].getMaxSplatCount();for(let e=0;e<i;e++)t[s]=e,n[s]=r,s++}return{localSplatIndexMap:t,sceneIndexMap:n}}buildSplatTree=function(t=[],n,s){return new Promise((r=>{this.disposeSplatTree(),this.baseSplatTree=new An(8,1e3);const i=performance.now(),o=new e.Vector4;this.baseSplatTree.processSplatMesh(this,(e=>{this.getSplatColor(e,o);const n=this.getSceneIndexForSplat(e),s=t[n]||1;return o.w>=s}),n,s).then((()=>{const e=performance.now()-i;if(this.logLevel>=xn&&console.log("SplatTree build: "+e+" ms"),this.disposed)r();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let e=0,t=0,n=0;this.splatTree.visitLeaves((s=>{const r=s.data.indexes.length;r>0&&(t+=r,n++,e++)})),this.logLevel>=xn&&(console.log(`SplatTree leaves: ${this.splatTree.countLeaves()}`),console.log(`SplatTree leaves with splats:${e}`),t/=n,console.log(`Avg splat count per node: ${t}`),console.log(`Total splat count: ${this.getSplatCount()}`)),r()}}))}))};build(t,n,s=!0,r=!1,i,o,a=!0){this.sceneOptions=n,this.finalBuild=r;const l=wn.getTotalMaxSplatCountForSplatBuffers(t),c=wn.buildScenes(this,t,n);if(s)for(let e=0;e<this.scenes.length&&e<c.length;e++){const t=c[e],n=this.getScene(e);t.copyTransformData(n)}this.scenes=c;let h=3;for(let e of t){const t=e.getMinSphericalHarmonicsDegree();t<h&&(h=t)}this.minSphericalHarmonicsDegree=Math.min(h,this.sphericalHarmonicsDegree);let d=!1;if(t.length!==this.lastBuildScenes.length)d=!0;else for(let e=0;e<t.length;e++){if(t[e]!==this.lastBuildScenes[e].splatBuffer){d=!0;break}}let p=!0;if((1!==this.scenes.length||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==l||d)&&(p=!1),!p){this.boundingBox=new e.Box3,a||(this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.firstRenderTime=-1),this.lastBuildScenes=[],this.lastBuildSplatCount=0,this.lastBuildMaxSplatCount=0,this.disposeMeshData(),this.geometry=hn.build(l),this.splatRenderMode===sn?this.material=ln.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize):this.material=cn.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const n=wn.buildSplatIndexMaps(t);this.globalSplatIndexToLocalSplatIndexMap=n.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=n.sceneIndexMap}const u=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();const m=this.refreshGPUDataFromSplatBuffers(p);for(let e=0;e<this.scenes.length;e++)this.lastBuildScenes[e]=this.scenes[e];return this.lastBuildSplatCount=u,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,r&&this.scenes.length>0&&this.buildSplatTree(n.map((e=>e.splatAlphaRemovalThreshold||1)),i,o).then((()=>{this.onSplatTreeReadyCallback&&this.onSplatTreeReadyCallback(this.splatTree),this.onSplatTreeReadyCallback=null})),this.visible=this.scenes.length>0,m}freeIntermediateSplatData(){const e=e=>{delete e.source.data,delete e.image,e.onUpdate=null};delete this.splatDataTextures.baseData.covariances,delete this.splatDataTextures.baseData.centers,delete this.splatDataTextures.baseData.colors,delete this.splatDataTextures.baseData.sphericalHarmonics,delete this.splatDataTextures.centerColors.data,delete this.splatDataTextures.covariances.data,this.splatDataTextures.sphericalHarmonics&&delete this.splatDataTextures.sphericalHarmonics.data,this.splatDataTextures.sceneIndexes&&delete this.splatDataTextures.sceneIndexes.data,this.splatDataTextures.centerColors.texture.needsUpdate=!0,this.splatDataTextures.centerColors.texture.onUpdate=()=>{e(this.splatDataTextures.centerColors.texture)},this.splatDataTextures.covariances.texture.needsUpdate=!0,this.splatDataTextures.covariances.texture.onUpdate=()=>{e(this.splatDataTextures.covariances.texture)},this.splatDataTextures.sphericalHarmonics&&(this.splatDataTextures.sphericalHarmonics.texture?(this.splatDataTextures.sphericalHarmonics.texture.needsUpdate=!0,this.splatDataTextures.sphericalHarmonics.texture.onUpdate=()=>{e(this.splatDataTextures.sphericalHarmonics.texture)}):this.splatDataTextures.sphericalHarmonics.textures.forEach((t=>{t.needsUpdate=!0,t.onUpdate=()=>{e(t)}}))),this.splatDataTextures.sceneIndexes&&(this.splatDataTextures.sceneIndexes.texture.needsUpdate=!0,this.splatDataTextures.sceneIndexes.texture.onUpdate=()=>{e(this.splatDataTextures.sceneIndexes.texture)})}dispose(){this.disposeMeshData(),this.disposeTextures(),this.disposeSplatTree(),this.enableDistancesComputationOnGPU&&(this.computeDistancesOnGPUSyncTimeout&&(clearTimeout(this.computeDistancesOnGPUSyncTimeout),this.computeDistancesOnGPUSyncTimeout=null),this.disposeDistancesComputationGPUResources()),this.scenes=[],this.distancesTransformFeedback={id:null,vertexShader:null,fragmentShader:null,program:null,centersBuffer:null,sceneIndexesBuffer:null,outDistancesBuffer:null,centersLoc:-1,modelViewProjLoc:-1,sceneIndexesLoc:-1,transformsLocs:[]},this.renderer=null,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSceneIndexMap=[],this.lastBuildSplatCount=0,this.lastBuildScenes=[],this.lastBuildMaxSplatCount=0,this.lastBuildSceneCount=0,this.firstRenderTime=-1,this.finalBuild=!1,this.webGLUtils=null,this.boundingBox=new e.Box3,this.calculatedSceneCenter=new e.Vector3,this.maxSplatDistanceFromSceneCenter=0,this.visibleRegionBufferRadius=0,this.visibleRegionRadius=0,this.visibleRegionFadeStartRadius=0,this.visibleRegionChanging=!1,this.splatScale=1,this.pointCloudModeEnabled=!1,this.disposed=!0,this.lastRenderer=null,this.visible=!1}disposeMeshData(){this.geometry&&this.geometry!==vn&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}disposeTextures(){for(let e in this.splatDataTextures)if(this.splatDataTextures.hasOwnProperty(e)){const t=this.splatDataTextures[e];t.texture&&(t.texture.dispose(),t.texture=null)}this.splatDataTextures=null}disposeSplatTree(){this.splatTree&&(this.splatTree.dispose(),this.splatTree=null),this.baseSplatTree&&(this.baseSplatTree.dispose(),this.baseSplatTree=null)}getSplatTree(){return this.splatTree}onSplatTreeReady(e){this.onSplatTreeReadyCallback=e}getDataForDistancesComputation(e,t){return{centers:this.integerBasedDistancesComputation?this.getIntegerCenters(e,t,!0):this.getFloatCenters(e,t,!0),sceneIndexes:this.getSceneIndexes(e,t)}}refreshGPUDataFromSplatBuffers(e){const t=this.getSplatCount(!0);this.refreshDataTexturesFromSplatBuffers(e);const n=e?this.lastBuildSplatCount:0,{centers:s,sceneIndexes:r}=this.getDataForDistancesComputation(n,t-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(s,r,e),{from:n,to:t-1,count:t-n,centers:s,sceneIndexes:r}}refreshGPUBuffersForDistancesComputation(e,t,n=!1){const s=n?this.lastBuildSplatCount:0;this.updateGPUCentersBufferForDistancesComputation(n,e,s),this.updateGPUTransformIndexesBufferForDistancesComputation(n,t,s)}refreshDataTexturesFromSplatBuffers(e){const t=this.getSplatCount(!0),n=this.lastBuildSplatCount,s=t-1;e?this.updateBaseDataFromSplatBuffers(n,s):(this.setupDataTextures(),this.updateBaseDataFromSplatBuffers()),this.updateDataTexturesFromBaseData(n,s),this.updateVisibleRegion(e)}setupDataTextures(){const t=this.getMaxSplatCount(),n=this.getSplatCount(!0);this.disposeTextures();const s=(n,s)=>{const r=new e.Vector2(4096,1024);for(;r.x*r.y*n<t*s;)r.y*=2;return r},r=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:s(t,6)}};let i=this.getTargetCovarianceCompressionLevel();const o=this.getTargetSphericalHarmonicsCompressionLevel();let a,l,c;if(this.splatRenderMode===sn){const e=r(i);e.texSize.x*e.texSize.y>Bn&&0===i&&(i=1),a=new Float32Array(6*t)}else l=new Float32Array(3*t),c=new Float32Array(4*t);const h=new Float32Array(3*t),d=new Uint8Array(4*t);let p=Float32Array;1===o?p=Uint16Array:2===o&&(p=Uint8Array);const u=C(this.minSphericalHarmonicsDegree),m=this.minSphericalHarmonicsDegree?new p(t*u):void 0,A=s(4,4),f=new Uint32Array(A.x*A.y*4);wn.updateCenterColorsPaddedData(0,n-1,h,d,f);const g=new e.DataTexture(f,A.x,A.y,e.RGBAIntegerFormat,e.UnsignedIntType);if(g.internalFormat="RGBA32UI",g.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=g,this.material.uniforms.centersColorsTextureSize.value.copy(A),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:a,scales:l,rotations:c,centers:h,colors:d,sphericalHarmonics:m},centerColors:{data:f,texture:g,size:A}},this.splatRenderMode===sn){const t=r(i),n=t.elementsPerTexelStored,s=t.texSize;const o=i>=1?8:4,l=new(i>=1?Uint32Array:Float32Array)(s.x*s.y*o);let c;if(0===i?l.set(a):wn.updatePaddedCompressedCovariancesTextureData(a,l,0,0,a.length),i>=1)c=new e.DataTexture(l,s.x,s.y,e.RGBAIntegerFormat,e.UnsignedIntType),c.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=c;else{c=new e.DataTexture(l,s.x,s.y,e.RGBAFormat,e.FloatType),this.material.uniforms.covariancesTexture.value=c;const t=new e.DataTexture(new Uint32Array(32),2,2,e.RGBAIntegerFormat,e.UnsignedIntType);t.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=t,t.needsUpdate=!0}c.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=i>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(s),this.splatDataTextures.covariances={data:l,texture:c,size:s,compressionLevel:i,elementsPerTexelStored:n,elementsPerTexelAllocated:o}}else{const t=s(4,6);let r=Float32Array,i=e.FloatType;const o=new r(t.x*t.y*4);wn.updateScaleRotationsPaddedData(0,n-1,l,c,o);const a=new e.DataTexture(o,t.x,t.y,e.RGBAFormat,i);a.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=a,this.material.uniforms.scaleRotationsTextureSize.value.copy(t),this.splatDataTextures.scaleRotations={data:o,texture:a,size:t,compressionLevel:0}}if(m){const t=2===o?e.UnsignedByteType:e.HalfFloatType;let r=u;r%2!=0&&r++;const i=4,a=e.RGBAFormat;let l=s(i,r);if(l.x*l.y<=Bn){const s=new p(l.x*l.y*i);for(let e=0;e<n;e++){const t=u*e,n=r*e;for(let e=0;e<u;e++)s[n+e]=m[t+e]}const c=new e.DataTexture(s,l.x,l.y,a,t);c.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=c,this.splatDataTextures.sphericalHarmonics={componentCount:u,paddedComponentCount:r,data:s,textureCount:1,texture:c,size:l,compressionLevel:o,elementsPerTexel:i}}else{const c=u/3;r=c,r%2!=0&&r++,l=s(i,r);const h=l.x*l.y*i,d=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],A=[],f=[];for(let s=0;s<3;s++){const i=new p(h);A.push(i);for(let e=0;e<n;e++){const t=u*e,n=r*e;if(c>=3){for(let e=0;e<3;e++)i[n+e]=m[t+3*s+e];if(c>=8)for(let e=0;e<5;e++)i[n+3+e]=m[t+9+5*s+e]}}const o=new e.DataTexture(i,l.x,l.y,a,t);f.push(o),o.needsUpdate=!0,d[s].value=o}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:u,componentCountPerChannel:c,paddedComponentCount:r,data:A,textureCount:3,textures:f,size:l,compressionLevel:o,elementsPerTexel:i}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(l),this.material.uniforms.sphericalHarmonics8BitMode.value=2===o?1:0;for(let e=0;e<this.scenes.length;e++){const t=this.scenes[e].splatBuffer;this.material.uniforms.sphericalHarmonics8BitCompressionRangeMin.value[e]=t.minSphericalHarmonicsCoeff,this.material.uniforms.sphericalHarmonics8BitCompressionRangeMax.value[e]=t.maxSphericalHarmonicsCoeff}this.material.uniformsNeedUpdate=!0}const S=s(1,4),y=new Uint32Array(S.x*S.y*1);for(let e=0;e<n;e++)y[e]=this.globalSplatIndexToSceneIndexMap[e];const x=new e.DataTexture(y,S.x,S.y,e.RedIntegerFormat,e.UnsignedIntType);x.internalFormat="R32UI",x.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=x,this.material.uniforms.sceneIndexesTextureSize.value.copy(S),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:y,texture:x,size:S},this.material.uniforms.sceneCount.value=this.scenes.length}updateBaseDataFromSplatBuffers(e,t){const n=this.splatDataTextures.covariances,s=n?n.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,i=r?r.compressionLevel:void 0,o=this.splatDataTextures.sphericalHarmonics,a=o?o.compressionLevel:0;this.fillSplatDataArrays(this.splatDataTextures.baseData.covariances,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,this.splatDataTextures.baseData.sphericalHarmonics,void 0,s,i,a,e,t,e)}updateDataTexturesFromBaseData(e,t){const n=this.splatDataTextures.covariances,s=n?n.compressionLevel:void 0,r=this.splatDataTextures.scaleRotations,i=r?r.compressionLevel:void 0,o=this.splatDataTextures.sphericalHarmonics,a=o?o.compressionLevel:0,l=this.splatDataTextures.centerColors,c=l.data,h=l.texture;wn.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,c);const d=this.renderer?this.renderer.properties.get(h):null;if(d&&d.__webglTexture?this.updateDataTexture(c,l.texture,l.size,d,4,4,4,e,t):h.needsUpdate=!0,n){const r=n.texture,i=6*e,o=6*t;if(0===s)for(let e=i;e<=o;e++){const t=this.splatDataTextures.baseData.covariances[e];n.data[e]=t}else wn.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,n.data,e*n.elementsPerTexelAllocated,i,o);const a=this.renderer?this.renderer.properties.get(r):null;a&&a.__webglTexture?0===s?this.updateDataTexture(n.data,n.texture,n.size,a,n.elementsPerTexelStored,6,4,e,t):this.updateDataTexture(n.data,n.texture,n.size,a,n.elementsPerTexelAllocated,n.elementsPerTexelAllocated,2,e,t):r.needsUpdate=!0}if(r){const n=r.data,s=r.texture,o=6,a=0===i?4:2;wn.updateScaleRotationsPaddedData(e,t,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,n);const l=this.renderer?this.renderer.properties.get(s):null;l&&l.__webglTexture?this.updateDataTexture(n,r.texture,r.size,l,4,o,a,e,t):s.needsUpdate=!0}const p=this.splatDataTextures.baseData.sphericalHarmonics;if(p){let n=4;1===a?n=2:2===a&&(n=1);const s=(s,r,i,o,a)=>{const l=this.renderer?this.renderer.properties.get(s):null;l&&l.__webglTexture?this.updateDataTexture(o,s,r,l,i,a,n,e,t):s.needsUpdate=!0},r=o.componentCount,i=o.paddedComponentCount;if(1===o.textureCount){const n=o.data;for(let s=e;s<=t;s++){const e=r*s,t=i*s;for(let s=0;s<r;s++)n[t+s]=p[e+s]}s(o.texture,o.size,o.elementsPerTexel,n,i)}else{const n=o.componentCountPerChannel;for(let a=0;a<3;a++){const l=o.data[a];for(let s=e;s<=t;s++){const e=r*s,t=i*s;if(n>=3){for(let n=0;n<3;n++)l[t+n]=p[e+3*a+n];if(n>=8)for(let n=0;n<5;n++)l[t+3+n]=p[e+9+5*a+n]}}s(o.textures[a],o.size,o.elementsPerTexel,l,i)}}}const u=this.splatDataTextures.sceneIndexes,m=u.data;for(let e=this.lastBuildSplatCount;e<=t;e++)m[e]=this.globalSplatIndexToSceneIndexMap[e];const A=u.texture,f=this.renderer?this.renderer.properties.get(A):null;f&&f.__webglTexture?this.updateDataTexture(m,u.texture,u.size,f,1,1,1,this.lastBuildSplatCount,t):A.needsUpdate=!0}getTargetCovarianceCompressionLevel(){return this.halfPrecisionCovariancesOnGPU?1:0}getTargetSphericalHarmonicsCompressionLevel(){return Math.max(1,this.getMaximumSplatBufferCompressionLevel())}getMaximumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const n=this.getScene(t).splatBuffer;(0===t||n.compressionLevel>e)&&(e=n.compressionLevel)}return e}getMinimumSplatBufferCompressionLevel(){let e;for(let t=0;t<this.scenes.length;t++){const n=this.getScene(t).splatBuffer;(0===t||n.compressionLevel<e)&&(e=n.compressionLevel)}return e}static computeTextureUpdateRegion(e,t,n,s,r){const i=r/s,o=e*i,a=Math.floor(o/n),l=a*n*s,c=t*i,h=Math.floor(c/n);return{dataStart:l,dataEnd:h*n*s+n*s,startRow:a,endRow:h}}updateDataTexture(e,t,n,s,r,i,o,a,l){const c=this.renderer.getContext(),h=wn.computeTextureUpdateRegion(a,l,n.x,r,i),d=h.dataEnd-h.dataStart,p=new e.constructor(e.buffer,h.dataStart*o,d),u=h.endRow-h.startRow+1,m=this.webGLUtils.convert(t.type),A=this.webGLUtils.convert(t.format,t.colorSpace),f=c.getParameter(c.TEXTURE_BINDING_2D);c.bindTexture(c.TEXTURE_2D,s.__webglTexture),c.texSubImage2D(c.TEXTURE_2D,0,0,h.startRow,n.x,u,A,m,p),c.bindTexture(c.TEXTURE_2D,f)}static updatePaddedCompressedCovariancesTextureData(e,t,n,s,r){let i=new DataView(t.buffer),o=n,a=0;for(let t=s;t<=r;t+=2)i.setUint16(2*o,e[t],!0),i.setUint16(2*o+2,e[t+1],!0),o+=2,a++,a>=3&&(o+=2,a=0)}static updateCenterColorsPaddedData(e,t,n,s,r){for(let a=e;a<=t;a++){const e=4*a,t=3*a,l=4*a;r[l]=(i=s)[o=e]+(i[o+1]<<8)+(i[o+2]<<16)+(i[o+3]<<24),r[l+1]=u(n[t]),r[l+2]=u(n[t+1]),r[l+3]=u(n[t+2])}var i,o}static updateScaleRotationsPaddedData(e,t,n,s,r){for(let i=e;i<=t;i++){const e=3*i,t=4*i,o=6*i;r[o]=n[e],r[o+1]=n[e+1],r[o+2]=n[e+2],r[o+3]=s[t],r[o+4]=s[t+1],r[o+5]=s[t+2]}}updateVisibleRegion(t){const n=this.getSplatCount(!0),s=new e.Vector3;if(!t){const t=new e.Vector3;this.scenes.forEach((e=>{t.add(e.splatBuffer.sceneCenter)})),t.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(t),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}for(let e=t?this.lastBuildSplatCount:0;e<n;e++){this.getSplatCenter(e,s,!0);const t=s.sub(this.calculatedSceneCenter).length();t>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=t)}this.maxSplatDistanceFromSceneCenter-this.visibleRegionBufferRadius>1&&(this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter,this.visibleRegionRadius=Math.max(this.visibleRegionBufferRadius-1,0)),this.finalBuild&&(this.visibleRegionRadius=this.visibleRegionBufferRadius=this.maxSplatDistanceFromSceneCenter),this.updateVisibleRegionFadeDistance()}updateVisibleRegionFadeDistance(e=Sn){const t=.012*this.sceneFadeInRateMultiplier,n=.003*this.sceneFadeInRateMultiplier,s=this.finalBuild?t:n,r=e===Sn?s:n;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*r+this.visibleRegionFadeStartRadius;const i=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,o=i||e===Cn?1:0;this.material.uniforms.visibleRegionFadeStartRadius.value=this.visibleRegionFadeStartRadius,this.material.uniforms.visibleRegionRadius.value=this.visibleRegionRadius,this.material.uniforms.firstRenderTime.value=this.firstRenderTime,this.material.uniforms.currentTime.value=performance.now(),this.material.uniforms.fadeInComplete.value=o,this.material.uniformsNeedUpdate=!0,this.visibleRegionChanging=!i}updateRenderIndexes(e,t){const n=this.geometry;n.attributes.splatIndex.set(e),n.attributes.splatIndex.needsUpdate=!0,t>0&&-1===this.firstRenderTime&&(this.firstRenderTime=performance.now()),n.instanceCount=t,n.setDrawRange(0,t)}updateTransforms(){for(let e=0;e<this.scenes.length;e++){this.getScene(e).updateTransform(this.dynamicMode)}}updateUniforms=function(){const t=new e.Vector2;return function(e,n,s,r,i,o){if(this.getSplatCount()>0){if(t.set(e.x*this.devicePixelRatio,e.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(t),this.material.uniforms.basisViewport.value.set(1/t.x,1/t.y),this.material.uniforms.focal.value.set(n,s),this.material.uniforms.orthographicMode.value=r?1:0,this.material.uniforms.orthoZoom.value=i,this.material.uniforms.inverseFocalAdjustment.value=o,this.dynamicMode)for(let e=0;e<this.scenes.length;e++)this.material.uniforms.transforms.value[e].copy(this.getScene(e).transform);if(this.enableOptionalEffects)for(let e=0;e<this.scenes.length;e++)this.material.uniforms.sceneOpacity.value[e]=A(this.getScene(e).opacity,0,1),this.material.uniforms.sceneVisibility.value[e]=this.getScene(e).visible?1:0,this.material.uniformsNeedUpdate=!0;this.material.uniformsNeedUpdate=!0}}}();setSplatScale(e=1){this.splatScale=e,this.material.uniforms.splatScale.value=e,this.material.uniformsNeedUpdate=!0}getSplatScale(){return this.splatScale}setPointCloudModeEnabled(e){this.pointCloudModeEnabled=e,this.material.uniforms.pointCloudModeEnabled.value=e?1:0,this.material.uniformsNeedUpdate=!0}getPointCloudModeEnabled(){return this.pointCloudModeEnabled}getSplatDataTextures(){return this.splatDataTextures}getSplatCount(e=!1){return e?wn.getTotalSplatCountForScenes(this.scenes):this.lastBuildSplatCount}static getTotalSplatCountForScenes(e){let t=0;for(let n of e)n&&n.splatBuffer&&(t+=n.splatBuffer.getSplatCount());return t}static getTotalSplatCountForSplatBuffers(e){let t=0;for(let n of e)t+=n.getSplatCount();return t}getMaxSplatCount(){return wn.getTotalMaxSplatCountForScenes(this.scenes)}static getTotalMaxSplatCountForScenes(e){let t=0;for(let n of e)n&&n.splatBuffer&&(t+=n.splatBuffer.getMaxSplatCount());return t}static getTotalMaxSplatCountForSplatBuffers(e){let t=0;for(let n of e)t+=n.getMaxSplatCount();return t}disposeDistancesComputationGPUResources(){if(!this.renderer)return;const e=this.renderer.getContext();this.distancesTransformFeedback.vao&&(e.deleteVertexArray(this.distancesTransformFeedback.vao),this.distancesTransformFeedback.vao=null),this.distancesTransformFeedback.program&&(e.deleteProgram(this.distancesTransformFeedback.program),e.deleteShader(this.distancesTransformFeedback.vertexShader),e.deleteShader(this.distancesTransformFeedback.fragmentShader),this.distancesTransformFeedback.program=null,this.distancesTransformFeedback.vertexShader=null,this.distancesTransformFeedback.fragmentShader=null),this.disposeDistancesComputationGPUBufferResources(),this.distancesTransformFeedback.id&&(e.deleteTransformFeedback(this.distancesTransformFeedback.id),this.distancesTransformFeedback.id=null)}disposeDistancesComputationGPUBufferResources(){if(!this.renderer)return;const e=this.renderer.getContext();this.distancesTransformFeedback.centersBuffer&&(this.distancesTransformFeedback.centersBuffer=null,e.deleteBuffer(this.distancesTransformFeedback.centersBuffer)),this.distancesTransformFeedback.outDistancesBuffer&&(e.deleteBuffer(this.distancesTransformFeedback.outDistancesBuffer),this.distancesTransformFeedback.outDistancesBuffer=null)}setRenderer(t){if(t!==this.renderer){this.renderer=t;const n=this.renderer.getContext(),s=new fn(n),r=new gn(n,s,{});if(s.init(r),this.webGLUtils=new e.WebGLUtils(n,s,r),this.enableDistancesComputationOnGPU&&this.getSplatCount()>0){this.setupDistancesComputationTransformFeedback();const{centers:e,sceneIndexes:t}=this.getDataForDistancesComputation(0,this.getSplatCount()-1);this.refreshGPUBuffersForDistancesComputation(e,t)}}}setupDistancesComputationTransformFeedback=function(){let e;return function(){const t=this.getMaxSplatCount();if(!this.renderer)return;const n=this.lastRenderer!==this.renderer,s=e!==t;if(!n&&!s)return;n?this.disposeDistancesComputationGPUResources():s&&this.disposeDistancesComputationGPUBufferResources();const r=this.renderer.getContext(),i=(e,t,n)=>{const s=e.createShader(t);if(!s)return console.error("Fatal error: gl could not create a shader object."),null;e.shaderSource(s,n),e.compileShader(s);if(!e.getShaderParameter(s,e.COMPILE_STATUS)){let n="unknown";t===e.VERTEX_SHADER?n="vertex shader":t===e.FRAGMENT_SHADER&&(n="fragement shader");const r=e.getShaderInfoLog(s);return console.error("Failed to compile "+n+" with these errors:"+r),e.deleteShader(s),null}return s};let o;this.integerBasedDistancesComputation?(o="#version 300 es\n in ivec4 center;\n flat out int distance;",this.dynamicMode?o+=`\n in uint sceneIndex;\n uniform ivec4 transforms[${b.MaxScenes}];\n void main(void) {\n ivec4 transform = transforms[sceneIndex];\n distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;\n }\n `:o+="\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "):(o="#version 300 es\n in vec4 center;\n flat out float distance;",this.dynamicMode?o+=`\n in uint sceneIndex;\n uniform mat4 transforms[${b.MaxScenes}];\n void main(void) {\n vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n `:o+="\n uniform vec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n ");const a=r.getParameter(r.VERTEX_ARRAY_BINDING),l=r.getParameter(r.CURRENT_PROGRAM),c=!!l&&r.getProgramParameter(l,r.DELETE_STATUS);if(n&&(this.distancesTransformFeedback.vao=r.createVertexArray()),r.bindVertexArray(this.distancesTransformFeedback.vao),n){const e=r.createProgram(),t=i(r,r.VERTEX_SHADER,o),n=i(r,r.FRAGMENT_SHADER,"#version 300 es\n precision lowp float;\n out vec4 fragColor;\n void main(){}\n ");if(!t||!n)throw new Error("Could not compile shaders for distances computation on GPU.");r.attachShader(e,t),r.attachShader(e,n),r.transformFeedbackVaryings(e,["distance"],r.SEPARATE_ATTRIBS),r.linkProgram(e);if(!r.getProgramParameter(e,r.LINK_STATUS)){const s=r.getProgramInfoLog(e);throw console.error("Fatal error: Failed to link program: "+s),r.deleteProgram(e),r.deleteShader(n),r.deleteShader(t),new Error("Could not link shaders for distances computation on GPU.")}this.distancesTransformFeedback.program=e,this.distancesTransformFeedback.vertexShader=t,this.distancesTransformFeedback.vertexShader=n}if(r.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=r.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let e=0;e<this.scenes.length;e++)this.distancesTransformFeedback.transformsLocs[e]=r.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${e}]`)}else this.distancesTransformFeedback.modelViewProjLoc=r.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(n||s)&&(this.distancesTransformFeedback.centersBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?r.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,r.INT,0,0):r.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,r.FLOAT,!1,0,0),this.dynamicMode&&(this.distancesTransformFeedback.sceneIndexesBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),r.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),r.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,r.UNSIGNED_INT,0,0))),(n||s)&&(this.distancesTransformFeedback.outDistancesBuffer=r.createBuffer()),r.bindBuffer(r.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),r.bufferData(r.ARRAY_BUFFER,4*t,r.STATIC_READ),n&&(this.distancesTransformFeedback.id=r.createTransformFeedback()),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),l&&!0!==c&&r.useProgram(l),a&&r.bindVertexArray(a),this.lastRenderer=this.renderer,e=t}}();updateGPUCentersBufferForDistancesComputation(e,t,n){if(!this.renderer)return;const s=this.renderer.getContext(),r=s.getParameter(s.VERTEX_ARRAY_BINDING);s.bindVertexArray(this.distancesTransformFeedback.vao);const i=this.integerBasedDistancesComputation?Uint32Array:Float32Array,o=16*n;if(s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),e)s.bufferSubData(s.ARRAY_BUFFER,o,t);else{const e=new i(16*this.getMaxSplatCount());e.set(t),s.bufferData(s.ARRAY_BUFFER,e,s.STATIC_DRAW)}s.bindBuffer(s.ARRAY_BUFFER,null),r&&s.bindVertexArray(r)}updateGPUTransformIndexesBufferForDistancesComputation(e,t,n){if(!this.renderer||!this.dynamicMode)return;const s=this.renderer.getContext(),r=s.getParameter(s.VERTEX_ARRAY_BINDING);s.bindVertexArray(this.distancesTransformFeedback.vao);const i=4*n;if(s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)s.bufferSubData(s.ARRAY_BUFFER,i,t);else{const e=new Uint32Array(4*this.getMaxSplatCount());e.set(t),s.bufferData(s.ARRAY_BUFFER,e,s.STATIC_DRAW)}s.bindBuffer(s.ARRAY_BUFFER,null),r&&s.bindVertexArray(r)}getSceneIndexes(e,t){let n;n=new Uint32Array(t-e+1);for(let s=e;s<=t;s++)n[s]=this.globalSplatIndexToSceneIndexMap[s];return n}fillTransformsArray=function(){const e=[];return function(t){e.length!==t.length&&(e.length=t.length);for(let t=0;t<this.scenes.length;t++){const n=this.getScene(t).transform.elements;for(let s=0;s<16;s++)e[16*t+s]=n[s]}t.set(e)}}();computeDistancesOnGPU=function(){const t=new e.Matrix4;return function(e,n){if(!this.renderer)return;const s=this.renderer.getContext(),r=s.getParameter(s.VERTEX_ARRAY_BINDING),i=s.getParameter(s.CURRENT_PROGRAM),o=!!i&&s.getProgramParameter(i,s.DELETE_STATUS);if(s.bindVertexArray(this.distancesTransformFeedback.vao),s.useProgram(this.distancesTransformFeedback.program),s.enable(s.RASTERIZER_DISCARD),this.dynamicMode)for(let n=0;n<this.scenes.length;n++)if(t.copy(this.getScene(n).transform),t.premultiply(e),this.integerBasedDistancesComputation){const e=wn.getIntegerMatrixArray(t),r=[e[2],e[6],e[10],e[14]];s.uniform4i(this.distancesTransformFeedback.transformsLocs[n],r[0],r[1],r[2],r[3])}else s.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[n],!1,t.elements);else if(this.integerBasedDistancesComputation){const t=wn.getIntegerMatrixArray(e),n=[t[2],t[6],t[10]];s.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,n[0],n[1],n[2])}else{const t=[e.elements[2],e.elements[6],e.elements[10]];s.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,t[0],t[1],t[2])}s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),s.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?s.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,s.INT,0,0):s.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,s.FLOAT,!1,0,0),this.dynamicMode&&(s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),s.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),s.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,s.UNSIGNED_INT,0,0)),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),s.beginTransformFeedback(s.POINTS),s.drawArrays(s.POINTS,0,this.getSplatCount()),s.endTransformFeedback(),s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,0,null),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null),s.disable(s.RASTERIZER_DISCARD);const a=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);s.flush();const l=new Promise((e=>{const t=()=>{if(this.disposed)e();else{const r=0,i=0;switch(s.clientWaitSync(a,i,r)){case s.TIMEOUT_EXPIRED:return this.computeDistancesOnGPUSyncTimeout=setTimeout(t),this.computeDistancesOnGPUSyncTimeout;case s.WAIT_FAILED:throw new Error("should never get here");default:this.computeDistancesOnGPUSyncTimeout=null,s.deleteSync(a);const r=s.getParameter(s.VERTEX_ARRAY_BINDING);s.bindVertexArray(this.distancesTransformFeedback.vao),s.bindBuffer(s.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),s.getBufferSubData(s.ARRAY_BUFFER,0,n),s.bindBuffer(s.ARRAY_BUFFER,null),r&&s.bindVertexArray(r),e()}}};this.computeDistancesOnGPUSyncTimeout=setTimeout(t)}));return i&&!0!==o&&s.useProgram(i),r&&s.bindVertexArray(r),l}}();getLocalSplatParameters(e,t,n){null==n&&(n=!this.dynamicMode),t.splatBuffer=this.getSplatBufferForSplat(e),t.localIndex=this.getSplatLocalIndex(e),t.sceneTransform=n?this.getSceneTransformForSplat(e):null}fillSplatDataArrays(t,n,s,r,i,o,a,l=0,c=0,h=1,d,p,u=0,m){const A=new e.Vector3;A.x=void 0,A.y=void 0,this.splatRenderMode===sn?A.z=void 0:A.z=1;const f=new e.Matrix4;let g=0,S=this.scenes.length-1;null!=m&&m>=0&&m<=this.scenes.length&&(g=m,S=m);for(let e=g;e<=S;e++){null==a&&(a=!this.dynamicMode);const m=this.getScene(e),g=m.splatBuffer;let S;if(a&&(this.getSceneTransform(e,f),S=f),t&&g.fillSplatCovarianceArray(t,S,d,p,u,l),n||s){if(!n||!s)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');g.fillSplatScaleRotationArray(n,s,S,d,p,u,c,A)}r&&g.fillSplatCenterArray(r,S,d,p,u),i&&g.fillSplatColorArray(i,m.minimumAlpha,d,p,u),o&&g.fillSphericalHarmonicsArray(o,this.minSphericalHarmonicsDegree,S,d,p,u,h),u+=g.getSplatCount()}}getIntegerCenters(e,t,n=!1){const s=t-e+1,r=new Float32Array(3*s);let i;this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e);let o=n?4:3;i=new Int32Array(s*o);for(let e=0;e<s;e++){for(let t=0;t<3;t++)i[e*o+t]=Math.round(1e3*r[3*e+t]);n&&(i[e*o+3]=1e3)}return i}getFloatCenters(e,t,n=!1){const s=t-e+1,r=new Float32Array(3*s);if(this.fillSplatDataArrays(null,null,null,r,null,null,void 0,void 0,void 0,void 0,e),!n)return r;let i=new Float32Array(4*s);for(let e=0;e<s;e++){for(let t=0;t<3;t++)i[4*e+t]=r[3*e+t];i[4*e+3]=1}return i}getSplatCenter=function(){const e={};return function(t,n,s){this.getLocalSplatParameters(t,e,s),e.splatBuffer.getSplatCenter(e.localIndex,n,e.sceneTransform)}}();getSplatScaleAndRotation=function(){const t={},n=new e.Vector3;return function(e,s,r,i){this.getLocalSplatParameters(e,t,i),n.x=void 0,n.y=void 0,n.z=void 0,this.splatRenderMode===rn&&(n.z=0),t.splatBuffer.getSplatScaleAndRotation(t.localIndex,s,r,t.sceneTransform,n)}}();getSplatColor=function(){const e={};return function(t,n){this.getLocalSplatParameters(t,e),e.splatBuffer.getSplatColor(e.localIndex,n)}}();getSceneTransform(e,t){const n=this.getScene(e);n.updateTransform(this.dynamicMode),t.copy(n.transform)}getScene(e){if(e<0||e>=this.scenes.length)throw new Error("SplatMesh::getScene() -> Invalid scene index.");return this.scenes[e]}getSceneCount(){return this.scenes.length}getSplatBufferForSplat(e){return this.getScene(this.globalSplatIndexToSceneIndexMap[e]).splatBuffer}getSceneIndexForSplat(e){return this.globalSplatIndexToSceneIndexMap[e]}getSceneTransformForSplat(e){return this.getScene(this.globalSplatIndexToSceneIndexMap[e]).transform}getSplatLocalIndex(e){return this.globalSplatIndexToLocalSplatIndexMap[e]}static getIntegerMatrixArray(e){const t=e.elements,n=[];for(let e=0;e<16;e++)n[e]=Math.round(1e3*t[e]);return n}computeBoundingBox(t=!1,n){let s=this.getSplatCount();if(null!=n){if(n<0||n>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");s=this.scenes[n].splatBuffer.getSplatCount()}const r=new Float32Array(3*s);this.fillSplatDataArrays(null,null,null,r,null,null,t,void 0,void 0,void 0,void 0,n);const i=new e.Vector3,o=new e.Vector3;for(let e=0;e<s;e++){const t=3*e,n=r[t],s=r[t+1],a=r[t+2];(0===e||n<i.x)&&(i.x=n),(0===e||s<i.y)&&(i.y=s),(0===e||a<i.z)&&(i.z=a),(0===e||n>o.x)&&(o.x=n),(0===e||s>o.y)&&(o.y=s),(0===e||a>o.z)&&(o.z=a)}return new e.Box3(i,o)}}var bn="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";function Dn(e){let t,n,s,r,i,o,a,l,c,h,d,p,u,m,A,f,g,S,C,y;e.onmessage=x=>{if(x.data.centers)centers=x.data.centers,sceneIndexes=x.data.sceneIndexes,r?new Int32Array(n,m+x.data.range.from*y.BytesPerInt*4,4*x.data.range.count).set(new Int32Array(centers)):new Float32Array(n,m+x.data.range.from*y.BytesPerFloat*4,4*x.data.range.count).set(new Float32Array(centers)),i&&new Uint32Array(n,c+4*x.data.range.from,x.data.range.count).set(new Uint32Array(sceneIndexes)),C=x.data.range.from+x.data.range.count;else if(x.data.sort){const v=Math.min(x.data.sort.splatRenderCount||0,C),I=Math.min(x.data.sort.splatSortCount||0,C),B=x.data.sort.usePrecomputedDistances;let w,b,D;s||(w=x.data.sort.indexesToSort,D=x.data.sort.transforms,B&&(b=x.data.sort.precomputedDistances)),function(C,x,v,I,B,w,b){const D=performance.now();if(!s&&(new Uint32Array(n,a,B.byteLength/y.BytesPerInt).set(B),new Float32Array(n,h,b.byteLength/y.BytesPerFloat).set(b),I)){let e;e=r?new Int32Array(n,d,w.byteLength/y.BytesPerInt):new Float32Array(n,d,w.byteLength/y.BytesPerFloat),e.set(w)}f||(f=new Uint32Array(S)),new Float32Array(n,A,16).set(v),new Uint32Array(n,u,S).set(f),t.exports.sortIndexes(a,m,d,p,u,A,l,c,h,S,C,x,o,I,r,i);const T={sortDone:!0,splatSortCount:C,splatRenderCount:x,sortTime:0};if(!s){const e=new Uint32Array(n,l,x);(!g||g.length<x)&&(g=new Uint32Array(x)),g.set(e),T.sortedIndexes=g}const E=performance.now();T.sortTime=E-D,e.postMessage(T)}(I,v,x.data.sort.modelViewProj,B,w,b,D)}else if(x.data.init){y=x.data.init.Constants,o=x.data.init.splatCount,s=x.data.init.useSharedMemory,r=x.data.init.integerBasedSort,i=x.data.init.dynamicMode,S=x.data.init.distanceMapRange,C=0;const f=r?4*y.BytesPerInt:4*y.BytesPerFloat,g=new Uint8Array(x.data.init.sorterWasmBytes),v=16*y.BytesPerFloat,I=o*y.BytesPerInt,B=o*f,w=v,b=r?o*y.BytesPerInt:o*y.BytesPerFloat,D=o*y.BytesPerInt,T=o*y.BytesPerInt,E=r?S*y.BytesPerInt*2:S*y.BytesPerFloat*2,M=i?o*y.BytesPerInt:0,F=i?y.MaxScenes*v:0,R=32*y.MemoryPageSize,P=I+B+w+b+D+E+T+M+F+R,H=Math.floor(P/y.MemoryPageSize)+1,k={module:{},env:{memory:new WebAssembly.Memory({initial:H,maximum:H,shared:!0})}};WebAssembly.compile(g).then((e=>WebAssembly.instantiate(e,k))).then((r=>{t=r,a=0,m=a+I,A=m+B,d=A+w,p=d+b,u=p+D,l=u+E,c=l+T,h=c+M,n=k.env.memory.buffer,s?e.postMessage({sortSetupPhase1Complete:!0,indexesToSortBuffer:n,indexesToSortOffset:a,sortedIndexesBuffer:n,sortedIndexesOffset:l,precomputedDistancesBuffer:n,precomputedDistancesOffset:d,transformsBuffer:n,transformsOffset:h}):e.postMessage({sortSetupPhase1Complete:!0})}))}}}const Tn=0,En=1,Mn=2;class Fn{static createButton(e,t={}){const n=document.createElement("button");function s(){n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(e){e.style.position="absolute",e.style.bottom="20px",e.style.padding="12px 6px",e.style.border="1px solid #fff",e.style.borderRadius="4px",e.style.background="rgba(0,0,0,0.1)",e.style.color="#fff",e.style.font="normal 13px sans-serif",e.style.textAlign="center",e.style.opacity="0.5",e.style.outline="none",e.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",r(n),navigator.xr.isSessionSupported("immersive-vr").then((function(r){r?function(){let s=null;async function r(t){t.addEventListener("end",i),await e.xr.setSession(t),n.textContent="EXIT VR",s=t}function i(){s.removeEventListener("end",i),n.textContent="ENTER VR",s=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR";const o={...t,optionalFeatures:["local-floor","bounded-floor","layers",...t.optionalFeatures||[]]};n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){null===s?navigator.xr.requestSession("immersive-vr",o).then(r):(s.end(),void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-vr",o).then(r).catch((e=>{console.warn(e)})))},void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-vr",o).then(r).catch((e=>{console.warn(e)}))}():(s(),n.textContent="VR NOT SUPPORTED"),r&&Fn.xrSessionIsGranted&&n.click()})).catch((function(e){s(),console.warn("Exception when trying to call xr.isSessionSupported",e),n.textContent="VR NOT ALLOWED"})),n;{const e=document.createElement("a");return!1===window.isSecureContext?(e.href=document.location.href.replace(/^http:/,"https:"),e.innerHTML="WEBXR NEEDS HTTPS"):(e.href="https://immersiveweb.dev/",e.innerHTML="WEBXR NOT AVAILABLE"),e.style.left="calc(50% - 90px)",e.style.width="180px",e.style.textDecoration="none",r(e),e}}static registerSessionGrantedListener(){if("undefined"!=typeof navigator&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",(()=>{Fn.xrSessionIsGranted=!0}))}}}Fn.xrSessionIsGranted=!1,Fn.registerSessionGrantedListener();class Rn{static createButton(e,t={}){const n=document.createElement("button");function s(){n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function r(e){e.style.position="absolute",e.style.bottom="20px",e.style.padding="12px 6px",e.style.border="1px solid #fff",e.style.borderRadius="4px",e.style.background="rgba(0,0,0,0.1)",e.style.color="#fff",e.style.font="normal 13px sans-serif",e.style.textAlign="center",e.style.opacity="0.5",e.style.outline="none",e.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",r(n),navigator.xr.isSessionSupported("immersive-ar").then((function(r){r?function(){if(void 0===t.domOverlay){const e=document.createElement("div");e.style.display="none",document.body.appendChild(e);const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("width",38),n.setAttribute("height",38),n.style.position="absolute",n.style.right="20px",n.style.top="20px",n.addEventListener("click",(function(){s.end()})),e.appendChild(n);const r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),r.setAttribute("stroke","#fff"),r.setAttribute("stroke-width",2),n.appendChild(r),void 0===t.optionalFeatures&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:e}}let s=null;async function r(r){r.addEventListener("end",i),e.xr.setReferenceSpaceType("local"),await e.xr.setSession(r),n.textContent="STOP AR",t.domOverlay.root.style.display="",s=r}function i(){s.removeEventListener("end",i),n.textContent="START AR",t.domOverlay.root.style.display="none",s=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){null===s?navigator.xr.requestSession("immersive-ar",t).then(r):(s.end(),void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-ar",t).then(r).catch((e=>{console.warn(e)})))},void 0!==navigator.xr.offerSession&&navigator.xr.offerSession("immersive-ar",t).then(r).catch((e=>{console.warn(e)}))}():(s(),n.textContent="AR NOT SUPPORTED")})).catch((function(e){s(),console.warn("Exception when trying to call xr.isSessionSupported",e),n.textContent="AR NOT ALLOWED"})),n;{const e=document.createElement("a");return!1===window.isSecureContext?(e.href=document.location.href.replace(/^http:/,"https:"),e.innerHTML="WEBXR NEEDS HTTPS"):(e.href="https://immersiveweb.dev/",e.innerHTML="WEBXR NOT AVAILABLE"),e.style.left="calc(50% - 90px)",e.style.width="180px",e.style.textDecoration="none",r(e),e}}}const Pn=0,Hn=2;class kn{constructor(t={}){if(t.cameraUp||(t.cameraUp=[0,1,0]),this.cameraUp=(new e.Vector3).fromArray(t.cameraUp),t.initialCameraPosition||(t.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new e.Vector3).fromArray(t.initialCameraPosition),t.initialCameraLookAt||(t.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new e.Vector3).fromArray(t.initialCameraLookAt),this.dropInMode=t.dropInMode||!1,void 0!==t.selfDrivenMode&&null!==t.selfDrivenMode||(t.selfDrivenMode=!0),this.selfDrivenMode=t.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),void 0===t.useBuiltInControls&&(t.useBuiltInControls=!0),this.useBuiltInControls=t.useBuiltInControls,this.rootElement=t.rootElement,this.ignoreDevicePixelRatio=t.ignoreDevicePixelRatio||!1,this.devicePixelRatio=this.ignoreDevicePixelRatio?1:window.devicePixelRatio||1,this.halfPrecisionCovariancesOnGPU=t.halfPrecisionCovariancesOnGPU||!1,this.threeScene=t.threeScene,this.renderer=t.renderer,this.camera=t.camera,this.gpuAcceleratedSort=t.gpuAcceleratedSort||!1,void 0!==t.integerBasedSort&&null!==t.integerBasedSort||(t.integerBasedSort=!0),this.integerBasedSort=t.integerBasedSort,void 0!==t.sharedMemoryForWorkers&&null!==t.sharedMemoryForWorkers||(t.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=t.sharedMemoryForWorkers,this.dynamicScene=!!t.dynamicScene,this.antialiased=t.antialiased||!1,this.kernel2DSize=void 0===t.kernel2DSize?.3:t.kernel2DSize,this.webXRMode=t.webXRMode||Tn,this.webXRMode!==Tn&&(this.gpuAcceleratedSort=!1),this.webXRActive=!1,this.webXRSessionInit=t.webXRSessionInit||{},this.renderMode=t.renderMode||Pn,this.sceneRevealMode=t.sceneRevealMode||Sn,this.focalAdjustment=t.focalAdjustment||1,this.maxScreenSpaceSplatSize=t.maxScreenSpaceSplatSize||1024,this.logLevel=t.logLevel||yn,this.sphericalHarmonicsDegree=t.sphericalHarmonicsDegree||0,this.enableOptionalEffects=t.enableOptionalEffects||!1,void 0!==t.enableSIMDInSort&&null!==t.enableSIMDInSort||(t.enableSIMDInSort=!0),this.enableSIMDInSort=t.enableSIMDInSort,void 0!==t.inMemoryCompressionLevel&&null!==t.inMemoryCompressionLevel||(t.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=t.inMemoryCompressionLevel,void 0!==t.optimizeSplatData&&null!==t.optimizeSplatData||(t.optimizeSplatData=!0),this.optimizeSplatData=t.optimizeSplatData,void 0!==t.freeIntermediateSplatData&&null!==t.freeIntermediateSplatData||(t.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=t.freeIntermediateSplatData,I()){const e=B();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==t.splatRenderMode&&null!==t.splatRenderMode||(t.splatRenderMode=sn),this.splatRenderMode=t.splatRenderMode,this.sceneFadeInRateMultiplier=t.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=t.splatSortDistanceMapPrecision||b.DefaultSplatSortDistanceMapPrecision;const n=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=A(this.splatSortDistanceMapPrecision,10,n),this.onSplatMeshChangedCallback=null,this.createSplatMesh(),this.controls=null,this.perspectiveControls=null,this.orthographicControls=null,this.orthographicCamera=null,this.perspectiveCamera=null,this.showMeshCursor=!1,this.showControlPlane=!1,this.showInfo=!1,this.sceneHelper=null,this.sortWorker=null,this.sortRunning=!1,this.splatRenderCount=0,this.splatSortCount=0,this.lastSplatSortCount=0,this.sortWorkerIndexesToSort=null,this.sortWorkerSortedIndexes=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.preSortMessages=[],this.runAfterNextSort=[],this.selfDrivenModeRunning=!1,this.splatRenderReady=!1,this.raycaster=new on,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new e.Vector3,this.nextCameraTarget=new e.Vector3,this.mousePosition=new e.Vector2,this.mouseDownPosition=new e.Vector2,this.mouseDownTime=null,this.resizeObserver=null,this.mouseMoveListener=null,this.mouseDownListener=null,this.mouseUpListener=null,this.keyDownListener=null,this.sortPromise=null,this.sortPromiseResolver=null,this.splatSceneDownloadPromises={},this.splatSceneDownloadAndBuildPromise=null,this.splatSceneRemovalPromise=null,this.loadingSpinner=new qt(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Wt(this.rootElement||document.body),this.loadingProgressBar.hide(),this.infoPanel=new jt(this.rootElement||document.body),this.infoPanel.hide(),this.usingExternalCamera=!(!this.dropInMode&&!this.camera),this.usingExternalRenderer=!(!this.dropInMode&&!this.renderer),this.initialized=!1,this.disposing=!1,this.disposed=!1,this.disposePromise=null,this.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new wn(this.splatRenderMode,this.dynamicScene,this.enableOptionalEffects,this.halfPrecisionCovariancesOnGPU,this.devicePixelRatio,this.gpuAcceleratedSort,this.integerBasedSort,this.antialiased,this.maxScreenSpaceSplatSize,this.logLevel,this.sphericalHarmonicsDegree,this.sceneFadeInRateMultiplier,this.kernel2DSize),this.splatMesh.frustumCulled=!1,this.onSplatMeshChangedCallback&&this.onSplatMeshChangedCallback()}init(){this.initialized||(this.rootElement||(this.usingExternalRenderer?this.rootElement=this.renderer.domElement||document.body:(this.rootElement=document.createElement("div"),this.rootElement.style.width="100%",this.rootElement.style.height="100%",this.rootElement.style.position="absolute",document.body.appendChild(this.rootElement))),this.setupCamera(),this.setupRenderer(),this.setupWebXR(this.webXRSessionInit),this.setupControls(),this.setupEventHandlers(),this.threeScene=this.threeScene||new e.Scene,this.sceneHelper=new Jt(this.threeScene),this.sceneHelper.setupMeshCursor(),this.sceneHelper.setupFocusMarker(),this.sceneHelper.setupControlPlane(),this.loadingProgressBar.setContainer(this.rootElement),this.loadingSpinner.setContainer(this.rootElement),this.infoPanel.setContainer(this.rootElement),this.initialized=!0)}setupCamera(){if(!this.usingExternalCamera){const t=new e.Vector2;this.getRenderDimensions(t),this.perspectiveCamera=new e.PerspectiveCamera(50,t.x/t.y,.1,1e3),this.orthographicCamera=new e.OrthographicCamera(t.x/-2,t.x/2,t.y/2,t.y/-2,.1,1e3),this.camera=this.startInOrthographicMode?this.orthographicCamera:this.perspectiveCamera,this.camera.position.copy(this.initialCameraPosition),this.camera.up.copy(this.cameraUp).normalize(),this.camera.lookAt(this.initialCameraLookAt)}}setupRenderer(){if(!this.usingExternalRenderer){const t=new e.Vector2;this.getRenderDimensions(t),this.renderer=new e.WebGLRenderer({antialias:!1,precision:"highp"}),this.renderer.setPixelRatio(this.devicePixelRatio),this.renderer.autoClear=!0,this.renderer.setClearColor(new e.Color(0),0),this.renderer.setSize(t.x,t.y),this.resizeObserver=new ResizeObserver((()=>{this.getRenderDimensions(t),this.renderer.setSize(t.x,t.y),this.forceRenderNextFrame()})),this.resizeObserver.observe(this.rootElement),this.rootElement.appendChild(this.renderer.domElement)}}setupWebXR(e){this.webXRMode&&(this.webXRMode===En?this.rootElement.appendChild(Fn.createButton(this.renderer,e)):this.webXRMode===Mn&&this.rootElement.appendChild(Rn.createButton(this.renderer,e)),this.renderer.xr.addEventListener("sessionstart",(e=>{this.webXRActive=!0})),this.renderer.xr.addEventListener("sessionend",(e=>{this.webXRActive=!1})),this.renderer.xr.enabled=!0,this.camera.position.copy(this.initialCameraPosition),this.camera.up.copy(this.cameraUp).normalize(),this.camera.lookAt(this.initialCameraLookAt))}setupControls(){if(this.useBuiltInControls&&this.webXRMode===Tn){this.usingExternalCamera?this.camera.isOrthographicCamera?this.orthographicControls=new Kt(this.camera,this.renderer.domElement):this.perspectiveControls=new Kt(this.camera,this.renderer.domElement):(this.perspectiveControls=new Kt(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new Kt(this.orthographicCamera,this.renderer.domElement));for(let e of[this.orthographicControls,this.perspectiveControls])e&&(e.listenToKeyEvents(window),e.rotateSpeed=.5,e.maxPolarAngle=.75*Math.PI,e.minPolarAngle=.1,e.enableDamping=!0,e.dampingFactor=.05,e.target.copy(this.initialCameraLookAt),e.update());this.controls=this.camera.isOrthographicCamera?this.orthographicControls:this.perspectiveControls,this.controls.update()}}setupEventHandlers(){this.useBuiltInControls&&this.webXRMode===Tn&&(this.mouseMoveListener=this.onMouseMove.bind(this),this.renderer.domElement.addEventListener("pointermove",this.mouseMoveListener,!1),this.mouseDownListener=this.onMouseDown.bind(this),this.renderer.domElement.addEventListener("pointerdown",this.mouseDownListener,!1),this.mouseUpListener=this.onMouseUp.bind(this),this.renderer.domElement.addEventListener("pointerup",this.mouseUpListener,!1),this.keyDownListener=this.onKeyDown.bind(this),window.addEventListener("keydown",this.keyDownListener,!1))}removeEventHandlers(){this.useBuiltInControls&&(this.renderer.domElement.removeEventListener("pointermove",this.mouseMoveListener),this.mouseMoveListener=null,this.renderer.domElement.removeEventListener("pointerdown",this.mouseDownListener),this.mouseDownListener=null,this.renderer.domElement.removeEventListener("pointerup",this.mouseUpListener),this.mouseUpListener=null,window.removeEventListener("keydown",this.keyDownListener),this.keyDownListener=null)}setRenderMode(e){this.renderMode=e}setActiveSphericalHarmonicsDegrees(e){this.splatMesh.material.uniforms.sphericalHarmonicsDegree.value=e,this.splatMesh.material.uniformsNeedUpdate=!0}onSplatMeshChanged(e){this.onSplatMeshChangedCallback=e}onKeyDown=function(){const t=new e.Vector3,n=new e.Matrix4,s=new e.Matrix4;return function(e){switch(t.set(0,0,-1),t.transformDirection(this.camera.matrixWorld),n.makeRotationAxis(t,Math.PI/128),s.makeRotationAxis(t,-Math.PI/128),e.code){case"KeyG":this.focalAdjustment+=.02,this.forceRenderNextFrame();break;case"KeyF":this.focalAdjustment-=.02,this.forceRenderNextFrame();break;case"ArrowLeft":this.camera.up.transformDirection(n);break;case"ArrowRight":this.camera.up.transformDirection(s);break;case"KeyC":this.showMeshCursor=!this.showMeshCursor;break;case"KeyU":this.showControlPlane=!this.showControlPlane;break;case"KeyI":this.showInfo=!this.showInfo,this.showInfo?this.infoPanel.show():this.infoPanel.hide();break;case"KeyO":this.usingExternalCamera||this.setOrthographicMode(!this.camera.isOrthographicCamera);break;case"KeyP":this.usingExternalCamera||this.splatMesh.setPointCloudModeEnabled(!this.splatMesh.getPointCloudModeEnabled());break;case"Equal":this.usingExternalCamera||this.splatMesh.setSplatScale(this.splatMesh.getSplatScale()+.05);break;case"Minus":this.usingExternalCamera||this.splatMesh.setSplatScale(Math.max(this.splatMesh.getSplatScale()-.05,0))}}}();onMouseMove(e){this.mousePosition.set(e.offsetX,e.offsetY)}onMouseDown(){this.mouseDownPosition.copy(this.mousePosition),this.mouseDownTime=f()}onMouseUp=function(){const t=new e.Vector2;return function(e){t.copy(this.mousePosition).sub(this.mouseDownPosition);f()-this.mouseDownTime<.5&&t.length()<2&&this.onMouseClick(e)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkForFocalPointChange=function(){const t=new e.Vector2,n=new e.Vector3,s=[];return function(){if(!this.transitioningCameraTarget&&(this.getRenderDimensions(t),s.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,t),this.raycaster.intersectSplatMesh(this.splatMesh,s),s.length>0)){const e=s[0].origin;n.copy(e).sub(this.camera.position),n.length()>.75&&(this.previousCameraTarget.copy(this.controls.target),this.nextCameraTarget.copy(e),this.transitioningCameraTarget=!0,this.transitioningCameraTargetStartTime=f())}}}();getRenderDimensions(e){this.rootElement?(e.x=this.rootElement.offsetWidth,e.y=this.rootElement.offsetHeight):this.renderer.getSize(e)}setOrthographicMode(e){if(e===this.camera.isOrthographicCamera)return;const t=this.camera,n=e?this.orthographicCamera:this.perspectiveCamera;if(n.position.copy(t.position),n.up.copy(t.up),n.rotation.copy(t.rotation),n.quaternion.copy(t.quaternion),n.matrix.copy(t.matrix),this.camera=n,this.controls){const s=e=>{e.saveState(),e.reset()},r=this.controls,i=e?this.orthographicControls:this.perspectiveControls;s(i),s(r),i.target.copy(r.target),e?kn.setCameraZoomFromPosition(n,t,r):kn.setCameraPositionFromZoom(n,t,i),this.controls=i,this.camera.lookAt(this.controls.target)}}static setCameraPositionFromZoom=function(){const t=new e.Vector3;return function(e,n,s){const r=1/(.001*n.zoom);t.copy(s.target).sub(e.position).normalize().multiplyScalar(r).negate(),e.position.copy(s.target).add(t)}}();static setCameraZoomFromPosition=function(){const t=new e.Vector3;return function(e,n,s){const r=t.copy(s.target).sub(n.position).length();e.zoom=1/(.001*r)}}();updateSplatMesh=function(){const t=new e.Vector2;return function(){if(!this.splatMesh)return;if(this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(t);const e=.5*this.camera.projectionMatrix.elements[0]*this.devicePixelRatio*t.x,n=.5*this.camera.projectionMatrix.elements[5]*this.devicePixelRatio*t.y,s=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,r=this.focalAdjustment*s,i=1/r;this.adjustForWebXRStereo(t),this.splatMesh.updateUniforms(t,e*r,n*r,this.camera.isOrthographicCamera,this.camera.zoom||1,i)}}}();adjustForWebXRStereo(e){if(this.camera&&this.webXRActive){const t=this.renderer.xr.getCamera().projectionMatrix.elements[0],n=this.camera.projectionMatrix.elements[0];e.x*=n/t}}isLoadingOrUnloading(){return Object.keys(this.splatSceneDownloadPromises).length>0||null!==this.splatSceneDownloadAndBuildPromise||null!==this.splatSceneRemovalPromise}isDisposingOrDisposed(){return this.disposing||this.disposed}addSplatSceneDownloadPromise(e){this.splatSceneDownloadPromises[e.id]=e}removeSplatSceneDownloadPromise(e){delete this.splatSceneDownloadPromises[e.id]}setSplatSceneDownloadAndBuildPromise(e){this.splatSceneDownloadAndBuildPromise=e}clearSplatSceneDownloadAndBuildPromise(){this.splatSceneDownloadAndBuildPromise=null}addSplatScene(e,t={}){if(this.isLoadingOrUnloading())throw new Error("Cannot add splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot add splat scene after dispose() is called.");t.progressiveLoad&&this.splatMesh.scenes&&this.splatMesh.scenes.length>0&&(console.log('addSplatScene(): "progressiveLoad" option ignore because there are multiple splat scenes'),t.progressiveLoad=!1);const n=void 0!==t.format&&null!==t.format?t.format:Ut(e),s=kn.isProgressivelyLoadable(n)&&t.progressiveLoad,r=void 0===t.showLoadingUI||null===t.showLoadingUI||t.showLoadingUI;let i=null;r&&(this.loadingSpinner.removeAllTasks(),i=this.loadingSpinner.addTask("Downloading..."));const o=(e,t,n)=>{if(r)if(n===lt)if(100==e)this.loadingSpinner.setMessageForTask(i,"Download complete!");else if(s)this.loadingSpinner.setMessageForTask(i,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(i,`Downloading${e}`)}else n===ct&&this.loadingSpinner.setMessageForTask(i,"Processing splats...")};let a=!1,l=0;const c=(e,t)=>{r&&((e&&s||t&&!s)&&(this.loadingSpinner.removeTask(i),t||a||this.loadingProgressBar.show()),s&&(t?(a=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(l)))};return(s?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(e,n,t.splatAlphaRemovalThreshold,((e,n,i)=>{!s&&t.onProgress&&t.onProgress(0,"0%",ct);const o={rotation:t.rotation||t.orientation,position:t.position,scale:t.scale,splatAlphaRemovalThreshold:t.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[o],i,n&&r,r,s,s).then((()=>{!s&&t.onProgress&&t.onProgress(100,"100%",ct),c(n,i)}))}).bind(this),((e,n,s)=>{l=e,o(e,n,s),t.onProgress&&t.onProgress(e,n,s)}),(()=>{this.loadingProgressBar.hide(),this.loadingSpinner.removeAllTasks()}).bind(this),t.headers)}downloadAndBuildSingleSplatSceneStandardLoad(e,t,n,s,r,i,o){const a=this.downloadSplatSceneToSplatBuffer(e,n,r,!1,void 0,t,o),l=x(a.abortHandler);return a.then((e=>(this.removeSplatSceneDownloadPromise(a),s(e,!0,!0).then((()=>{l.resolve(),this.clearSplatSceneDownloadAndBuildPromise()}))))).catch((t=>{i&&i(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(a),l.reject(this.updateError(t,`Viewer::addSplatScene -> Could not load file ${e}`))})),this.addSplatSceneDownloadPromise(a),this.setSplatSceneDownloadAndBuildPromise(l.promise),l.promise}downloadAndBuildSingleSplatSceneProgressiveLoad(e,t,n,s,r,i,o){let a=0,l=!1;const c=[],h=()=>{if(c.length>0&&!l&&!this.isDisposingOrDisposed()){l=!0;const e=c.shift();s(e.splatBuffer,e.firstBuild,e.finalBuild).then((()=>{l=!1,e.firstBuild?p.resolve():e.finalBuild&&(u.resolve(),this.clearSplatSceneDownloadAndBuildPromise()),c.length>0&&S((()=>h()))}))}},d=this.downloadSplatSceneToSplatBuffer(e,n,r,!0,((e,t)=>{this.isDisposingOrDisposed()||(t||0===c.length||e.getSplatCount()>c[0].splatBuffer.getSplatCount())&&(c.push({splatBuffer:e,firstBuild:0===a,finalBuild:t}),a++,h())}),t,o),p=x(d.abortHandler),u=x();return this.addSplatSceneDownloadPromise(d),this.setSplatSceneDownloadAndBuildPromise(u.promise),d.then((()=>{this.removeSplatSceneDownloadPromise(d)})).catch((e=>{this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(d);const t=this.updateError(e,"Viewer::addSplatScene -> Could not load one or more scenes");p.reject(t),i&&i(t)})),p.promise}addSplatScenes(e,t=!0,n=void 0){if(this.isLoadingOrUnloading())throw new Error("Cannot add splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot add splat scene after dispose() is called.");const s=e.length,r=[];let i;t&&(this.loadingSpinner.removeAllTasks(),i=this.loadingSpinner.addTask("Downloading..."));const o=(e,o,a,l)=>{r[e]=o;let c=0;for(let e=0;e<s;e++)c+=r[e]||0;c/=s,a=`${c.toFixed(2)}%`,t&&l===lt&&this.loadingSpinner.setMessageForTask(i,100==c?"Download complete!":`Downloading: ${a}`),n&&n(c,a,l)},a=[],l=[];for(let t=0;t<e.length;t++){const n=e[t],s=void 0!==n.format&&null!==n.format?n.format:Ut(n.path),r=this.downloadSplatSceneToSplatBuffer(n.path,n.splatAlphaRemovalThreshold,o.bind(this,t),!1,void 0,s,n.headers);a.push(r),l.push(r.promise)}const c=new d(((s,r)=>{Promise.all(l).then((r=>{t&&this.loadingSpinner.removeTask(i),n&&n(0,"0%",ct),this.addSplatBuffers(r,e,!0,t,t,!1,!1).then((()=>{n&&n(100,"100%",ct),this.clearSplatSceneDownloadAndBuildPromise(),s()}))})).catch((e=>{t&&this.loadingSpinner.removeTask(i),this.clearSplatSceneDownloadAndBuildPromise(),r(this.updateError(e,"Viewer::addSplatScenes -> Could not load one or more splat scenes."))})).finally((()=>{this.removeSplatSceneDownloadPromise(c)}))}),(e=>{for(let t of a)t.abort(e)}));return this.addSplatSceneDownloadPromise(c),this.setSplatSceneDownloadAndBuildPromise(c),c}downloadSplatSceneToSplatBuffer(e,t=1,n=void 0,s=!1,r=void 0,i,o){try{if(i===Ht||i===kt||i===Lt){const a=!s&&this.optimizeSplatData;if(i===Ht)return Rt.loadFromURL(e,n,s,r,t,this.inMemoryCompressionLevel,a,o);if(i===kt)return Pt.loadFromURL(e,n,s,r,o);if(i===Lt)return gt.loadFromURL(e,n,s,r,t,this.inMemoryCompressionLevel,a,this.sphericalHarmonicsDegree,o)}else if(i===Ot)return Et.loadFromURL(e,n,t,this.inMemoryCompressionLevel,this.optimizeSplatData,this.sphericalHarmonicsDegree,o)}catch(e){throw this.updateError(e,null)}throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${e}`)}static isProgressivelyLoadable(e){return e===Ht||e===kt||e===Lt}addSplatBuffers=function(){return function(e,t=[],n=!0,s=!0,r=!0,i=!1,o=!1,a=!0){if(this.isDisposingOrDisposed())return Promise.resolve();let l=null;const c=()=>{null!==l&&(this.loadingSpinner.removeTask(l),l=null)};return this.splatRenderReady=!1,new Promise((h=>{s&&(l=this.loadingSpinner.addTask("Processing splats...")),S((()=>{if(this.isDisposingOrDisposed())h();else{const s=this.addSplatBuffersToMesh(e,t,n,r,i,a),l=this.splatMesh.getMaxSplatCount();this.sortWorker&&this.sortWorker.maxSplatCount!==l&&this.disposeSortWorker(),this.gpuAcceleratedSort||this.preSortMessages.push({centers:s.centers.buffer,sceneIndexes:s.sceneIndexes.buffer,range:{from:s.from,to:s.to,count:s.count}});(!this.sortWorker&&l>0?this.setupSortWorker(this.splatMesh):Promise.resolve()).then((()=>{this.isDisposingOrDisposed()||this.runSplatSort(!0,!0).then((e=>{this.sortWorker&&e?(o?this.splatRenderReady=!0:this.runAfterNextSort.push((()=>{this.splatRenderReady=!0})),this.runAfterNextSort.push((()=>{c(),h()}))):(this.splatRenderReady=!0,c(),h())}))}))}}),!0)}))}}();addSplatBuffersToMesh=function(){let e;return function(t,n,s=!0,r=!1,i=!1,o=!0){if(this.isDisposingOrDisposed())return;let a=[],l=[];i||(a=this.splatMesh.scenes.map((e=>e.splatBuffer))||[],l=this.splatMesh.sceneOptions?this.splatMesh.sceneOptions.map((e=>e)):[]),a.push(...t),l.push(...n),this.renderer&&this.splatMesh.setRenderer(this.renderer);const c=this.splatMesh.build(a,l,!0,s,(t=>{if(this.isDisposingOrDisposed())return;const n=this.splatMesh.getSplatCount();r&&n>=15e5&&(t||e||(this.loadingSpinner.setMinimized(!0,!0),e=this.loadingSpinner.addTask("Optimizing data structures...")))}),(t=>{this.isDisposingOrDisposed()||t&&e&&(this.loadingSpinner.removeTask(e),e=null)}),o);return s&&this.freeIntermediateSplatData&&this.splatMesh.freeIntermediateSplatData(),c}}();setupSortWorker(e){if(!this.isDisposingOrDisposed())return new Promise((t=>{const n=this.integerBasedSort?Int32Array:Float32Array,s=e.getSplatCount(),r=e.getMaxSplatCount();this.sortWorker=function(e,t,n,s,r,i=b.DefaultSplatSortDistanceMapPrecision){const o=new Worker(URL.createObjectURL(new Blob(["(",Dn.toString(),")(self)"],{type:"application/javascript"})));let a="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";const l=I()?B():null;n||t?n?t||l&&l.major<=16&&l.minor<4&&(a="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"):a=bn:(a=bn,l&&l.major<=16&&l.minor<4&&(a="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"));const c=atob(a),h=new Uint8Array(c.length);for(let e=0;e<c.length;e++)h[e]=c.charCodeAt(e);return o.postMessage({init:{sorterWasmBytes:h.buffer,splatCount:e,useSharedMemory:t,integerBasedSort:s,dynamicMode:r,distanceMapRange:1<<i,Constants:{BytesPerFloat:b.BytesPerFloat,BytesPerInt:b.BytesPerInt,MemoryPageSize:b.MemoryPageSize,MaxScenes:b.MaxScenes}}}),o}(r,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),this.sortWorker.onmessage=e=>{if(e.data.sortDone){if(this.sortRunning=!1,this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,e.data.splatRenderCount);else{const t=new Uint32Array(e.data.sortedIndexes.buffer,0,e.data.splatRenderCount);this.splatMesh.updateRenderIndexes(t,e.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=e.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach((e=>{e()})),this.runAfterNextSort.length=0)}else if(e.data.sortCanceled)this.sortRunning=!1;else if(e.data.sortSetupPhase1Complete){this.logLevel>=xn&&console.log("Sorting web worker WASM setup complete."),this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(e.data.sortedIndexesBuffer,e.data.sortedIndexesOffset,r),this.sortWorkerIndexesToSort=new Uint32Array(e.data.indexesToSortBuffer,e.data.indexesToSortOffset,r),this.sortWorkerPrecomputedDistances=new n(e.data.precomputedDistancesBuffer,e.data.precomputedDistancesOffset,r),this.sortWorkerTransforms=new Float32Array(e.data.transformsBuffer,e.data.transformsOffset,16*b.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(r),this.sortWorkerPrecomputedDistances=new n(r),this.sortWorkerTransforms=new Float32Array(16*b.MaxScenes));for(let e=0;e<s;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=r,this.logLevel>=xn){console.log("Sorting web worker ready.");const e=this.splatMesh.getSplatDataTextures(),t=e.covariances.size,n=e.centerColors.size;console.log("Covariances texture size: "+t.x+" x "+t.y),console.log("Centers/colors texture size: "+n.x+" x "+n.y)}t()}}}))}updateError(e,t){return e instanceof p?e:e instanceof dt?new Error("File type or server does not support progressive loading."):t?new Error(t):e}disposeSortWorker(){this.sortWorker&&this.sortWorker.terminate(),this.sortWorker=null,this.sortPromise=null,this.sortPromiseResolver&&(this.sortPromiseResolver(),this.sortPromiseResolver=null),this.preSortMessages=[],this.sortRunning=!1}removeSplatScene(e,t=!0){return this.removeSplatScenes([e],t)}removeSplatScenes(e,t=!0){if(this.isLoadingOrUnloading())throw new Error("Cannot remove splat scene while another load or unload is already in progress.");if(this.isDisposingOrDisposed())throw new Error("Cannot remove splat scene after dispose() is called.");let n;return this.splatSceneRemovalPromise=new Promise(((s,r)=>{let i;t&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),i=this.loadingSpinner.addTask("Removing splat scene..."));const o=()=>{t&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(i))},a=e=>{o(),this.splatSceneRemovalPromise=null,e?r(e):s()},l=()=>!!this.isDisposingOrDisposed()&&(a(),!0);n=this.sortPromise||Promise.resolve(),n.then((()=>{if(l())return;const t=[],s=[],r=[];for(let n=0;n<this.splatMesh.scenes.length;n++){let i=!1;for(let t of e)if(t===n){i=!0;break}if(!i){const e=this.splatMesh.scenes[n];t.push(e.splatBuffer),s.push(this.splatMesh.sceneOptions[n]),r.push({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=Cn,this.createSplatMesh(),this.addSplatBuffers(t,s,!0,!1,!0).then((()=>{l()||(o(),this.splatMesh.scenes.forEach(((e,t)=>{e.position.copy(r[t].position),e.quaternion.copy(r[t].quaternion),e.scale.copy(r[t].scale)})),this.splatMesh.updateTransforms(),this.splatRenderReady=!1,this.runSplatSort(!0).then((()=>{l()?this.splatRenderReady=!0:(n=this.sortPromise||Promise.resolve(),n.then((()=>{this.splatRenderReady=!0,a()})))})))})).catch((e=>{a(e)}))}))})),this.splatSceneRemovalPromise}start(){if(!this.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");this.webXRMode?this.renderer.setAnimationLoop(this.selfDrivenUpdateFunc):this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc),this.selfDrivenModeRunning=!0}stop(){this.selfDrivenMode&&this.selfDrivenModeRunning&&(this.webXRMode?this.renderer.setAnimationLoop(null):cancelAnimationFrame(this.requestFrameId),this.selfDrivenModeRunning=!1)}async dispose(){if(this.isDisposingOrDisposed())return this.disposePromise;let e=[],t=[];for(let n in this.splatSceneDownloadPromises)if(this.splatSceneDownloadPromises.hasOwnProperty(n)){const s=this.splatSceneDownloadPromises[n];t.push(s),e.push(s.promise)}return this.sortPromise&&e.push(this.sortPromise),this.disposing=!0,this.disposePromise=Promise.all(e).finally((()=>{this.stop(),this.orthographicControls&&(this.orthographicControls.dispose(),this.orthographicControls=null),this.perspectiveControls&&(this.perspectiveControls.dispose(),this.perspectiveControls=null),this.controls=null,this.splatMesh&&(this.splatMesh.dispose(),this.splatMesh=null),this.sceneHelper&&(this.sceneHelper.dispose(),this.sceneHelper=null),this.resizeObserver&&(this.resizeObserver.unobserve(this.rootElement),this.resizeObserver=null),this.disposeSortWorker(),this.removeEventHandlers(),this.loadingSpinner.removeAllTasks(),this.loadingSpinner.setContainer(null),this.loadingProgressBar.hide(),this.loadingProgressBar.setContainer(null),this.infoPanel.setContainer(null),this.camera=null,this.threeScene=null,this.splatRenderReady=!1,this.initialized=!1,this.renderer&&(this.usingExternalRenderer||(this.rootElement.removeChild(this.renderer.domElement),this.renderer.dispose()),this.renderer=null),this.usingExternalRenderer||document.body.removeChild(this.rootElement),this.sortWorkerSortedIndexes=null,this.sortWorkerIndexesToSort=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.disposed=!0,this.disposing=!1,this.disposePromise=null})),t.forEach((e=>{e.abort("Scene disposed")})),this.disposePromise}selfDrivenUpdate(){this.selfDrivenMode&&!this.webXRMode&&(this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc)),this.update(),this.shouldRender()?(this.render(),this.consecutiveRenderFrames++):this.consecutiveRenderFrames=0,this.renderNextFrame=!1}forceRenderNextFrame(){this.renderNextFrame=!0}shouldRender=function(){let t=0;const n=new e.Vector3,s=new e.Quaternion,r=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let e=!1,i=!1;if(this.camera){const e=this.camera.position,t=this.camera.quaternion;i=Math.abs(e.x-n.x)>r||Math.abs(e.y-n.y)>r||Math.abs(e.z-n.z)>r||Math.abs(t.x-s.x)>r||Math.abs(t.y-s.y)>r||Math.abs(t.z-s.z)>r||Math.abs(t.w-s.w)>r}return e=this.renderMode!==Hn&&(0===t||this.splatMesh.visibleRegionChanging||i||this.renderMode===Pn||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(n.copy(this.camera.position),s.copy(this.camera.quaternion)),t++,e}}();render=function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return;const e=this.renderer.autoClear;(e=>{for(let t of e.children)if(t.visible)return!0;return!1})(this.threeScene)&&(this.renderer.render(this.threeScene,this.camera),this.renderer.autoClear=!1),this.renderer.render(this.splatMesh,this.camera),this.renderer.autoClear=!1,this.sceneHelper.getFocusMarkerOpacity()>0&&this.renderer.render(this.sceneHelper.focusMarker,this.camera),this.showControlPlane&&this.renderer.render(this.sceneHelper.controlPlane,this.camera),this.renderer.autoClear=e};update(e,t){this.dropInMode&&this.updateForDropInMode(e,t),this.initialized&&this.splatRenderReady&&!this.isDisposingOrDisposed()&&(this.controls&&(this.controls.update(),this.camera.isOrthographicCamera&&!this.usingExternalCamera&&kn.setCameraPositionFromZoom(this.camera,this.camera,this.controls)),this.runSplatSort(),this.updateForRendererSizeChanges(),this.updateSplatMesh(),this.updateMeshCursor(),this.updateFPS(),this.timingSensitiveUpdates(),this.updateInfoPanel(),this.updateControlPlane())}updateForDropInMode(e,t){this.renderer=e,this.splatMesh&&this.splatMesh.setRenderer(this.renderer),this.camera=t,this.controls&&(this.controls.object=t),this.init()}updateFPS=function(){let e=f(),t=0;return function(){if(this.consecutiveRenderFrames>60){const n=f();n-e>=1?(this.currentFPS=t,t=0,e=n):t++}else this.currentFPS=null}}();updateForRendererSizeChanges=function(){const t=new e.Vector2,n=new e.Vector2;let s;return function(){this.usingExternalCamera||(this.renderer.getSize(n),void 0!==s&&s===this.camera.isOrthographicCamera&&n.x===t.x&&n.y===t.y||(this.camera.isOrthographicCamera?(this.camera.left=-n.x/2,this.camera.right=n.x/2,this.camera.top=n.y/2,this.camera.bottom=-n.y/2):this.camera.aspect=n.x/n.y,this.camera.updateProjectionMatrix(),t.copy(n),s=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){const t=f();e||(e=t);const n=t-e;this.updateCameraTransition(t),this.updateFocusMarker(n),e=t}}();updateCameraTransition=function(){let t=new e.Vector3,n=new e.Vector3,s=new e.Vector3;return function(e){if(this.transitioningCameraTarget){n.copy(this.previousCameraTarget).sub(this.camera.position).normalize(),s.copy(this.nextCameraTarget).sub(this.camera.position).normalize();const r=Math.acos(n.dot(s)),i=(r/(Math.PI/3)*.65+.3)/r*(e-this.transitioningCameraTargetStartTime);t.copy(this.previousCameraTarget).lerp(this.nextCameraTarget,i),this.camera.lookAt(t),this.controls.target.copy(t),i>=1&&(this.transitioningCameraTarget=!1)}}}();updateFocusMarker=function(){const t=new e.Vector2;let n=!1;return function(e){if(this.getRenderDimensions(t),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const s=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let r=Math.min(s+10*e,1);this.sceneHelper.setFocusMarkerOpacity(r),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,t),n=!0,this.forceRenderNextFrame()}else{let s;if(s=n?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),s>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,t);let n=Math.max(s-2.5*e,0);this.sceneHelper.setFocusMarkerOpacity(n),0===n&&this.sceneHelper.setFocusMarkerVisibility(!1)}s>0&&this.forceRenderNextFrame(),n=!1}}}();updateMeshCursor=function(){const t=[],n=new e.Vector2;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(n),t.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,n),this.raycaster.intersectSplatMesh(this.splatMesh,t),t.length>0?(this.sceneHelper.setMeshCursorVisibility(!0),this.sceneHelper.positionAndOrientMeshCursor(t[0].origin,this.camera)):this.sceneHelper.setMeshCursorVisibility(!1)):(this.sceneHelper.getMeschCursorVisibility()&&this.forceRenderNextFrame(),this.sceneHelper.setMeshCursorVisibility(!1))}}();updateInfoPanel=function(){const t=new e.Vector2;return function(){if(!this.showInfo)return;const e=this.splatMesh.getSplatCount();this.getRenderDimensions(t);const n=this.controls?this.controls.target:null,s=this.showMeshCursor?this.sceneHelper.meshCursor.position:null,r=e>0?this.splatRenderCount/e*100:0;this.infoPanel.update(t,this.camera.position,n,this.camera.up,this.camera.isOrthographicCamera,s,this.currentFPS||"N/A",e,this.splatRenderCount,r,this.lastSortTime,this.focalAdjustment,this.splatMesh.getSplatScale(),this.splatMesh.getPointCloudModeEnabled())}}();updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}runSplatSort=function(){const t=new e.Matrix4,n=[],s=new e.Vector3(0,0,-1),r=new e.Vector3(0,0,-1),i=new e.Vector3,o=new e.Vector3,a=[],l=[{angleThreshold:.55,sortFractions:[.125,.33333,.75]},{angleThreshold:.65,sortFractions:[.33333,.66667]},{angleThreshold:.8,sortFractions:[.5]}];return function(e=!1,c=!1){if(!this.initialized)return Promise.resolve(!1);if(this.sortRunning)return Promise.resolve(!0);if(this.splatMesh.getSplatCount()<=0)return this.splatRenderCount=0,Promise.resolve(!1);let h=0,d=0,p=!1,u=!1;if(r.set(0,0,-1).applyQuaternion(this.camera.quaternion),h=r.dot(s),d=o.copy(this.camera.position).sub(i).length(),!(e||this.splatMesh.dynamicMode||0!==a.length||(h<=.99&&(p=!0),d>=1&&(u=!0),p||u)))return Promise.resolve(!1);this.sortRunning=!0;let{splatRenderCount:m,shouldSortAll:A}=this.gatherSceneNodesForSort();A=A||c,this.splatRenderCount=m,t.copy(this.camera.matrixWorld).invert();const f=this.perspectiveCamera||this.camera;t.premultiply(f.projectionMatrix),this.splatMesh.dynamicMode||t.multiply(this.splatMesh.matrixWorld);let g=Promise.resolve(!0);return this.gpuAcceleratedSort&&(a.length<=1||a.length%2==0)&&(g=this.splatMesh.computeDistancesOnGPU(t,this.sortWorkerPrecomputedDistances)),g.then((()=>{if(0===a.length)if(this.splatMesh.dynamicMode||A)a.push(this.splatRenderCount);else{for(let e of l)if(h<e.angleThreshold){for(let t of e.sortFractions)a.push(Math.floor(this.splatRenderCount*t));break}a.push(this.splatRenderCount)}let e=Math.min(a.shift(),this.splatRenderCount);this.splatSortCount=e,n[0]=this.camera.position.x,n[1]=this.camera.position.y,n[2]=this.camera.position.z;const o={modelViewProj:t.elements,cameraPosition:n,splatRenderCount:this.splatRenderCount,splatSortCount:e,usePrecomputedDistances:this.gpuAcceleratedSort};return this.splatMesh.dynamicMode&&this.splatMesh.fillTransformsArray(this.sortWorkerTransforms),this.sharedMemoryForWorkers||(o.indexesToSort=this.sortWorkerIndexesToSort,o.transforms=this.sortWorkerTransforms,this.gpuAcceleratedSort&&(o.precomputedDistances=this.sortWorkerPrecomputedDistances)),this.sortPromise=new Promise((e=>{this.sortPromiseResolver=e})),this.preSortMessages.length>0&&(this.preSortMessages.forEach((e=>{this.sortWorker.postMessage(e)})),this.preSortMessages=[]),this.sortWorker.postMessage({sort:o}),0===a.length&&(i.copy(this.camera.position),s.copy(r)),!0})),g}}();gatherSceneNodesForSort=function(){const t=[];let n=null;const s=new e.Vector3,r=new e.Vector3,i=new e.Vector3,o=new e.Matrix4,a=new e.Matrix4,l=new e.Matrix4,c=new e.Vector3,h=new e.Vector3(0,0,-1),d=new e.Vector3,p=e=>d.copy(e.max).sub(e.min).length();return function(d=!1){this.getRenderDimensions(c);const u=c.y/2/Math.tan(this.camera.fov/2*e.MathUtils.DEG2RAD),m=Math.atan(c.x/2/u),A=Math.atan(c.y/2/u),f=Math.cos(m),g=Math.cos(A),S=this.splatMesh.getSplatTree();if(S){a.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||a.multiply(this.splatMesh.matrixWorld);let e=0,n=0;for(let c=0;c<S.subTrees.length;c++){const u=S.subTrees[c];o.copy(a),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(c,l),o.multiply(l));const m=u.nodesWithIndexes.length;for(let a=0;a<m;a++){const l=u.nodesWithIndexes[a];if(!l.data||!l.data.indexes||0===l.data.indexes.length)continue;i.copy(l.center).applyMatrix4(o);const c=i.length();i.normalize(),s.copy(i).setX(0).normalize(),r.copy(i).setY(0).normalize();const m=h.dot(r),A=h.dot(s),S=p(l);!d&&(m<f-.6||A<g-.6)&&c>S||(n+=l.data.indexes.length,t[e]=l,l.data.distanceToNode=c,e++)}}t.length=e,t.sort(((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1));let c=n*b.BytesPerInt;for(let n=0;n<e;n++){const e=t[n],s=e.data.indexes.length,r=s*b.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,c-r,s).set(e.data.indexes),c-=r}return{splatRenderCount:n,shouldSortAll:!1}}{const e=this.splatMesh.getSplatCount();if(!n||n.length!==e){n=new Uint32Array(e);for(let t=0;t<e;t++)n[t]=t}return this.sortWorkerIndexesToSort.set(n),{splatRenderCount:e,shouldSortAll:!0}}}}();getSplatMesh(){return this.splatMesh}getSplatScene(e){return this.splatMesh.getScene(e)}getSceneCount(){return this.splatMesh.getSceneCount()}isMobile(){return navigator.userAgent.includes("Mobi")}}class Ln extends e.Group{constructor(e={}){super(),e.selfDrivenMode=!1,e.useBuiltInControls=!1,e.rootElement=null,e.dropInMode=!0,e.camera=void 0,e.renderer=void 0,this.viewer=new kn(e),this.splatMesh=null,this.updateSplatMesh(),this.callbackMesh=Ln.createCallbackMesh(),this.add(this.callbackMesh),this.callbackMesh.onBeforeRender=Ln.onBeforeRender.bind(this,this.viewer),this.viewer.onSplatMeshChanged((()=>{this.updateSplatMesh()}))}updateSplatMesh(){this.splatMesh!==this.viewer.splatMesh&&(this.splatMesh&&this.remove(this.splatMesh),this.splatMesh=this.viewer.splatMesh,this.add(this.viewer.splatMesh))}addSplatScene(e,t={}){return!1!==t.showLoadingUI&&(t.showLoadingUI=!0),this.viewer.addSplatScene(e,t)}addSplatScenes(e,t){return!1!==t&&(t=!0),this.viewer.addSplatScenes(e,t)}getSplatScene(e){return this.viewer.getSplatScene(e)}removeSplatScene(e,t=!0){return this.viewer.removeSplatScene(e,t)}removeSplatScenes(e,t=!0){return this.viewer.removeSplatScenes(e,t)}getSceneCount(){return this.viewer.getSceneCount()}setActiveSphericalHarmonicsDegrees(e){this.viewer.setActiveSphericalHarmonicsDegrees(e)}async dispose(){return await this.viewer.dispose()}static onBeforeRender(e,t,n,s){e.update(t,s)}static createCallbackMesh(){const t=new e.SphereGeometry(1,8,8),n=new e.MeshBasicMaterial;n.colorWrite=!1,n.depthWrite=!1;const s=new e.Mesh(t,n);return s.frustumCulled=!1,s}}const On=(new l).setFromAxisAngle(new i(0,0,1),Math.PI);class Un{constructor(){}async load(e,t={},n){n||(n=this.createViewer()),await n.addSplatScene(e,Object.assign({showLoadingUI:!1},t));const s=n.getSplatScene(0);return s&&s.quaternion.copy(On),n}async loads(e,t,n=!1){t||(t=this.createViewer()),await t.addSplatScenes(e,n);const s=t.getSceneCount();for(let e=0;e<s;e++){const n=t.getSplatScene(e);n&&n.quaternion.copy(On)}return t}createViewer(e){return new Ln(Object.assign({sharedMemoryForWorkers:!1,gpuAcceleratedSort:!1,halfPrecisionCovariancesOnGPU:!0,dynamicScene:!0},e))}}export{Un as default};
|