import{E as Ue,bi as pt,i as Ut,bS as Pt,S as W,P as Nt,a2 as Wt,a3 as Gt,a4 as jt,a7 as Xt,ab as Zt,q as Vt,b8 as $t,v as qt,x as Kt,w as Qt,f as _t,ak as Jt,m as K,R as Lt,bT as Yt,bU as es,D as Pe,M as Ce,V as M,C as Ne,bV as ts,d as Z,L as de,bW as Me,bX as Ie,e as Rt,aV as le,bY as ss,ap as re,bh as L,Q as rs,F as Se,aq as he,bw as se,B as os,bZ as He,aE as ns}from"./index-6jOCfdig.js";import{_ as ye}from"./index-Ds2meNS5.js";import{ShaderMaterial as is}from"./shaderMaterial-DgaWoVHF.js";import"./logDepthDeclaration-Dwp6Onv7.js";import"./fogFragment-Bt8ZUPFz.js";import"./sceneUboDeclaration-CBM--qyH.js";import"./meshUboDeclaration-5_vgMHR7.js";import"./logDepthVertex-8dZnyEoz.js";import"./helperFunctions-C8obpaoJ.js";import"./clipPlaneFragment-CpTH2ok1.js";import"./logDepthDeclaration-o_Q4m4rj.js";import"./fogFragment-CFdlL0uf.js";import"./sceneUboDeclaration-D5qDFEBI.js";import"./meshUboDeclaration-DMCdxtAs.js";import"./helperFunctions-HlNEQLxP.js";import"./clipPlaneVertex-B-dmPkvj.js";import"./logDepthVertex-LhUaE1fA.js";import"./shadowMapFragmentExtraDeclaration-BdKi3DOx.js";import{R as we}from"./rawTexture-CpjOe2U7.js";import"./thinInstanceMesh-Dh3xKL92.js";import{A as as}from"./assetContainer-Drc86vic.js";import{Ray as cs}from"./ray-DrOAtl-Q.js";import{S as ls}from"./standardMaterial-BXdzQN--.js";import"./svelte/svelte_svelte.js";import"./svelte/svelte_animate.js";import"./svelte/svelte_attachments.js";import"./svelte/svelte_easing.js";import"./svelte/svelte_internal_client.js";import"./svelte/svelte_internal_flags_async.js";import"./svelte/svelte_internal_flags_legacy.js";import"./svelte/svelte_internal_flags_tracing.js";import"./svelte/svelte_internal_server.js";import"./svelte/svelte_legacy.js";import"./svelte/svelte_motion.js";import"./svelte/svelte_reactivity.js";import"./svelte/svelte_reactivity_window.js";import"./svelte/svelte_server.js";import"./svelte/svelte_store.js";import"./svelte/svelte_transition.js";import"./svelte/svelte_events.js";import"./packingFunctions-hXt6UD6k.js";class hs{constructor(){this.mm=new Map}get(e,s){const r=this.mm.get(e);if(r!==void 0)return r.get(s)}set(e,s,r){let n=this.mm.get(e);n===void 0&&this.mm.set(e,n=new Map),n.set(s,r)}}class us{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,s,r){this._baseMaterial=e,this._scene=s??Ue.LastCreatedScene,this._options=r,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new hs,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add(n=>{const o=n.subMesh?.getMesh();o&&!this._meshes.has(o)&&this._meshes.set(o,o.onDisposeObservable.add(i=>{const c=this._subMeshToEffect.keys();for(let f=c.next();f.done!==!0;f=c.next()){const a=f.value;a?.getMesh()===i&&(this._subMeshToEffect.delete(a),this._deleteDepthWrapperEffect(a))}})),this._subMeshToEffect.get(n.subMesh)?.[0]!==n.effect&&(this._subMeshToEffect.set(n.subMesh,[n.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(n.subMesh))})}_deleteDepthWrapperEffect(e){const s=this._subMeshToDepthWrapper.mm.get(e);s&&(s.forEach(r=>{r.mainDrawWrapper.effect?.dispose()}),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,s,r){const n=this._subMeshToDepthWrapper.mm.get(e)?.get(s);if(!n)return null;let o=n.drawWrapper[r];return o||(o=n.drawWrapper[r]=new pt(this._scene.getEngine()),o.setEffect(n.mainDrawWrapper.effect,n.mainDrawWrapper.defines)),o}isReadyForSubMesh(e,s,r,n,o){return this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,n)?!1:this._makeEffect(e,s,r,o)?.isReady()??!1}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let s=e.next();s.done!==!0;s=e.next()){const[r,n]=s.value;r.onDisposeObservable.remove(n)}}_makeEffect(e,s,r,n){const o=this._scene.getEngine(),i=this._subMeshToEffect.get(e);if(!i)return null;const[c,f]=i;if(!c.isReady())return null;let a=this._subMeshToDepthWrapper.get(e,r);if(!a){const x=new pt(o);x.defines=e._getDrawWrapper(f)?.defines??null,a={drawWrapper:[],mainDrawWrapper:x,depthDefines:"",token:Ut()},a.drawWrapper[n]=x,this._subMeshToDepthWrapper.set(e,r,a)}const _=s.join(`
`);if(a.mainDrawWrapper.effect&&_===a.depthDefines)return a.mainDrawWrapper.effect;a.depthDefines=_;const h=c.getUniformNames().slice();let l=c.vertexSourceCodeBeforeMigration,d=c.fragmentSourceCodeBeforeMigration;if(!l&&!d)return null;if(!this.doNotInjectCode){const x=this._options&&this._options.remappedVariables?`#include<shadowMapVertexNormalBias>(${this._options.remappedVariables.join(",")})`:"#include<shadowMapVertexNormalBias>",C=this._options&&this._options.remappedVariables?`#include<shadowMapVertexMetric>(${this._options.remappedVariables.join(",")})`:"#include<shadowMapVertexMetric>",S=this._options&&this._options.remappedVariables?`#include<shadowMapFragmentSoftTransparentShadow>(${this._options.remappedVariables.join(",")})`:"#include<shadowMapFragmentSoftTransparentShadow>",u="#include<shadowMapFragment>",b="#include<shadowMapVertexExtraDeclaration>";c.shaderLanguage===0?l=l.replace(/void\s+?main/g,`
${b}
void main`):l=l.replace(/@vertex/g,`
${b}
@vertex`),l=l.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,x),l.indexOf("#define SHADOWDEPTH_METRIC")!==-1?l=l.replace(/#define SHADOWDEPTH_METRIC/g,C):l=l.replace(/}\s*$/g,C+`
}`),l=l.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const m=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,p=d.indexOf("#define SHADOWDEPTH_FRAGMENT")!==-1;let v="";m?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,S):v=S+`
`,d=d.replace(/void\s+?main/g,Pt.IncludesShadersStore.shadowMapFragmentExtraDeclaration+`
void main`),p?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,u):v+=u+`
`,v&&(d=d.replace(/}\s*$/g,v+"}")),h.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}a.mainDrawWrapper.effect=o.createEffect({vertexSource:l,fragmentSource:d,vertexToken:a.token,fragmentToken:a.token},{attributes:c.getAttributesNames(),uniformsNames:h,uniformBuffersNames:c.getUniformBuffersNames(),samplers:c.getSamplers(),defines:_+`
`+c.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:c.getIndexParameters(),shaderLanguage:c.shaderLanguage},o);for(let x=0;x<a.drawWrapper.length;++x)x!==n&&a.drawWrapper[x]?.setEffect(a.mainDrawWrapper.effect,a.mainDrawWrapper.defines);return a.mainDrawWrapper.effect}}const mt="gaussianSplattingFragmentDeclaration",fs=`vec4 gaussianColor(vec4 inColor)
{float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*inColor.a;
#include<logDepthFragment>
vec3 color=inColor.rgb;
#ifdef FOG
#include<fogFragment>
#endif
return vec4(color,B);}
`;W.IncludesShadersStore[mt]||(W.IncludesShadersStore[mt]=fs);const ke="gaussianSplattingPixelShader",kt=`#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
varying vec4 vColor;varying vec2 vPosition;
#include<gaussianSplattingFragmentDeclaration>
void main () { 
#include<clipPlaneFragment>
gl_FragColor=gaussianColor(vColor);}
`;W.ShadersStore[ke]||(W.ShadersStore[ke]=kt);const ds={name:ke,shader:kt},ps=Object.freeze(Object.defineProperty({__proto__:null,gaussianSplattingPixelShader:ds},Symbol.toStringTag,{value:"Module"})),xt="gaussianSplattingVertexDeclaration",_s="attribute vec2 position;uniform mat4 view;uniform mat4 projection;uniform mat4 world;uniform vec4 vEyePosition;";W.IncludesShadersStore[xt]||(W.IncludesShadersStore[xt]=_s);const vt="gaussianSplattingUboDeclaration",ms=`#include<sceneUboDeclaration>
#include<meshUboDeclaration>
attribute vec2 position;`;W.IncludesShadersStore[vt]||(W.IncludesShadersStore[vt]=ms);const gt="gaussianSplatting",xs=`#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE)
mat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0],
matrix[0][1],matrix[1][1],matrix[2][1],
matrix[0][2],matrix[1][2],matrix[2][2]);}
#endif
vec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);}
#if SH_DEGREE>0
ivec2 getDataUVint(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return ivec2(uint(x+0.5),uint(y+0.5));}
#endif
struct Splat {vec4 center;vec4 color;vec4 covA;vec4 covB;
#if SH_DEGREE>0
uvec4 sh0; 
#endif
#if SH_DEGREE>1
uvec4 sh1;
#endif
#if SH_DEGREE>2
uvec4 sh2;
#endif
};Splat readSplat(float splatIndex)
{Splat splat;vec2 splatUV=getDataUV(splatIndex,dataTextureSize);splat.center=texture2D(centersTexture,splatUV);splat.color=texture2D(colorsTexture,splatUV);splat.covA=texture2D(covariancesATexture,splatUV)*splat.center.w;splat.covB=texture2D(covariancesBTexture,splatUV)*splat.center.w;
#if SH_DEGREE>0
ivec2 splatUVint=getDataUVint(splatIndex,dataTextureSize);splat.sh0=texelFetch(shTexture0,splatUVint,0);
#endif
#if SH_DEGREE>1
splat.sh1=texelFetch(shTexture1,splatUVint,0);
#endif
#if SH_DEGREE>2
splat.sh2=texelFetch(shTexture2,splatUVint,0);
#endif
return splat;}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
vec3 computeColorFromSHDegree(vec3 dir,const vec3 sh[16])
{const float SH_C0=0.28209479;const float SH_C1=0.48860251;float SH_C2[5];SH_C2[0]=1.092548430;SH_C2[1]=-1.09254843;SH_C2[2]=0.315391565;SH_C2[3]=-1.09254843;SH_C2[4]=0.546274215;float SH_C3[7];SH_C3[0]=-0.59004358;SH_C3[1]=2.890611442;SH_C3[2]=-0.45704579;SH_C3[3]=0.373176332;SH_C3[4]=-0.45704579;SH_C3[5]=1.445305721;SH_C3[6]=-0.59004358;vec3 result=/*SH_C0**/sh[0];
#if SH_DEGREE>0
float x=dir.x;float y=dir.y;float z=dir.z;result+=- SH_C1*y*sh[1]+SH_C1*z*sh[2]-SH_C1*x*sh[3];
#if SH_DEGREE>1
float xx=x*x,yy=y*y,zz=z*z;float xy=x*y,yz=y*z,xz=x*z;result+=
SH_C2[0]*xy*sh[4] +
SH_C2[1]*yz*sh[5] +
SH_C2[2]*(2.0*zz-xx-yy)*sh[6] +
SH_C2[3]*xz*sh[7] +
SH_C2[4]*(xx-yy)*sh[8];
#if SH_DEGREE>2
result+=
SH_C3[0]*y*(3.0*xx-yy)*sh[9] +
SH_C3[1]*xy*z*sh[10] +
SH_C3[2]*y*(4.0*zz-xx-yy)*sh[11] +
SH_C3[3]*z*(2.0*zz-3.0*xx-3.0*yy)*sh[12] +
SH_C3[4]*x*(4.0*zz-xx-yy)*sh[13] +
SH_C3[5]*z*(xx-yy)*sh[14] +
SH_C3[6]*x*(xx-3.0*yy)*sh[15];
#endif
#endif
#endif
return result;}
vec4 decompose(uint value)
{vec4 components=vec4(
float((value ) & 255u),
float((value>>uint( 8)) & 255u),
float((value>>uint(16)) & 255u),
float((value>>uint(24)) & 255u));return components*vec4(2./255.)-vec4(1.);}
vec3 computeSH(Splat splat,vec3 dir)
{vec3 sh[16];sh[0]=vec3(0.,0.,0.);
#if SH_DEGREE>0
vec4 sh00=decompose(splat.sh0.x);vec4 sh01=decompose(splat.sh0.y);vec4 sh02=decompose(splat.sh0.z);sh[1]=vec3(sh00.x,sh00.y,sh00.z);sh[2]=vec3(sh00.w,sh01.x,sh01.y);sh[3]=vec3(sh01.z,sh01.w,sh02.x);
#endif
#if SH_DEGREE>1
vec4 sh03=decompose(splat.sh0.w);vec4 sh04=decompose(splat.sh1.x);vec4 sh05=decompose(splat.sh1.y);sh[4]=vec3(sh02.y,sh02.z,sh02.w);sh[5]=vec3(sh03.x,sh03.y,sh03.z);sh[6]=vec3(sh03.w,sh04.x,sh04.y);sh[7]=vec3(sh04.z,sh04.w,sh05.x);sh[8]=vec3(sh05.y,sh05.z,sh05.w);
#endif
#if SH_DEGREE>2
vec4 sh06=decompose(splat.sh1.z);vec4 sh07=decompose(splat.sh1.w);vec4 sh08=decompose(splat.sh2.x);vec4 sh09=decompose(splat.sh2.y);vec4 sh10=decompose(splat.sh2.z);vec4 sh11=decompose(splat.sh2.w);sh[9]=vec3(sh06.x,sh06.y,sh06.z);sh[10]=vec3(sh06.w,sh07.x,sh07.y);sh[11]=vec3(sh07.z,sh07.w,sh08.x);sh[12]=vec3(sh08.y,sh08.z,sh08.w);sh[13]=vec3(sh09.x,sh09.y,sh09.z);sh[14]=vec3(sh09.w,sh10.x,sh10.y);sh[15]=vec3(sh10.z,sh10.w,sh11.x); 
#endif
return computeColorFromSHDegree(dir,sh);}
#else
vec3 computeSH(Splat splat,vec3 dir)
{return vec3(0.,0.,0.);}
#endif
vec4 gaussianSplatting(vec2 meshPos,vec3 worldPos,vec2 scale,vec3 covA,vec3 covB,mat4 worldMatrix,mat4 viewMatrix,mat4 projectionMatrix)
{mat4 modelView=viewMatrix*worldMatrix;vec4 camspace=viewMatrix*vec4(worldPos,1.);vec4 pos2d=projectionMatrix*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds
|| pos2d.y<-bounds || pos2d.y>bounds) {return vec4(0.0,0.0,2.0,1.0);}
mat3 Vrk=mat3(
covA.x,covA.y,covA.z,
covA.y,covB.x,covB.y,
covA.z,covB.y,covB.z
);bool isOrtho=abs(projectionMatrix[3][3]-1.0)<0.001;mat3 J;if (isOrtho) {J=mat3(
focal.x,0.,0.,
0.,focal.y,0.,
0.,0.,0.
);} else {J=mat3(
focal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z),
0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),
0.,0.,0.
);}
mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;
#if COMPENSATION
float c00=cov2d[0][0];float c11=cov2d[1][1];float c01=cov2d[0][1];float detOrig=c00*c11-c01*c01;
#endif
cov2d[0][0]+=kernelSize;cov2d[1][1]+=kernelSize;
#if COMPENSATION
vec3 c2d=vec3(cov2d[0][0],c01,cov2d[1][1]);float detBlur=c2d.x*c2d.z-c2d.y*c2d.y;float compensation=sqrt(max(0.,detOrig/detBlur));vColor.w*=compensation;
#endif
float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float epsilon=0.0001;float lambda1=mid+radius+epsilon,lambda2=mid-radius+epsilon;if (lambda2<0.0)
{return vec4(0.0,0.0,2.0,1.0);}
vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vec2 vCenter=vec2(pos2d);float scaleFactor=isOrtho ? 1.0 : pos2d.w;return vec4(
vCenter 
+ ((meshPos.x*majorAxis
+ meshPos.y*minorAxis)*invViewport*scaleFactor)*scale,pos2d.zw);}`;W.IncludesShadersStore[gt]||(W.IncludesShadersStore[gt]=xs);const Fe="gaussianSplattingVertexShader",Ft=`#include<__decl__gaussianSplattingVertex>
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
attribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform float kernelSize;uniform vec3 eyePosition;uniform vec3 viewDirectionFactor;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;
#if SH_DEGREE>0
uniform highp usampler2D shTexture0;
#endif
#if SH_DEGREE>1
uniform highp usampler2D shTexture1;
#endif
#if SH_DEGREE>2
uniform highp usampler2D shTexture2;
#endif
varying vec4 vColor;varying vec2 vPosition;
#include<gaussianSplatting>
void main () {Splat splat=readSplat(splatIndex);vec3 covA=splat.covA.xyz;vec3 covB=vec3(splat.covA.w,splat.covB.xy);vec4 worldPos=world*vec4(splat.center.xyz,1.0);vColor=splat.color;vPosition=position;
#if SH_DEGREE>0
mat3 worldRot=mat3(world);mat3 normWorldRot=inverseMat3(worldRot);vec3 dir=normalize(normWorldRot*(worldPos.xyz-eyePosition));dir*=viewDirectionFactor;vColor.xyz=splat.color.xyz+computeSH(splat,dir);
#endif
gl_Position=gaussianSplatting(position,worldPos.xyz,vec2(1.,1.),covA,covB,world,view,projection);
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}
`;W.ShadersStore[Fe]||(W.ShadersStore[Fe]=Ft);const vs={name:Fe,shader:Ft},gs=Object.freeze(Object.defineProperty({__proto__:null,gaussianSplattingVertexShader:vs},Symbol.toStringTag,{value:"Module"})),St="gaussianSplattingFragmentDeclaration",Ss=`fn gaussianColor(inColor: vec4f,inPosition: vec2f)->vec4f
{var A : f32=-dot(inPosition,inPosition);if (A>-4.0)
{var B: f32=exp(A)*inColor.a;
#include<logDepthFragment>
var color: vec3f=inColor.rgb;
#ifdef FOG
#include<fogFragment>
#endif
return vec4f(color,B);} else {return vec4f(0.0);}}
`;W.IncludesShadersStoreWGSL[St]||(W.IncludesShadersStoreWGSL[St]=Ss);const Oe="gaussianSplattingPixelShader",Ot=`#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
varying vColor: vec4f;varying vPosition: vec2f;
#include<gaussianSplattingFragmentDeclaration>
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
fragmentOutputs.color=gaussianColor(input.vColor,input.vPosition);}
`;W.ShadersStoreWGSL[Oe]||(W.ShadersStoreWGSL[Oe]=Ot);const ys={name:Oe,shader:Ot},ws=Object.freeze(Object.defineProperty({__proto__:null,gaussianSplattingPixelShaderWGSL:ys},Symbol.toStringTag,{value:"Module"})),yt="gaussianSplatting",Cs=`fn getDataUV(index: f32,dataTextureSize: vec2f)->vec2<f32> {let y: f32=floor(index/dataTextureSize.x);let x: f32=index-y*dataTextureSize.x;return vec2f((x+0.5),(y+0.5));}
struct Splat {center: vec4f,
color: vec4f,
covA: vec4f,
covB: vec4f,
#if SH_DEGREE>0
sh0: vec4<u32>,
#endif
#if SH_DEGREE>1
sh1: vec4<u32>,
#endif
#if SH_DEGREE>2
sh2: vec4<u32>,
#endif
};fn readSplat(splatIndex: f32,dataTextureSize: vec2f)->Splat {var splat: Splat;let splatUV=getDataUV(splatIndex,dataTextureSize);let splatUVi32=vec2<i32>(i32(splatUV.x),i32(splatUV.y));splat.center=textureLoad(centersTexture,splatUVi32,0);splat.color=textureLoad(colorsTexture,splatUVi32,0);splat.covA=textureLoad(covariancesATexture,splatUVi32,0)*splat.center.w;splat.covB=textureLoad(covariancesBTexture,splatUVi32,0)*splat.center.w;
#if SH_DEGREE>0
splat.sh0=textureLoad(shTexture0,splatUVi32,0);
#endif
#if SH_DEGREE>1
splat.sh1=textureLoad(shTexture1,splatUVi32,0);
#endif
#if SH_DEGREE>2
splat.sh2=textureLoad(shTexture2,splatUVi32,0);
#endif
return splat;}
fn computeColorFromSHDegree(dir: vec3f,sh: array<vec3<f32>,16>)->vec3f
{let SH_C0: f32=0.28209479;let SH_C1: f32=0.48860251;var SH_C2: array<f32,5>=array<f32,5>(
1.092548430,
-1.09254843,
0.315391565,
-1.09254843,
0.546274215
);var SH_C3: array<f32,7>=array<f32,7>(
-0.59004358,
2.890611442,
-0.45704579,
0.373176332,
-0.45704579,
1.445305721,
-0.59004358
);var result: vec3f=/*SH_C0**/sh[0];
#if SH_DEGREE>0
let x: f32=dir.x;let y: f32=dir.y;let z: f32=dir.z;result+=-SH_C1*y*sh[1]+SH_C1*z*sh[2]-SH_C1*x*sh[3];
#if SH_DEGREE>1
let xx: f32=x*x;let yy: f32=y*y;let zz: f32=z*z;let xy: f32=x*y;let yz: f32=y*z;let xz: f32=x*z;result+=
SH_C2[0]*xy*sh[4] +
SH_C2[1]*yz*sh[5] +
SH_C2[2]*(2.0f*zz-xx-yy)*sh[6] +
SH_C2[3]*xz*sh[7] +
SH_C2[4]*(xx-yy)*sh[8];
#if SH_DEGREE>2
result+=
SH_C3[0]*y*(3.0f*xx-yy)*sh[9] +
SH_C3[1]*xy*z*sh[10] +
SH_C3[2]*y*(4.0f*zz-xx-yy)*sh[11] +
SH_C3[3]*z*(2.0f*zz-3.0f*xx-3.0f*yy)*sh[12] +
SH_C3[4]*x*(4.0f*zz-xx-yy)*sh[13] +
SH_C3[5]*z*(xx-yy)*sh[14] +
SH_C3[6]*x*(xx-3.0f*yy)*sh[15];
#endif
#endif
#endif
return result;}
fn decompose(value: u32)->vec4f
{let components : vec4f=vec4f(
f32((value ) & 255u),
f32((value>>u32( 8)) & 255u),
f32((value>>u32(16)) & 255u),
f32((value>>u32(24)) & 255u));return components*vec4f(2./255.)-vec4f(1.);}
fn computeSH(splat: Splat,dir: vec3f)->vec3f
{var sh: array<vec3<f32>,16>;sh[0]=vec3f(0.,0.,0.);
#if SH_DEGREE>0
let sh00: vec4f=decompose(splat.sh0.x);let sh01: vec4f=decompose(splat.sh0.y);let sh02: vec4f=decompose(splat.sh0.z);sh[1]=vec3f(sh00.x,sh00.y,sh00.z);sh[2]=vec3f(sh00.w,sh01.x,sh01.y);sh[3]=vec3f(sh01.z,sh01.w,sh02.x);
#endif
#if SH_DEGREE>1
let sh03: vec4f=decompose(splat.sh0.w);let sh04: vec4f=decompose(splat.sh1.x);let sh05: vec4f=decompose(splat.sh1.y);sh[4]=vec3f(sh02.y,sh02.z,sh02.w);sh[5]=vec3f(sh03.x,sh03.y,sh03.z);sh[6]=vec3f(sh03.w,sh04.x,sh04.y);sh[7]=vec3f(sh04.z,sh04.w,sh05.x);sh[8]=vec3f(sh05.y,sh05.z,sh05.w);
#endif
#if SH_DEGREE>2
let sh06: vec4f=decompose(splat.sh1.z);let sh07: vec4f=decompose(splat.sh1.w);let sh08: vec4f=decompose(splat.sh2.x);let sh09: vec4f=decompose(splat.sh2.y);let sh10: vec4f=decompose(splat.sh2.z);let sh11: vec4f=decompose(splat.sh2.w);sh[9]=vec3f(sh06.x,sh06.y,sh06.z);sh[10]=vec3f(sh06.w,sh07.x,sh07.y);sh[11]=vec3f(sh07.z,sh07.w,sh08.x);sh[12]=vec3f(sh08.y,sh08.z,sh08.w);sh[13]=vec3f(sh09.x,sh09.y,sh09.z);sh[14]=vec3f(sh09.w,sh10.x,sh10.y);sh[15]=vec3f(sh10.z,sh10.w,sh11.x); 
#endif
return computeColorFromSHDegree(dir,sh);}
fn gaussianSplatting(
meshPos: vec2<f32>,
worldPos: vec3<f32>,
scale: vec2<f32>,
covA: vec3<f32>,
covB: vec3<f32>,
worldMatrix: mat4x4<f32>,
viewMatrix: mat4x4<f32>,
projectionMatrix: mat4x4<f32>,
focal: vec2f,
invViewport: vec2f,
kernelSize: f32
)->vec4f {let modelView=viewMatrix*worldMatrix;let camspace=viewMatrix*vec4f(worldPos,1.0);let pos2d=projectionMatrix*camspace;let bounds=1.2*pos2d.w;if (pos2d.z<0. || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {return vec4f(0.0,0.0,2.0,1.0);}
let Vrk=mat3x3<f32>(
covA.x,covA.y,covA.z,
covA.y,covB.x,covB.y,
covA.z,covB.y,covB.z
);let isOrtho=abs(projectionMatrix[3][3]-1.0)<0.001;var J: mat3x3<f32>;if (isOrtho) {J=mat3x3<f32>(
focal.x,0.0,0.0,
0.0,focal.y,0.0,
0.0,0.0,0.0
);} else {J=mat3x3<f32>(
focal.x/camspace.z,0.0,-(focal.x*camspace.x)/(camspace.z*camspace.z),
0.0,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),
0.0,0.0,0.0
);}
let invy=mat3x3<f32>(
1.0,0.0,0.0,
0.0,-1.0,0.0,
0.0,0.0,1.0
);let T=invy*transpose(mat3x3<f32>(
modelView[0].xyz,
modelView[1].xyz,
modelView[2].xyz))*J;var cov2d=transpose(T)*Vrk*T;
#if COMPENSATION
let c00: f32=cov2d[0][0];let c11: f32=cov2d[1][1];let c01: f32=cov2d[0][1];let detOrig: f32=c00*c11-c01*c01;
#endif
cov2d[0][0]+=kernelSize;cov2d[1][1]+=kernelSize;
#if COMPENSATION
let c2d: vec3f=vec3f(cov2d[0][0],c01,cov2d[1][1]);let detBlur: f32=c2d.x*c2d.z-c2d.y*c2d.y;let compensation: f32=sqrt(max(0.,detOrig/detBlur));vertexOutputs.vColor.w*=compensation;
#endif
let mid=(cov2d[0][0]+cov2d[1][1])/2.0;let radius=length(vec2<f32>((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));let lambda1=mid+radius;let lambda2=mid-radius;if (lambda2<0.0) {return vec4f(0.0,0.0,2.0,1.0);}
let diagonalVector=normalize(vec2<f32>(cov2d[0][1],lambda1-cov2d[0][0]));let majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;let minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2<f32>(diagonalVector.y,-diagonalVector.x);let vCenter=vec2<f32>(pos2d.x,pos2d.y);let scaleFactor=select(pos2d.w,1.0,isOrtho);return vec4f(
vCenter+((meshPos.x*majorAxis+meshPos.y*minorAxis)*invViewport*scaleFactor)*scale,
pos2d.z,
pos2d.w
);}`;W.IncludesShadersStoreWGSL[yt]||(W.IncludesShadersStoreWGSL[yt]=Cs);const Be="gaussianSplattingVertexShader",Bt=`#include<sceneUboDeclaration>
#include<meshUboDeclaration>
#include<helperFunctions>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
attribute splatIndex: f32;attribute position: vec2f;uniform invViewport: vec2f;uniform dataTextureSize: vec2f;uniform focal: vec2f;uniform kernelSize: f32;uniform eyePosition: vec3f;uniform viewDirectionFactor: vec3f;var covariancesATexture: texture_2d<f32>;var covariancesBTexture: texture_2d<f32>;var centersTexture: texture_2d<f32>;var colorsTexture: texture_2d<f32>;
#if SH_DEGREE>0
var shTexture0: texture_2d<u32>;
#endif
#if SH_DEGREE>1
var shTexture1: texture_2d<u32>;
#endif
#if SH_DEGREE>2
var shTexture2: texture_2d<u32>;
#endif
varying vColor: vec4f;varying vPosition: vec2f;
#include<gaussianSplatting>
@vertex
fn main(input : VertexInputs)->FragmentInputs {var splat: Splat=readSplat(input.splatIndex,uniforms.dataTextureSize);var covA: vec3f=splat.covA.xyz;var covB: vec3f=vec3f(splat.covA.w,splat.covB.xy);let worldPos: vec4f=mesh.world*vec4f(splat.center.xyz,1.0);vertexOutputs.vPosition=input.position;
#if SH_DEGREE>0
let worldRot: mat3x3f= mat3x3f(mesh.world[0].xyz,mesh.world[1].xyz,mesh.world[2].xyz);let normWorldRot: mat3x3f=inverseMat3(worldRot);var dir: vec3f=normalize(normWorldRot*(worldPos.xyz-uniforms.eyePosition.xyz));dir*=uniforms.viewDirectionFactor;vertexOutputs.vColor=vec4f(splat.color.xyz+computeSH(splat,dir),splat.color.w);
#else
vertexOutputs.vColor=splat.color;
#endif
vertexOutputs.position=gaussianSplatting(input.position,worldPos.xyz,vec2f(1.0,1.0),covA,covB,mesh.world,scene.view,scene.projection,uniforms.focal,uniforms.invViewport,uniforms.kernelSize);
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}
`;W.ShadersStoreWGSL[Be]||(W.ShadersStoreWGSL[Be]=Bt);const bs={name:Be,shader:Bt},Ts=Object.freeze(Object.defineProperty({__proto__:null,gaussianSplattingVertexShaderWGSL:bs},Symbol.toStringTag,{value:"Module"})),wt="gaussianSplattingDepthPixelShader",As=`precision highp float;varying vec2 vPosition;varying vec4 vColor;void main(void) {float A=-dot(vPosition,vPosition);
#if defined(SM_SOFTTRANSPARENTSHADOW) && SM_SOFTTRANSPARENTSHADOW==1
float alpha=exp(A)*vColor.a;if (A<-4.) discard;
#else
if (A<-1.) discard;
#endif
}`;W.ShadersStore[wt]||(W.ShadersStore[wt]=As);const Ct="gaussianSplattingDepthVertexShader",Es=`#include<__decl__gaussianSplattingVertex>
attribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform float kernelSize;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec2 vPosition;varying vec4 vColor;
#include<gaussianSplatting>
void main(void) {Splat splat=readSplat(splatIndex);vec3 covA=splat.covA.xyz;vec3 covB=vec3(splat.covA.w,splat.covB.xy);vec4 worldPosGS=world*vec4(splat.center.xyz,1.0);vPosition=position.xy;vColor=splat.color;gl_Position=gaussianSplatting(position.xy,worldPosGS.xyz,vec2(1.,1.),covA,covB,world,view,projection);}`;W.ShadersStore[Ct]||(W.ShadersStore[Ct]=Es);const bt="gaussianSplattingDepthPixelShader",Ds=`#include<gaussianSplattingFragmentDeclaration>
#include<shadowMapFragmentExtraDeclaration>
varying vPosition: vec2f;varying vColor: vec4f;fn checkDiscard(inPosition: vec2f,inColor: vec4f)->vec4f {var A : f32=-dot(inPosition,inPosition);var alpha : f32=exp(A)*inColor.a;
#if defined(SM_SOFTTRANSPARENTSHADOW) && SM_SOFTTRANSPARENTSHADOW==1
if (A<-4.) {discard;}
#else
if (A<-1.) {discard;}
#endif
return vec4f(inColor.rgb,alpha);}
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=checkDiscard(fragmentInputs.vPosition,fragmentInputs.vColor);
#if defined(SM_SOFTTRANSPARENTSHADOW) && SM_SOFTTRANSPARENTSHADOW==1
var alpha : f32=fragmentOutputs.color.a;
#endif
}
`;W.ShadersStoreWGSL[bt]||(W.ShadersStoreWGSL[bt]=Ds);const Tt="gaussianSplattingDepthVertexShader",zs=`#include<sceneUboDeclaration>
#include<meshUboDeclaration>
attribute splatIndex: f32;attribute position: vec2f;uniform invViewport: vec2f;uniform dataTextureSize: vec2f;uniform focal: vec2f;uniform kernelSize: f32;var covariancesATexture: texture_2d<f32>;var covariancesBTexture: texture_2d<f32>;var centersTexture: texture_2d<f32>;var colorsTexture: texture_2d<f32>;varying vPosition: vec2f;varying vColor: vec4f;
#include<gaussianSplatting>
@vertex
fn main(input : VertexInputs)->FragmentInputs {var splat: Splat=readSplat(input.splatIndex,uniforms.dataTextureSize);var covA: vec3f=splat.covA.xyz;var covB: vec3f=vec3f(splat.covA.w,splat.covB.xy);let worldPos: vec4f=mesh.world*vec4f(splat.center.xyz,1.0);vertexOutputs.vPosition=input.position;vertexOutputs.vColor=splat.color;vertexOutputs.position=gaussianSplatting(input.position,worldPos.xyz,vec2f(1.0,1.0),covA,covB,mesh.world,scene.view,scene.projection,uniforms.focal,uniforms.invViewport,uniforms.kernelSize);}`;W.ShadersStoreWGSL[Tt]||(W.ShadersStoreWGSL[Tt]=zs);class Ms extends Jt{constructor(){super(),this.FOG=!1,this.THIN_INSTANCES=!0,this.LOGARITHMICDEPTH=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.SH_DEGREE=0,this.COMPENSATION=!1,this.rebuild()}}class R extends Nt{constructor(e,s){super(e,s),this.kernelSize=R.KernelSize,this._compensation=R.Compensation,this._isDirty=!1,this.backFaceCulling=!1,this.shadowDepthWrapper=R._MakeGaussianSplattingShadowDepthWrapper(s,this.shaderLanguage)}set compensation(e){this._isDirty=this._isDirty!=e,this._compensation=e}get compensation(){return this._compensation}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,s){const n=s._drawWrapper;let o=s.materialDefines;if(o&&this._isDirty&&o.markAsUnprocessed(),n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===!0)return!0;s.materialDefines||(o=s.materialDefines=new Ms);const i=this.getScene();if(this._isReadyForSubMesh(s))return!0;const c=i.getEngine(),f=e;Wt(e,i,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,o,void 0,void 0,void 0,this._isVertexOutputInvariant),Gt(i,c,this,o,!0,null,!0),jt(e,o,!1,!1),(c.version>1||c.isWebGPU)&&(o.SH_DEGREE=f.shDegree);const a=f.material;if(o.COMPENSATION=a&&a.compensation?a.compensation:R.Compensation,o.isDirty){o.markAsProcessed(),i.resetCachedMaterial(),Xt(R._Attribs,o),Zt({uniformsNames:R._Uniforms,uniformBuffersNames:R._UniformBuffers,samplers:R._Samplers,defines:o}),Vt(R._Uniforms);const _=o.toString(),h=i.getEngine().createEffect("gaussianSplatting",{attributes:R._Attribs,uniformsNames:R._Uniforms,uniformBuffersNames:R._UniformBuffers,samplers:R._Samplers,defines:_,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([ye(()=>Promise.resolve().then(()=>ws),void 0,import.meta.url),ye(()=>Promise.resolve().then(()=>Ts),void 0,import.meta.url)]):await Promise.all([ye(()=>Promise.resolve().then(()=>ps),void 0,import.meta.url),ye(()=>Promise.resolve().then(()=>gs),void 0,import.meta.url)])}},c);s.setEffect(h,o,this._materialContext)}return!s.effect||!s.effect.isReady()?!1:(o._renderId=i.getRenderId(),n._wasPreviouslyReady=!0,n._wasPreviouslyUsingInstances=!0,this._isDirty=!1,!0)}static BindEffect(e,s,r){const n=r.getEngine(),o=r.activeCamera,i=n.getRenderWidth(),c=n.getRenderHeight(),f=e,a=f.material,_=o?.rigParent?.rigCameras.length||1;s.setFloat2("invViewport",1/(i/_),1/c);let h=1e3;if(o){const l=o.getProjectionMatrix().m[5];o.fovMode==$t.FOVMODE_VERTICAL_FIXED?h=c*l/2:h=i*l/2}if(s.setFloat2("focal",h,h),s.setVector3("viewDirectionFactor",f.viewDirectionFactor),s.setFloat("kernelSize",a&&a.kernelSize?a.kernelSize:R.KernelSize),r.bindEyePosition(s,"eyePosition",!0),f.covariancesATexture){const l=f.covariancesATexture.getSize();if(s.setFloat2("dataTextureSize",l.width,l.height),s.setTexture("covariancesATexture",f.covariancesATexture),s.setTexture("covariancesBTexture",f.covariancesBTexture),s.setTexture("centersTexture",f.centersTexture),s.setTexture("colorsTexture",f.colorsTexture),f.shTextures)for(let d=0;d<f.shTextures?.length;d++)s.setTexture(`shTexture${d}`,f.shTextures[d])}}bindForSubMesh(e,s,r){const n=this.getScene(),o=r.materialDefines;if(!o)return;const i=r.effect;if(!i)return;this._activeEffect=i,s.getMeshUniformBuffer().bindToEffect(i,"Mesh"),s.transferToEffect(e),this._mustRebind(n,i,r,s.visibility)?(this.bindView(i),this.bindViewProjection(i),R.BindEffect(s,this._activeEffect,n),qt(i,this,n)):n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0),Kt(n,s,i),this.useLogarithmicDepth&&Qt(o,i,n),this._afterBind(s,this._activeEffect,r)}static _MakeGaussianSplattingShadowDepthWrapper(e,s){const r=new is("gaussianSplattingDepth",e,{vertex:"gaussianSplattingDepth",fragment:"gaussianSplattingDepth"},{attributes:R._Attribs,uniforms:R._Uniforms,samplers:R._Samplers,uniformBuffers:R._UniformBuffers,shaderLanguage:s}),n=new us(r,e,{standalone:!0});return r.onBindObservable.add(o=>{const i=r.getEffect(),c=o.material,f=o;o.getMeshUniformBuffer().bindToEffect(i,"Mesh"),r.bindView(i),r.bindViewProjection(i);const a=e.getEngine().getRenderWidth(),_=e.getEngine().getRenderHeight();i.setFloat2("invViewport",1/a,1/_);const l=e.getProjectionMatrix().m[5],d=a*l/2;if(i.setFloat2("focal",d,d),i.setFloat("kernelSize",c&&c.kernelSize?c.kernelSize:R.KernelSize),f.covariancesATexture){const x=f.covariancesATexture.getSize();i.setFloat2("dataTextureSize",x.width,x.height),i.setTexture("covariancesATexture",f.covariancesATexture),i.setTexture("covariancesBTexture",f.covariancesBTexture),i.setTexture("centersTexture",f.centersTexture),i.setTexture("colorsTexture",f.colorsTexture)}}),n}clone(e){return _t.Clone(()=>new R(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,s,r){return _t.Parse(()=>new R(e.name,s),e,s,r)}}R.KernelSize=.3;R.Compensation=!1;R._Attribs=[K.PositionKind,"splatIndex"];R._Samplers=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture","shTexture0","shTexture1","shTexture2"];R._UniformBuffers=["Scene","Mesh"];R._Uniforms=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","invViewport","dataTextureSize","focal","eyePosition","kernelSize","viewDirectionFactor"];Lt("BABYLON.GaussianSplattingMaterial",R);const Is=es,V={...Yt,TwoPi:Math.PI*2,Sign:Math.sign,Log2:Math.log2,HCF:Is},J=(t,e)=>{const s=(1<<e)-1;return(t&s)/s},At=(t,e)=>{e.x=J(t>>>21,11),e.y=J(t>>>11,10),e.z=J(t,11)},Hs=(t,e)=>{e[0]=J(t>>>24,8)*255,e[1]=J(t>>>16,8)*255,e[2]=J(t>>>8,8)*255,e[3]=J(t,8)*255},Rs=(t,e)=>{const s=1/(Math.sqrt(2)*.5),r=(J(t>>>20,10)-.5)*s,n=(J(t>>>10,10)-.5)*s,o=(J(t,10)-.5)*s,i=Math.sqrt(1-(r*r+n*n+o*o));switch(t>>>30){case 0:e.set(i,r,n,o);break;case 1:e.set(r,i,n,o);break;case 2:e.set(r,n,i,o);break;case 3:e.set(r,n,o,i);break}};var Et;(function(t){t[t.FLOAT=0]="FLOAT",t[t.INT=1]="INT",t[t.UINT=2]="UINT",t[t.DOUBLE=3]="DOUBLE",t[t.UCHAR=4]="UCHAR",t[t.UNDEFINED=5]="UNDEFINED"})(Et||(Et={}));var Dt;(function(t){t[t.MIN_X=0]="MIN_X",t[t.MIN_Y=1]="MIN_Y",t[t.MIN_Z=2]="MIN_Z",t[t.MAX_X=3]="MAX_X",t[t.MAX_Y=4]="MAX_Y",t[t.MAX_Z=5]="MAX_Z",t[t.MIN_SCALE_X=6]="MIN_SCALE_X",t[t.MIN_SCALE_Y=7]="MIN_SCALE_Y",t[t.MIN_SCALE_Z=8]="MIN_SCALE_Z",t[t.MAX_SCALE_X=9]="MAX_SCALE_X",t[t.MAX_SCALE_Y=10]="MAX_SCALE_Y",t[t.MAX_SCALE_Z=11]="MAX_SCALE_Z",t[t.PACKED_POSITION=12]="PACKED_POSITION",t[t.PACKED_ROTATION=13]="PACKED_ROTATION",t[t.PACKED_SCALE=14]="PACKED_SCALE",t[t.PACKED_COLOR=15]="PACKED_COLOR",t[t.X=16]="X",t[t.Y=17]="Y",t[t.Z=18]="Z",t[t.SCALE_0=19]="SCALE_0",t[t.SCALE_1=20]="SCALE_1",t[t.SCALE_2=21]="SCALE_2",t[t.DIFFUSE_RED=22]="DIFFUSE_RED",t[t.DIFFUSE_GREEN=23]="DIFFUSE_GREEN",t[t.DIFFUSE_BLUE=24]="DIFFUSE_BLUE",t[t.OPACITY=25]="OPACITY",t[t.F_DC_0=26]="F_DC_0",t[t.F_DC_1=27]="F_DC_1",t[t.F_DC_2=28]="F_DC_2",t[t.F_DC_3=29]="F_DC_3",t[t.ROT_0=30]="ROT_0",t[t.ROT_1=31]="ROT_1",t[t.ROT_2=32]="ROT_2",t[t.ROT_3=33]="ROT_3",t[t.MIN_COLOR_R=34]="MIN_COLOR_R",t[t.MIN_COLOR_G=35]="MIN_COLOR_G",t[t.MIN_COLOR_B=36]="MIN_COLOR_B",t[t.MAX_COLOR_R=37]="MAX_COLOR_R",t[t.MAX_COLOR_G=38]="MAX_COLOR_G",t[t.MAX_COLOR_B=39]="MAX_COLOR_B",t[t.SH_0=40]="SH_0",t[t.SH_1=41]="SH_1",t[t.SH_2=42]="SH_2",t[t.SH_3=43]="SH_3",t[t.SH_4=44]="SH_4",t[t.SH_5=45]="SH_5",t[t.SH_6=46]="SH_6",t[t.SH_7=47]="SH_7",t[t.SH_8=48]="SH_8",t[t.SH_9=49]="SH_9",t[t.SH_10=50]="SH_10",t[t.SH_11=51]="SH_11",t[t.SH_12=52]="SH_12",t[t.SH_13=53]="SH_13",t[t.SH_14=54]="SH_14",t[t.SH_15=55]="SH_15",t[t.SH_16=56]="SH_16",t[t.SH_17=57]="SH_17",t[t.SH_18=58]="SH_18",t[t.SH_19=59]="SH_19",t[t.SH_20=60]="SH_20",t[t.SH_21=61]="SH_21",t[t.SH_22=62]="SH_22",t[t.SH_23=63]="SH_23",t[t.SH_24=64]="SH_24",t[t.SH_25=65]="SH_25",t[t.SH_26=66]="SH_26",t[t.SH_27=67]="SH_27",t[t.SH_28=68]="SH_28",t[t.SH_29=69]="SH_29",t[t.SH_30=70]="SH_30",t[t.SH_31=71]="SH_31",t[t.SH_32=72]="SH_32",t[t.SH_33=73]="SH_33",t[t.SH_34=74]="SH_34",t[t.SH_35=75]="SH_35",t[t.SH_36=76]="SH_36",t[t.SH_37=77]="SH_37",t[t.SH_38=78]="SH_38",t[t.SH_39=79]="SH_39",t[t.SH_40=80]="SH_40",t[t.SH_41=81]="SH_41",t[t.SH_42=82]="SH_42",t[t.SH_43=83]="SH_43",t[t.SH_44=84]="SH_44",t[t.UNDEFINED=85]="UNDEFINED"})(Dt||(Dt={}));class H extends Pe{get viewDirectionFactor(){return this._viewDirectionFactor}get shDegree(){return this._shDegree}get splatCount(){return this._splatIndex?.length}get splatsData(){return this._splatsData}get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}get shTextures(){return this._shTextures}get kernelSize(){return this._material instanceof R?this._material.kernelSize:0}get compensation(){return this._material instanceof R?this._material.compensation:!1}set material(e){this._material=e,this._material.backFaceCulling=!0,this._material.cullBackFaces=!1,e.resetDrawCache()}get material(){return this._material}constructor(e,s=null,r=null,n=!1){super(e,r),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=Ce.Identity(),this._canPostToWorker=!0,this._readyToDisplay=!1,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._splatPositions=null,this._splatIndex=null,this._shTextures=null,this._splatsData=null,this._sh=null,this._keepInRam=!1,this._delayedTextureUpdate=null,this._oldDirection=new M,this._useRGBACovariants=!1,this._material=null,this._tmpCovariances=[0,0,0,0,0,0],this._sortIsDirty=!1,this._shDegree=0,this._viewDirectionFactor=new M(1,1,-1);const o=new Ne;o.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],o.indices=[0,1,2,0,2,3],o.applyToMesh(this),this.subMeshes=[],new ts(0,0,4,0,6,this),this.setEnabled(!1),this._useRGBACovariants=!this.getEngine().isWebGPU&&this.getEngine().version===1,this._keepInRam=n,s&&this.loadFileAsync(s),this._material=new R(this.name+"_material",this._scene)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}isReady(e=!1){return super.isReady(e,!0)?this._readyToDisplay?!0:(this._postToWorker(!0),!1):!1}_postToWorker(e=!1){const s=this.getScene().getFrameId();if((e||s!==this._frameIdLastUpdate)&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){const r=this._scene.activeCamera.getViewMatrix();this.getWorldMatrix().multiplyToRef(r,this._modelViewMatrix),r.invertToRef(Z.Matrix[0]),this.getWorldMatrix().multiplyToRef(Z.Matrix[0],Z.Matrix[1]),M.TransformNormalToRef(M.Forward(this._scene.useRightHandedSystem),Z.Matrix[1],Z.Vector3[2]),Z.Vector3[2].normalize();const n=M.Dot(Z.Vector3[2],this._oldDirection);(e||Math.abs(n-1)>=.01)&&(this._oldDirection.copyFrom(Z.Vector3[2]),this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}}render(e,s,r){return this._postToWorker(),super.render(e,s,r)}static _TypeNameToEnum(e){switch(e){case"float":return 0;case"int":return 1;case"uint":return 2;case"double":return 3;case"uchar":return 4}return 5}static _ValueNameToEnum(e){switch(e){case"min_x":return 0;case"min_y":return 1;case"min_z":return 2;case"max_x":return 3;case"max_y":return 4;case"max_z":return 5;case"min_scale_x":return 6;case"min_scale_y":return 7;case"min_scale_z":return 8;case"max_scale_x":return 9;case"max_scale_y":return 10;case"max_scale_z":return 11;case"packed_position":return 12;case"packed_rotation":return 13;case"packed_scale":return 14;case"packed_color":return 15;case"x":return 16;case"y":return 17;case"z":return 18;case"scale_0":return 19;case"scale_1":return 20;case"scale_2":return 21;case"diffuse_red":case"red":return 22;case"diffuse_green":case"green":return 23;case"diffuse_blue":case"blue":return 24;case"f_dc_0":return 26;case"f_dc_1":return 27;case"f_dc_2":return 28;case"f_dc_3":return 29;case"opacity":return 25;case"rot_0":return 30;case"rot_1":return 31;case"rot_2":return 32;case"rot_3":return 33;case"min_r":return 34;case"min_g":return 35;case"min_b":return 36;case"max_r":return 37;case"max_g":return 38;case"max_b":return 39;case"f_rest_0":return 40;case"f_rest_1":return 41;case"f_rest_2":return 42;case"f_rest_3":return 43;case"f_rest_4":return 44;case"f_rest_5":return 45;case"f_rest_6":return 46;case"f_rest_7":return 47;case"f_rest_8":return 48;case"f_rest_9":return 49;case"f_rest_10":return 50;case"f_rest_11":return 51;case"f_rest_12":return 52;case"f_rest_13":return 53;case"f_rest_14":return 54;case"f_rest_15":return 55;case"f_rest_16":return 56;case"f_rest_17":return 57;case"f_rest_18":return 58;case"f_rest_19":return 59;case"f_rest_20":return 60;case"f_rest_21":return 61;case"f_rest_22":return 62;case"f_rest_23":return 63;case"f_rest_24":return 64;case"f_rest_25":return 65;case"f_rest_26":return 66;case"f_rest_27":return 67;case"f_rest_28":return 68;case"f_rest_29":return 69;case"f_rest_30":return 70;case"f_rest_31":return 71;case"f_rest_32":return 72;case"f_rest_33":return 73;case"f_rest_34":return 74;case"f_rest_35":return 75;case"f_rest_36":return 76;case"f_rest_37":return 77;case"f_rest_38":return 78;case"f_rest_39":return 79;case"f_rest_40":return 80;case"f_rest_41":return 81;case"f_rest_42":return 82;case"f_rest_43":return 83;case"f_rest_44":return 84}return 85}static ParseHeader(e){const s=new Uint8Array(e),r=new TextDecoder().decode(s.slice(0,1024*10)),n=`end_header
`,o=r.indexOf(n);if(o<0||!r)return null;const i=parseInt(/element vertex (\d+)\n/.exec(r)[1]),c=/element chunk (\d+)\n/.exec(r);let f=0;c&&(f=parseInt(c[1]));let a=0,_=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let l;(function(g){g[g.Vertex=0]="Vertex",g[g.Chunk=1]="Chunk",g[g.SH=2]="SH"})(l||(l={}));let d=1;const x=[],C=[],S=r.slice(0,o).split(`
`);let u=0;for(const g of S)if(g.startsWith("property ")){const[,y,A]=g.split(" "),w=H._ValueNameToEnum(A);w!=85&&(w>=84?u=3:w>=64?u=2:w>=48&&(u=1));const D=H._TypeNameToEnum(y);d==1?(C.push({value:w,type:D,offset:_}),_+=h[y]):d==0?(x.push({value:w,type:D,offset:a}),a+=h[y]):d==2&&x.push({value:w,type:D,offset:a}),h[y]||de.Warn(`Unsupported property type: ${y}.`)}else if(g.startsWith("element ")){const[,y]=g.split(" ");y=="chunk"?d=1:y=="vertex"?d=0:y=="sh"&&(d=2)}const b=new DataView(e,o+n.length),m=new ArrayBuffer(H._RowOutputLength*i);let p=null,v=0;return u&&(v=((u+1)*(u+1)-1)*3,p=new ArrayBuffer(v*i)),{vertexCount:i,chunkCount:f,rowVertexLength:a,rowChunkLength:_,vertexProperties:x,chunkProperties:C,dataView:b,buffer:m,shDegree:u,shCoefficientCount:v,shBuffer:p}}static _GetCompressedChunks(e,s){if(!e.chunkCount)return null;const r=e.dataView,n=new Array(e.chunkCount);for(let o=0;o<e.chunkCount;o++){const i={min:new M,max:new M,minScale:new M,maxScale:new M,minColor:new M(0,0,0),maxColor:new M(1,1,1)};n[o]=i;for(let c=0;c<e.chunkProperties.length;c++){const f=e.chunkProperties[c];let a;switch(f.type){case 0:a=r.getFloat32(f.offset+s.value,!0);break;default:continue}switch(f.value){case 0:i.min.x=a;break;case 1:i.min.y=a;break;case 2:i.min.z=a;break;case 3:i.max.x=a;break;case 4:i.max.y=a;break;case 5:i.max.z=a;break;case 6:i.minScale.x=a;break;case 7:i.minScale.y=a;break;case 8:i.minScale.z=a;break;case 9:i.maxScale.x=a;break;case 10:i.maxScale.y=a;break;case 11:i.maxScale.z=a;break;case 34:i.minColor.x=a;break;case 35:i.minColor.y=a;break;case 36:i.minColor.z=a;break;case 37:i.maxColor.x=a;break;case 38:i.maxColor.y=a;break;case 39:i.maxColor.z=a;break}}s.value+=e.rowChunkLength}return n}static _GetSplat(e,s,r,n){const o=Z.Quaternion[0],i=Z.Vector3[0],c=H._RowOutputLength,f=e.buffer,a=e.dataView,_=new Float32Array(f,s*c,3),h=new Float32Array(f,s*c+12,3),l=new Uint8ClampedArray(f,s*c+24,4),d=new Uint8ClampedArray(f,s*c+28,4);let x=null;e.shBuffer&&(x=new Uint8ClampedArray(e.shBuffer,s*e.shCoefficientCount,e.shCoefficientCount));const C=s>>8;let S=255,u=0,b=0,m=0;const p=[];for(let v=0;v<e.vertexProperties.length;v++){const g=e.vertexProperties[v];let y;switch(g.type){case 0:y=a.getFloat32(n.value+g.offset,!0);break;case 1:y=a.getInt32(n.value+g.offset,!0);break;case 2:y=a.getUint32(n.value+g.offset,!0);break;case 3:y=a.getFloat64(n.value+g.offset,!0);break;case 4:y=a.getUint8(n.value+g.offset);break;default:continue}switch(g.value){case 12:{const A=r[C];At(y,i),_[0]=V.Lerp(A.min.x,A.max.x,i.x),_[1]=V.Lerp(A.min.y,A.max.y,i.y),_[2]=V.Lerp(A.min.z,A.max.z,i.z)}break;case 13:Rs(y,o),S=o.x,u=o.y,b=o.z,m=o.w;break;case 14:{const A=r[C];At(y,i),h[0]=Math.exp(V.Lerp(A.minScale.x,A.maxScale.x,i.x)),h[1]=Math.exp(V.Lerp(A.minScale.y,A.maxScale.y,i.y)),h[2]=Math.exp(V.Lerp(A.minScale.z,A.maxScale.z,i.z))}break;case 15:{const A=r[C];Hs(y,l),l[0]=V.Lerp(A.minColor.x,A.maxColor.x,l[0]/255)*255,l[1]=V.Lerp(A.minColor.y,A.maxColor.y,l[1]/255)*255,l[2]=V.Lerp(A.minColor.z,A.maxColor.z,l[2]/255)*255}break;case 16:_[0]=y;break;case 17:_[1]=y;break;case 18:_[2]=y;break;case 19:h[0]=Math.exp(y);break;case 20:h[1]=Math.exp(y);break;case 21:h[2]=Math.exp(y);break;case 22:l[0]=y;break;case 23:l[1]=y;break;case 24:l[2]=y;break;case 26:l[0]=(.5+H._SH_C0*y)*255;break;case 27:l[1]=(.5+H._SH_C0*y)*255;break;case 28:l[2]=(.5+H._SH_C0*y)*255;break;case 29:l[3]=(.5+H._SH_C0*y)*255;break;case 25:l[3]=1/(1+Math.exp(-y))*255;break;case 30:S=y;break;case 31:u=y;break;case 32:b=y;break;case 33:m=y;break}if(x&&g.value>=40&&g.value<=84){const A=g.value-40;if(g.type==4&&e.chunkCount){const w=a.getUint8(e.rowChunkLength*e.chunkCount+e.vertexCount*e.rowVertexLength+s*e.shCoefficientCount+A);p[A]=(w*(8/255)-4)*127.5+127.5}else{const w=V.Clamp(y*127.5+127.5,0,255);p[A]=w}}}if(x){const v=e.shDegree==1?3:e.shDegree==2?8:15;for(let g=0;g<v;g++)x[g*3+0]=p[g],x[g*3+1]=p[g+v],x[g*3+2]=p[g+v*2]}o.set(u,b,m,S),o.normalize(),d[0]=o.w*127.5+127.5,d[1]=o.x*127.5+127.5,d[2]=o.y*127.5+127.5,d[3]=o.z*127.5+127.5,n.value+=e.rowVertexLength}static*ConvertPLYWithSHToSplat(e,s=!1){const r=H.ParseHeader(e);if(!r)return{buffer:e};const n={value:0},o=H._GetCompressedChunks(r,n);for(let c=0;c<r.vertexCount;c++)H._GetSplat(r,c,o,n),c%H._PlyConversionBatchSize===0&&s&&(yield);let i=null;if(r.shDegree&&r.shBuffer){const c=Math.ceil(r.shCoefficientCount/16);let f=0;const a=new Uint8Array(r.shBuffer);i=[];const _=r.vertexCount,h=Ue.LastCreatedEngine;if(h){const l=h.getCaps().maxTextureSize,d=Math.ceil(_/l);for(let x=0;x<c;x++){const C=new Uint8Array(d*l*4*4);i.push(C)}for(let x=0;x<_;x++)for(let C=0;C<r.shCoefficientCount;C++){const S=a[f++],u=Math.floor(C/16),b=i[u],m=C%16,p=x*16;b[m+p]=S}}}return{buffer:r.buffer,sh:i}}static*ConvertPLYToSplat(e,s=!1){const r=H.ParseHeader(e);if(!r)return e;const n={value:0},o=H._GetCompressedChunks(r,n);for(let i=0;i<r.vertexCount;i++)H._GetSplat(r,i,o,n),i%H._PlyConversionBatchSize===0&&s&&(yield);return r.buffer}static async ConvertPLYToSplatAsync(e){return await Me(H.ConvertPLYToSplat(e,!0),Ie())}static async ConvertPLYWithSHToSplatAsync(e){return await Me(H.ConvertPLYWithSHToSplat(e,!0),Ie())}async loadDataAsync(e){return await this.updateDataAsync(e)}async loadFileAsync(e){const s=await Rt.LoadFileAsync(e,!0),r=await H.ConvertPLYWithSHToSplatAsync(s);await this.updateDataAsync(r.buffer,r.sh)}dispose(e){if(this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._shTextures)for(const s of this._shTextures)s.dispose();this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._shTextures=null,this._worker?.terminate(),this._worker=null,super.dispose(e,!0)}_copyTextures(e){if(this._covariancesATexture=e.covariancesATexture?.clone(),this._covariancesBTexture=e.covariancesBTexture?.clone(),this._centersTexture=e.centersTexture?.clone(),this._colorsTexture=e.colorsTexture?.clone(),e._shTextures){this._shTextures=[];for(const s of this._shTextures)this._shTextures?.push(s.clone())}}clone(e=""){const s=new H(e,void 0,this.getScene());s._copySource(this),s.makeGeometryUnique(),s._vertexCount=this._vertexCount,s._copyTextures(this),s._modelViewMatrix=Ce.Identity(),s._splatPositions=this._splatPositions,s._readyToDisplay=!1,s._instanciateWorker();const r=this.getBoundingInfo();return s.getBoundingInfo().reConstruct(r.minimum,r.maximum,this.getWorldMatrix()),s.forcedInstanceCount=s._vertexCount,s.setEnabled(!0),s}_makeSplat(e,s,r,n,o,i,c,f){const a=Z.Matrix[0],_=Z.Matrix[1],h=Z.Quaternion[0],l=this._useRGBACovariants?4:2,d=s[8*e+0],x=-s[8*e+1],C=s[8*e+2];this._splatPositions[4*e+0]=d,this._splatPositions[4*e+1]=x,this._splatPositions[4*e+2]=C,c.minimizeInPlaceFromFloats(d,x,C),f.maximizeInPlaceFromFloats(d,x,C),h.set((r[32*e+28+1]-127.5)/127.5,(r[32*e+28+2]-127.5)/127.5,(r[32*e+28+3]-127.5)/127.5,-(r[32*e+28+0]-127.5)/127.5),h.normalize(),h.toRotationMatrix(a),Ce.ScalingToRef(s[8*e+3+0]*2,s[8*e+3+1]*2,s[8*e+3+2]*2,_);const S=a.multiplyToRef(_,Z.Matrix[0]).m,u=this._tmpCovariances;u[0]=S[0]*S[0]+S[1]*S[1]+S[2]*S[2],u[1]=S[0]*S[4]+S[1]*S[5]+S[2]*S[6],u[2]=S[0]*S[8]+S[1]*S[9]+S[2]*S[10],u[3]=S[4]*S[4]+S[5]*S[5]+S[6]*S[6],u[4]=S[4]*S[8]+S[5]*S[9]+S[6]*S[10],u[5]=S[8]*S[8]+S[9]*S[9]+S[10]*S[10];let b=-1e4;for(let p=0;p<6;p++)b=Math.max(b,Math.abs(u[p]));this._splatPositions[4*e+3]=b;const m=b;n[e*4+0]=le(u[0]/m),n[e*4+1]=le(u[1]/m),n[e*4+2]=le(u[2]/m),n[e*4+3]=le(u[3]/m),o[e*l+0]=le(u[4]/m),o[e*l+1]=le(u[5]/m),i[e*4+0]=r[32*e+24+0],i[e*4+1]=r[32*e+24+1],i[e*4+2]=r[32*e+24+2],i[e*4+3]=r[32*e+24+3]}_updateTextures(e,s,r,n){const o=this._getTextureSize(this._vertexCount),i=(_,h,l,d)=>new we(_,h,l,d,this._scene,!1,!1,2,1),c=(_,h,l,d)=>new we(_,h,l,d,this._scene,!1,!1,2,0),f=(_,h,l,d)=>new we(_,h,l,d,this._scene,!1,!1,1,7),a=(_,h,l,d)=>new we(_,h,l,d,this._scene,!1,!1,2,2);if(this._covariancesATexture){this._delayedTextureUpdate={covA:e,covB:s,colors:r,centers:this._splatPositions,sh:n};const _=Float32Array.from(this._splatPositions),h=this._vertexCount;this._worker.postMessage({positions:_,vertexCount:h},[_.buffer]),this._postToWorker(!0)}else{if(this._covariancesATexture=a(e,o.x,o.y,5),this._covariancesBTexture=a(s,o.x,o.y,this._useRGBACovariants?5:7),this._centersTexture=i(this._splatPositions,o.x,o.y,5),this._colorsTexture=c(r,o.x,o.y,5),n){this._shTextures=[];for(const _ of n){const h=new Uint32Array(_.buffer),l=f(h,o.x,o.y,11);l.wrapU=0,l.wrapV=0,this._shTextures.push(l)}}this._instanciateWorker()}}*_updateData(e,s,r){this._covariancesATexture||(this._readyToDisplay=!1);const n=new Uint8Array(e),o=new Float32Array(n.buffer);this._keepInRam&&(this._splatsData=e,r&&(this._sh=r));const i=n.length/H._RowOutputLength;i!=this._vertexCount&&this._updateSplatIndexBuffer(i),this._vertexCount=i,this._shDegree=r?r.length:0;const c=this._getTextureSize(i),f=c.x*c.y,a=H.ProgressiveUpdateAmount??c.y,_=c.x*a;this._splatPositions=new Float32Array(4*f);const h=new Uint16Array(f*4),l=new Uint16Array((this._useRGBACovariants?4:2)*f),d=new Uint8Array(f*4),x=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),C=new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(H.ProgressiveUpdateAmount){this._updateTextures(h,l,d,r),this.setEnabled(!0);const S=Math.ceil(c.y/a);for(let m=0;m<S;m++){const p=m*a,v=p*c.x;for(let g=0;g<_;g++)this._makeSplat(v+g,o,n,h,l,d,x,C);this._updateSubTextures(this._splatPositions,h,l,d,p,Math.min(a,c.y-p)),this.getBoundingInfo().reConstruct(x,C,this.getWorldMatrix()),s&&(yield)}const u=Float32Array.from(this._splatPositions),b=this._vertexCount;this._worker.postMessage({positions:u,vertexCount:b},[u.buffer]),this._sortIsDirty=!0}else{for(let S=0;S<i;S++)this._makeSplat(S,o,n,h,l,d,x,C),s&&S%H._SplatBatchSize===0&&(yield);this._updateTextures(h,l,d,r),this.getBoundingInfo().reConstruct(x,C,this.getWorldMatrix()),this.setEnabled(!0)}this._postToWorker(!0)}async updateDataAsync(e,s){return await Me(this._updateData(e,!0,s),Ie())}updateData(e,s){ss(this._updateData(e,!1,s))}refreshBoundingInfo(){return this.thinInstanceRefreshBoundingInfo(!1),this}_updateSplatIndexBuffer(e){(!this._splatIndex||e>this._splatIndex.length)&&(this._splatIndex=new Float32Array(e),this.thinInstanceSetBuffer("splatIndex",this._splatIndex,1,!1)),this.forcedInstanceCount=e}_updateSubTextures(e,s,r,n,o,i,c){const f=(u,b,m,p,v)=>{this.getEngine().updateTextureData(u.getInternalTexture(),b,0,p,m,v,0,0,!1)},a=this._getTextureSize(this._vertexCount),_=this._useRGBACovariants?4:2,h=o*a.x,l=i*a.x,d=new Uint16Array(s.buffer,h*4*Uint16Array.BYTES_PER_ELEMENT,l*4),x=new Uint16Array(r.buffer,h*_*Uint16Array.BYTES_PER_ELEMENT,l*_),C=new Uint8Array(n.buffer,h*4,l*4),S=new Float32Array(e.buffer,h*4*Float32Array.BYTES_PER_ELEMENT,l*4);if(f(this._covariancesATexture,d,a.x,o,i),f(this._covariancesBTexture,x,a.x,o,i),f(this._centersTexture,S,a.x,o,i),f(this._colorsTexture,C,a.x,o,i),c)for(let u=0;u<c.length;u++){const m=new Uint8Array(this._sh[u].buffer,h*4,l*4);f(this._shTextures[u],m,a.x,o,i)}}_instanciateWorker(){if(!this._vertexCount)return;this._updateSplatIndexBuffer(this._vertexCount),this._worker?.terminate(),this._worker=new Worker(URL.createObjectURL(new Blob(["(",H._CreateWorker.toString(),")(self)"],{type:"application/javascript"}))),this._depthMix=new BigInt64Array(this._vertexCount);const e=Float32Array.from(this._splatPositions),s=this._vertexCount;this._worker.postMessage({positions:e,vertexCount:s},[e.buffer]),this._worker.onmessage=r=>{this._depthMix=r.data.depthMix;const n=new Uint32Array(r.data.depthMix.buffer);if(this._splatIndex)for(let o=0;o<this._vertexCount;o++)this._splatIndex[o]=n[2*o];if(this._delayedTextureUpdate){const o=this._getTextureSize(s);this._updateSubTextures(this._delayedTextureUpdate.centers,this._delayedTextureUpdate.covA,this._delayedTextureUpdate.covB,this._delayedTextureUpdate.colors,0,o.y,this._delayedTextureUpdate.sh),this._delayedTextureUpdate=null}this.thinInstanceBufferUpdated("splatIndex"),this._canPostToWorker=!0,this._readyToDisplay=!0,this._sortIsDirty&&(this._postToWorker(!0),this._sortIsDirty=!1)}}_getTextureSize(e){const s=this._scene.getEngine(),r=s.getCaps().maxTextureSize;let n=1;if(s.version===1&&!s.isWebGPU)for(;r*n<e;)n*=2;else n=Math.ceil(e/r);return n>r&&(de.Error("GaussianSplatting texture size: ("+r+", "+n+"), maxTextureSize: "+r),n=r),new re(r,n)}}H._RowOutputLength=32;H._SH_C0=.28209479177387814;H._SplatBatchSize=327680;H._PlyConversionBatchSize=32768;H.ProgressiveUpdateAmount=0;H._CreateWorker=function(t){let e=0,s,r,n,o;t.onmessage=i=>{if(i.data.positions)s=i.data.positions,e=i.data.vertexCount;else{const c=i.data.view;if(!s||!c)throw new Error("positions or view is not defined!");r=i.data.depthMix,n=new Uint32Array(r.buffer),o=new Float32Array(r.buffer);for(let a=0;a<e;a++)n[2*a]=a;let f=-1;i.data.useRightHandedSystem&&(f=1);for(let a=0;a<e;a++)o[2*a+1]=1e4+(c[2]*s[4*a+0]+c[6]*s[4*a+1]+c[10]*s[4*a+2])*f;r.sort(),t.postMessage({depthMix:r},[r.buffer])}}};class ks{constructor(e,s,r,n,o){this.idx=0,this.color=new L(1,1,1,1),this.position=M.Zero(),this.rotation=M.Zero(),this.uv=new re(0,0),this.velocity=M.Zero(),this.pivot=M.Zero(),this.translateFromPivot=!1,this._pos=0,this._ind=0,this.groupId=0,this.idxInGroup=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=M.Zero(),this.idx=e,this._group=s,this.groupId=r,this.idxInGroup=n,this._pcs=o}get size(){return this.size}set size(e){this.size=e}get quaternion(){return this.rotationQuaternion}set quaternion(e){this.rotationQuaternion=e}intersectsMesh(e,s){if(!e.hasBoundingInfo)return!1;if(!this._pcs.mesh)throw new Error("Point Cloud System doesnt contain the Mesh");if(s)return e.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));const r=e.getBoundingInfo().boundingBox,n=r.maximumWorld.x,o=r.minimumWorld.x,i=r.maximumWorld.y,c=r.minimumWorld.y,f=r.maximumWorld.z,a=r.minimumWorld.z,_=this.position.x+this._pcs.mesh.position.x,h=this.position.y+this._pcs.mesh.position.y,l=this.position.z+this._pcs.mesh.position.z;return o<=_&&_<=n&&c<=h&&h<=i&&a<=l&&l<=f}getRotationMatrix(e){let s;if(this.rotationQuaternion)s=this.rotationQuaternion;else{s=Z.Quaternion[0];const r=this.rotation;rs.RotationYawPitchRollToRef(r.y,r.x,r.z,s)}s.toRotationMatrix(e)}}class Re{get groupID(){return this.groupId}set groupID(e){this.groupId=e}constructor(e,s){this.groupId=e,this._positionFunction=s}}var zt;(function(t){t[t.Color=2]="Color",t[t.UV=1]="UV",t[t.Random=0]="Random",t[t.Stated=3]="Stated"})(zt||(zt={}));class Fs{get positions(){return this._positions32}get colors(){return this._colors32}get uvs(){return this._uvs32}constructor(e,s,r,n){this.particles=new Array,this.nbParticles=0,this.counter=0,this.vars={},this._promises=[],this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._updatable=!0,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._groups=new Array,this._groupCounter=0,this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeBoundingBox=!1,this._isReady=!1,this.name=e,this._size=s,this._scene=r||Ue.LastCreatedScene,n&&n.updatable!==void 0?this._updatable=n.updatable:this._updatable=!0}async buildMeshAsync(e){return await Promise.all(this._promises),this._isReady=!0,await this._buildMeshAsync(e)}async _buildMeshAsync(e){this.nbParticles===0&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const s=new Ne;s.set(this._positions32,K.PositionKind),this._uvs32.length>0&&s.set(this._uvs32,K.UVKind);let r=0;this._colors32.length>0&&(r=1,s.set(this._colors32,K.ColorKind));const n=new Pe(this.name,this._scene);s.applyToMesh(n,this._updatable),this.mesh=n,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let o=e;return o||(o=new ls("point cloud material",this._scene),o.emissiveColor=new Se(r,r,r),o.disableLighting=!0,o.pointsCloud=!0,o.pointSize=this._size),n.material=o,n}_addParticle(e,s,r,n){const o=new ks(e,s,r,n,this);return this.particles.push(o),o}_randomUnitVector(e){e.position=new M(Math.random(),Math.random(),Math.random()),e.color=new L(1,1,1,1)}_getColorIndicesForCoord(e,s,r,n){const o=e._groupImageData,i=r*(n*4)+s*4,c=[i,i+1,i+2,i+3],f=c[0],a=c[1],_=c[2],h=c[3],l=o[f],d=o[a],x=o[_],C=o[h];return new L(l/255,d/255,x/255,C)}_setPointsColorOrUV(e,s,r,n,o,i,c,f){f=f??0,r&&e.updateFacetData();const _=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(K.PositionKind);const l=e.getIndices(),d=e.getVerticesData(K.UVKind+(f?f+1:"")),x=e.getVerticesData(K.ColorKind),C=M.Zero();e.computeWorldMatrix();const S=e.getWorldMatrix();if(!S.isIdentity()){h=h.slice(0);for(let X=0;X<h.length/3;X++)M.TransformCoordinatesFromFloatsToRef(h[3*X],h[3*X+1],h[3*X+2],S,C),h[3*X]=C.x,h[3*X+1]=C.y,h[3*X+2]=C.z}let u=0,b=0,m=0,p=0,v=0,g=0,y=0,A=0,w=0,D=0,O=0,T=0,B=0;const I=M.Zero(),U=M.Zero(),k=M.Zero(),P=M.Zero(),G=M.Zero();let j=0,z=0,E=0,$=0,Q=0,oe=0;const ee=re.Zero(),F=re.Zero(),We=re.Zero(),Ge=re.Zero(),je=re.Zero();let Xe=0,Ze=0,Ve=0,$e=0,qe=0,Ke=0,Qe=0,Je=0,Le=0,Ye=0,et=0,tt=0;const ue=he.Zero(),be=he.Zero(),st=he.Zero(),rt=he.Zero(),ot=he.Zero();let te=0,pe=0;c=c||0;let fe,_e,N=new he(0,0,0,0),Te=M.Zero(),Ae=M.Zero(),nt=M.Zero(),ne=0,it=M.Zero(),at=0,ct=0;const me=new cs(M.Zero(),new M(1,0,0));let Ee,xe=M.Zero();for(let X=0;X<l.length/3;X++){b=l[3*X],m=l[3*X+1],p=l[3*X+2],v=h[3*b],g=h[3*b+1],y=h[3*b+2],A=h[3*m],w=h[3*m+1],D=h[3*m+2],O=h[3*p],T=h[3*p+1],B=h[3*p+2],I.set(v,g,y),U.set(A,w,D),k.set(O,T,B),U.subtractToRef(I,P),k.subtractToRef(U,G),d&&(j=d[2*b],z=d[2*b+1],E=d[2*m],$=d[2*m+1],Q=d[2*p],oe=d[2*p+1],ee.set(j,z),F.set(E,$),We.set(Q,oe),F.subtractToRef(ee,Ge),We.subtractToRef(F,je)),x&&n&&(Xe=x[4*b],Ze=x[4*b+1],Ve=x[4*b+2],$e=x[4*b+3],qe=x[4*m],Ke=x[4*m+1],Qe=x[4*m+2],Je=x[4*m+3],Le=x[4*p],Ye=x[4*p+1],et=x[4*p+2],tt=x[4*p+3],ue.set(Xe,Ze,Ve,$e),be.set(qe,Ke,Qe,Je),st.set(Le,Ye,et,tt),be.subtractToRef(ue,rt),st.subtractToRef(be,ot));let De,lt,ht,ut,ft,ie,ae,ve;const dt=new Se(0,0,0),ge=new Se(0,0,0);let ce,q;for(let ze=0;ze<s._groupDensity[X];ze++)u=this.particles.length,this._addParticle(u,s,this._groupCounter,X+ze),q=this.particles[u],te=Math.sqrt(se(0,1)),pe=se(0,1),fe=I.add(P.scale(te)).add(G.scale(te*pe)),r&&(Te=e.getFacetNormal(X).normalize().scale(-1),Ae=P.clone().normalize(),nt=M.Cross(Te,Ae),ne=se(0,2*Math.PI),it=Ae.scale(Math.cos(ne)).add(nt.scale(Math.sin(ne))),ne=se(.1,Math.PI/2),xe=it.scale(Math.cos(ne)).add(Te.scale(Math.sin(ne))),me.origin=fe.add(xe.scale(1e-5)),me.direction=xe,me.length=_,Ee=me.intersectsMesh(e),Ee.hit&&(ct=Ee.pickedPoint.subtract(fe).length(),at=se(0,1)*ct,fe.addInPlace(xe.scale(at)))),q.position=fe.clone(),this._positions.push(q.position.x,q.position.y,q.position.z),n!==void 0?d&&(_e=ee.add(Ge.scale(te)).add(je.scale(te*pe)),n?o&&s._groupImageData!==null?(De=s._groupImgWidth,lt=s._groupImgHeight,ce=this._getColorIndicesForCoord(s,Math.round(_e.x*De),Math.round(_e.y*lt),De),q.color=ce,this._colors.push(ce.r,ce.g,ce.b,ce.a)):x?(N=ue.add(rt.scale(te)).add(ot.scale(te*pe)),q.color=new L(N.x,N.y,N.z,N.w),this._colors.push(N.x,N.y,N.z,N.w)):(N=ue.set(Math.random(),Math.random(),Math.random(),1),q.color=new L(N.x,N.y,N.z,N.w),this._colors.push(N.x,N.y,N.z,N.w)):(q.uv=_e.clone(),this._uvs.push(q.uv.x,q.uv.y))):(i?(dt.set(i.r,i.g,i.b),ht=se(-c,c),ut=se(-c,c),ve=dt.toHSV(),ft=ve.r,ie=ve.g+ht,ae=ve.b+ut,ie<0&&(ie=0),ie>1&&(ie=1),ae<0&&(ae=0),ae>1&&(ae=1),Se.HSVtoRGBToRef(ft,ie,ae,ge),N.set(ge.r,ge.g,ge.b,1)):N=ue.set(Math.random(),Math.random(),Math.random(),1),q.color=new L(N.x,N.y,N.z,N.w),this._colors.push(N.x,N.y,N.z,N.w))}}_colorFromTexture(e,s,r){if(e.material===null){de.Warn(e.name+"has no material."),s._groupImageData=null,this._setPointsColorOrUV(e,s,r,!0,!1);return}const o=e.material.getActiveTextures();if(o.length===0){de.Warn(e.name+"has no usable texture."),s._groupImageData=null,this._setPointsColorOrUV(e,s,r,!0,!1);return}const i=e.clone();i.setEnabled(!1),this._promises.push(new Promise(c=>{os.WhenAllReady(o,()=>{let f=s._textureNb;f<0&&(f=0),f>o.length-1&&(f=o.length-1);const a=()=>{s._groupImgWidth=o[f].getSize().width,s._groupImgHeight=o[f].getSize().height,this._setPointsColorOrUV(i,s,r,!0,!0,void 0,void 0,o[f].coordinatesIndex),i.dispose(),c()};s._groupImageData=null;const _=o[f].readPixels();_?_.then(h=>{s._groupImageData=h,a()}):a()})}))}_calculateDensity(e,s,r){let n,o,i,c,f,a,_,h,l,d,x,C;const S=M.Zero(),u=M.Zero(),b=M.Zero(),m=M.Zero(),p=M.Zero(),v=M.Zero();let g;const y=[];let A=0;const w=r.length/3;for(let T=0;T<w;T++)n=r[3*T],o=r[3*T+1],i=r[3*T+2],c=s[3*n],f=s[3*n+1],a=s[3*n+2],_=s[3*o],h=s[3*o+1],l=s[3*o+2],d=s[3*i],x=s[3*i+1],C=s[3*i+2],S.set(c,f,a),u.set(_,h,l),b.set(d,x,C),u.subtractToRef(S,m),b.subtractToRef(u,p),M.CrossToRef(m,p,v),g=.5*v.length(),A+=g,y[T]=A;const D=new Array(w);let O=e;for(let T=w-1;T>0;T--){const B=y[T];if(B===0)D[T]=0;else{const U=(B-y[T-1])/B*O,k=Math.floor(U),P=U-k,G=+(Math.random()<P),j=k+G;D[T]=j,O-=j}}return D[0]=O,D}addPoints(e,s=this._randomUnitVector){const r=new Re(this._groupCounter,s);let n,o=this.nbParticles;for(let i=0;i<e;i++)n=this._addParticle(o,r,this._groupCounter,i),r&&r._positionFunction&&r._positionFunction(n,o,i),this._positions.push(n.position.x,n.position.y,n.position.z),n.color&&this._colors.push(n.color.r,n.color.g,n.color.b,n.color.a),n.uv&&this._uvs.push(n.uv.x,n.uv.y),o++;return this.nbParticles+=e,this._groupCounter++,this._groupCounter}addSurfacePoints(e,s,r,n,o){let i=r||0;(isNaN(i)||i<0||i>3)&&(i=0);const c=e.getVerticesData(K.PositionKind),f=e.getIndices();this._groups.push(this._groupCounter);const a=new Re(this._groupCounter,null);switch(a._groupDensity=this._calculateDensity(s,c,f),i===2?a._textureNb=n||0:n=n||new L(1,1,1,1),i){case 2:this._colorFromTexture(e,a,!1);break;case 1:this._setPointsColorOrUV(e,a,!1,!1,!1);break;case 0:this._setPointsColorOrUV(e,a,!1);break;case 3:this._setPointsColorOrUV(e,a,!1,void 0,void 0,n,o);break}return this.nbParticles+=s,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,s,r,n,o){let i=r||0;(isNaN(i)||i<0||i>3)&&(i=0);const c=e.getVerticesData(K.PositionKind),f=e.getIndices();this._groups.push(this._groupCounter);const a=new Re(this._groupCounter,null);switch(a._groupDensity=this._calculateDensity(s,c,f),i===2?a._textureNb=n||0:n=n||new L(1,1,1,1),i){case 2:this._colorFromTexture(e,a,!0);break;case 1:this._setPointsColorOrUV(e,a,!0,!1,!1);break;case 0:this._setPointsColorOrUV(e,a,!0);break;case 3:this._setPointsColorOrUV(e,a,!0,void 0,void 0,n,o);break}return this.nbParticles+=s,this._groupCounter++,this._groupCounter-1}setParticles(e=0,s=this.nbParticles-1,r=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,s,r);const n=Z.Matrix[0],o=this.mesh,i=this._colors32,c=this._positions32,f=this._uvs32,a=Z.Vector3,_=a[5].copyFromFloats(1,0,0),h=a[6].copyFromFloats(0,1,0),l=a[7].copyFromFloats(0,0,1),d=a[8].setAll(Number.MAX_VALUE),x=a[9].setAll(-Number.MAX_VALUE);Ce.IdentityToRef(n);let C=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),s=s>=this.nbParticles?this.nbParticles-1:s,this._computeBoundingBox&&(e!=0||s!=this.nbParticles-1)){const m=this.mesh?.getBoundingInfo();m&&(d.copyFrom(m.minimum),x.copyFrom(m.maximum))}C=0;let S=0,u=0,b=0;for(let m=e;m<=s;m++){const p=this.particles[m];C=p.idx,S=3*C,u=4*C,b=2*C,this.updateParticle(p);const v=p._rotationMatrix,g=p.position,y=p._globalPosition;if(this._computeParticleRotation&&p.getRotationMatrix(n),p.parentId!==null){const z=this.particles[p.parentId],E=z._rotationMatrix,$=z._globalPosition,Q=g.x*E[1]+g.y*E[4]+g.z*E[7],oe=g.x*E[0]+g.y*E[3]+g.z*E[6],ee=g.x*E[2]+g.y*E[5]+g.z*E[8];if(y.x=$.x+oe,y.y=$.y+Q,y.z=$.z+ee,this._computeParticleRotation){const F=n.m;v[0]=F[0]*E[0]+F[1]*E[3]+F[2]*E[6],v[1]=F[0]*E[1]+F[1]*E[4]+F[2]*E[7],v[2]=F[0]*E[2]+F[1]*E[5]+F[2]*E[8],v[3]=F[4]*E[0]+F[5]*E[3]+F[6]*E[6],v[4]=F[4]*E[1]+F[5]*E[4]+F[6]*E[7],v[5]=F[4]*E[2]+F[5]*E[5]+F[6]*E[8],v[6]=F[8]*E[0]+F[9]*E[3]+F[10]*E[6],v[7]=F[8]*E[1]+F[9]*E[4]+F[10]*E[7],v[8]=F[8]*E[2]+F[9]*E[5]+F[10]*E[8]}}else if(y.x=0,y.y=0,y.z=0,this._computeParticleRotation){const z=n.m;v[0]=z[0],v[1]=z[1],v[2]=z[2],v[3]=z[4],v[4]=z[5],v[5]=z[6],v[6]=z[8],v[7]=z[9],v[8]=z[10]}const w=a[11];p.translateFromPivot?w.setAll(0):w.copyFrom(p.pivot);const D=a[0];D.copyFrom(p.position);const O=D.x-p.pivot.x,T=D.y-p.pivot.y,B=D.z-p.pivot.z;let I=O*v[0]+T*v[3]+B*v[6],U=O*v[1]+T*v[4]+B*v[7],k=O*v[2]+T*v[5]+B*v[8];I+=w.x,U+=w.y,k+=w.z;const P=c[S]=y.x+_.x*I+h.x*U+l.x*k,G=c[S+1]=y.y+_.y*I+h.y*U+l.y*k,j=c[S+2]=y.z+_.z*I+h.z*U+l.z*k;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(P,G,j),x.maximizeInPlaceFromFloats(P,G,j)),this._computeParticleColor&&p.color){const z=p.color,E=this._colors32;E[u]=z.r,E[u+1]=z.g,E[u+2]=z.b,E[u+3]=z.a}if(this._computeParticleTexture&&p.uv){const z=p.uv,E=this._uvs32;E[b]=z.x,E[b+1]=z.y}}return o&&(r&&(this._computeParticleColor&&o.updateVerticesData(K.ColorKind,i,!1,!1),this._computeParticleTexture&&o.updateVerticesData(K.UVKind,f,!1,!1),o.updateVerticesData(K.PositionKind,c,!1,!1)),this._computeBoundingBox&&(o.hasBoundingInfo?o.getBoundingInfo().reConstruct(d,x,o._worldMatrix):o.buildBoundingInfo(d,x,o._worldMatrix))),this.afterUpdateParticles(e,s,r),this}dispose(){this.mesh?.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const s=e/2;this.mesh.buildBoundingInfo(new M(-s,-s,-s),new M(s,s,s))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,s,r){}afterUpdateParticles(e,s,r){}}function Os(t,e,s){const r=new Uint8Array(t),n=new Uint32Array(t.slice(0,12)),o=n[2],i=r[12],c=r[13],f=r[14],a=r[15],_=n[1];if(a||n[0]!=1347635022||_!=2&&_!=3)return new Promise(w=>{w({mode:3,data:l,hasVertexColors:!1})});const h=32,l=new ArrayBuffer(h*o),d=1/(1<<c),x=new Int32Array(1),C=new Uint8Array(x.buffer),S=function(w,D){return C[0]=w[D+0],C[1]=w[D+1],C[2]=w[D+2],C[3]=w[D+2]&128?255:0,x[0]*d};let u=16;const b=new Float32Array(l),m=new Float32Array(l),p=new Uint8ClampedArray(l),v=new Uint8ClampedArray(l);let g=1,y=0;s.flipY||(g=-1,y=255);for(let w=0;w<o;w++)b[w*8+0]=S(r,u+0),b[w*8+1]=g*S(r,u+3),b[w*8+2]=g*S(r,u+6),u+=9;const A=.282;for(let w=0;w<o;w++){for(let D=0;D<3;D++){const T=(r[u+o+w*3+D]-127.5)/(.15*255);p[w*32+24+D]=V.Clamp((.5+A*T)*255,0,255)}p[w*32+24+3]=r[u+w]}u+=o*4;for(let w=0;w<o;w++)m[w*8+3+0]=Math.exp(r[u+0]/16-10),m[w*8+3+1]=Math.exp(r[u+1]/16-10),m[w*8+3+2]=Math.exp(r[u+2]/16-10),u+=3;if(_>=3){const w=Math.SQRT1_2;for(let D=0;D<o;D++){const O=[r[u+0],r[u+1],r[u+2],r[u+3]],T=O[0]+(O[1]<<8)+(O[2]<<16)+(O[3]<<24),B=511,I=[],U=T>>>30;let k=T,P=0;for(let z=3;z>=0;--z)if(z!==U){const E=k&B,$=k>>>9&1;k=k>>>10,I[z]=w*(E/B),$===1&&(I[z]=-I[z]),P+=I[z]*I[z]}const G=1-P;I[U]=Math.sqrt(Math.max(G,0)),I[1]*=g,I[2]*=g;const j=[3,0,1,2];for(let z=0;z<4;z++)v[D*32+28+z]=Math.round(127.5+I[j[z]]*127.5);u+=4}}else for(let w=0;w<o;w++){const D=r[u+0],O=r[u+1]*g+y,T=r[u+2]*g+y,B=D/127.5-1,I=O/127.5-1,U=T/127.5-1;v[w*32+28+1]=D,v[w*32+28+2]=O,v[w*32+28+3]=T;const k=1-(B*B+I*I+U*U);v[w*32+28+0]=127.5+Math.sqrt(k<0?0:k)*127.5,u+=3}if(i){const D=((i+1)*(i+1)-1)*3,O=Math.ceil(D/16);let T=u;const B=[],U=e.getEngine().getCaps().maxTextureSize,k=Math.ceil(o/U);for(let P=0;P<O;P++){const G=new Uint8Array(k*U*4*4);B.push(G)}for(let P=0;P<o;P++)for(let G=0;G<D;G++){const j=r[T++],z=Math.floor(G/16),E=B[z],$=G%16,Q=P*16;E[$+Q]=j}return new Promise(P=>{P({mode:0,data:l,hasVertexColors:!1,sh:B,trainedWithAntialiasing:!!f})})}return new Promise(w=>{w({mode:0,data:l,hasVertexColors:!1,trainedWithAntialiasing:!!f})})}const Mt=.28209479177387814;async function It(t,e,s){return await new Promise((n,o)=>{const i=s.createCanvasImage();if(!i)throw new Error("Failed to create ImageBitmap");i.onload=()=>{try{const f=s.createCanvas(i.width,i.height);if(!f)throw new Error("Failed to create canvas");const a=f.getContext("2d");if(!a)throw new Error("Failed to get 2D context");a.drawImage(i,0,0);const _=a.getImageData(0,0,f.width,f.height);n({bits:new Uint8Array(_.data.buffer),width:_.width})}catch(f){o(`Error loading image ${i.src} with exception: ${f}`)}},i.onerror=f=>{o(`Error loading image ${i.src} with exception: ${f}`)},i.crossOrigin="anonymous";let c;if(typeof t=="string"){if(!e)throw new Error("filename is required when using a URL");i.src=t+e}else{const f=new Blob([t],{type:"image/webp"});c=URL.createObjectURL(f),i.src=c}})}async function Bs(t,e,s){const r=t.count?t.count:t.means.shape[0],n=32,o=new ArrayBuffer(n*r),i=new Float32Array(o),c=new Float32Array(o),f=new Uint8ClampedArray(o),a=new Uint8ClampedArray(o),_=u=>Math.sign(u)*(Math.exp(Math.abs(u))-1),h=e[0].bits,l=e[1].bits;if(!Array.isArray(t.means.mins)||!Array.isArray(t.means.maxs))throw new Error("Missing arrays in SOG data.");for(let u=0;u<r;u++){const b=u*4;for(let m=0;m<3;m++){const p=t.means.mins[m],v=t.means.maxs[m],g=l[b+m],y=h[b+m],A=g<<8|y,w=V.Lerp(p,v,A/65535);i[u*8+m]=_(w)}}const d=e[2].bits;if(t.version===2){if(!t.scales.codebook)throw new Error("Missing codebook in SOG version 2 scales data.");for(let u=0;u<r;u++){const b=u*4;for(let m=0;m<3;m++){const p=t.scales.codebook[d[b+m]],v=Math.exp(p);c[u*8+3+m]=v}}}else{if(!Array.isArray(t.scales.mins)||!Array.isArray(t.scales.maxs))throw new Error("Missing arrays in SOG scales data.");for(let u=0;u<r;u++){const b=u*4;for(let m=0;m<3;m++){const p=d[b+m],v=V.Lerp(t.scales.mins[m],t.scales.maxs[m],p/255),g=Math.exp(v);c[u*8+3+m]=g}}}const x=e[4].bits;if(t.version===2){if(!t.sh0.codebook)throw new Error("Missing codebook in SOG version 2 sh0 data.");for(let u=0;u<r;u++){const b=u*4;for(let m=0;m<3;m++){const p=.5+t.sh0.codebook[x[b+m]]*Mt;f[u*32+24+m]=Math.max(0,Math.min(255,Math.round(255*p)))}f[u*32+24+3]=x[b+3]}}else{if(!Array.isArray(t.sh0.mins)||!Array.isArray(t.sh0.maxs))throw new Error("Missing arrays in SOG sh0 data.");for(let u=0;u<r;u++){const b=u*4;for(let m=0;m<4;m++){const p=t.sh0.mins[m],v=t.sh0.maxs[m],g=x[b+m],y=V.Lerp(p,v,g/255);let A;m<3?A=.5+y*Mt:A=1/(1+Math.exp(-y)),f[u*32+24+m]=Math.max(0,Math.min(255,Math.round(255*A)))}}}const C=u=>(u/255-.5)*2/Math.SQRT2,S=e[3].bits;for(let u=0;u<r;u++){const b=S[u*4+0],m=S[u*4+1],p=S[u*4+2],v=S[u*4+3],g=C(b),y=C(m),A=C(p),w=v-252,D=g*g+y*y+A*A,O=Math.sqrt(Math.max(0,1-D));let T;switch(w){case 0:T=[O,g,y,A];break;case 1:T=[g,O,y,A];break;case 2:T=[g,y,O,A];break;case 3:T=[g,y,A,O];break;default:throw new Error("Invalid quaternion mode")}a[u*32+28+0]=T[0]*127.5+127.5,a[u*32+28+1]=T[1]*127.5+127.5,a[u*32+28+2]=T[2]*127.5+127.5,a[u*32+28+3]=T[3]*127.5+127.5}if(t.shN){const u=[0,3,8,15],b=t.shN.bands?u[t.shN.bands]:t.shN.shape[1]/3,m=e[5].bits,p=e[6].bits,v=e[5].width,g=b*3,y=Math.ceil(g/16),A=[],D=s.getEngine().getCaps().maxTextureSize,O=Math.ceil(r/D);for(let T=0;T<y;T++){const B=new Uint8Array(O*D*4*4);A.push(B)}if(t.version===2){if(!t.shN.codebook)throw new Error("Missing codebook in SOG version 2 shN data.");for(let T=0;T<r;T++){const B=p[T*4+0]+(p[T*4+1]<<8),I=B%64*b,U=Math.floor(B/64);for(let k=0;k<b;k++)for(let P=0;P<3;P++){const G=k*3+P,j=Math.floor(G/16),z=A[j],E=G%16,$=T*16,Q=t.shN.codebook[m[(I+k)*4+P+U*v*4]]*127.5+127.5;z[E+$]=Math.max(0,Math.min(255,Q))}}}else for(let T=0;T<r;T++){const B=p[T*4+0]+(p[T*4+1]<<8),I=B%64*b,U=Math.floor(B/64),k=t.shN.mins,P=t.shN.maxs;for(let G=0;G<3;G++)for(let j=0;j<b/3;j++){const z=j*3+G,E=Math.floor(z/16),$=A[E],Q=z%16,oe=T*16,ee=V.Lerp(k,P,m[(I+j)*4+G+U*v*4]/255)*127.5+127.5;$[Q+oe]=Math.max(0,Math.min(255,ee))}}return await new Promise(T=>{T({mode:0,data:o,hasVertexColors:!1,sh:A})})}return await new Promise(u=>{u({mode:0,data:o,hasVertexColors:!1})})}async function Ht(t,e,s){let r,n;if(t instanceof Map){n=t;const c=n.get("meta.json");if(!c)throw new Error("meta.json not found in files Map");r=JSON.parse(new TextDecoder().decode(c))}else r=t;const o=[...r.means.files,...r.scales.files,...r.quats.files,...r.sh0.files];r.shN&&o.push(...r.shN.files);const i=await Promise.all(o.map(async c=>{if(n&&n.has(c)){const f=n.get(c);return await It(f,c,s.getEngine())}else return await It(e,c,s.getEngine())}));return await Bs(r,i,s)}class Y{constructor(e=Y._DefaultLoadingOptions){this.name=He.name,this._assetContainer=null,this.extensions=He.extensions,this._loadingOptions=e}createPlugin(e){return new Y(e[He.name])}async importMeshAsync(e,s,r,n,o,i){return await this._parseAsync(e,s,r,n).then(c=>({meshes:c,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}static _BuildPointCloud(e,s){if(!s.byteLength)return!1;const r=new Uint8Array(s),n=new Float32Array(s),o=32,i=r.length/o,c=function(f,a){const _=n[8*a+0],h=n[8*a+1],l=n[8*a+2];f.position=new M(_,h,l);const d=r[o*a+24+0]/255,x=r[o*a+24+1]/255,C=r[o*a+24+2]/255;f.color=new L(d,x,C,1)};return e.addPoints(i,c),!0}static _BuildMesh(e,s){const r=new Pe("PLYMesh",e),n=new Uint8Array(s.data),o=new Float32Array(s.data),i=32,c=n.length/i,f=[],a=new Ne;for(let _=0;_<c;_++){const h=o[8*_+0],l=o[8*_+1],d=o[8*_+2];f.push(h,l,d)}if(s.hasVertexColors){const _=new Float32Array(c*4);for(let h=0;h<c;h++){const l=n[i*h+24+0]/255,d=n[i*h+24+1]/255,x=n[i*h+24+2]/255;_[h*4+0]=l,_[h*4+1]=d,_[h*4+2]=x,_[h*4+3]=1}a.colors=_}return a.positions=f,a.indices=s.faces,a.applyToMesh(r),r}async _unzipWithFFlateAsync(e){let s=this._loadingOptions.fflate;s||(typeof window.fflate>"u"&&await Rt.LoadScriptAsync(this._loadingOptions.deflateURL??"https://unpkg.com/fflate/umd/index.js"),s=window.fflate);const{unzipSync:r}=s,n=r(e),o=new Map;for(const[i,c]of Object.entries(n))o.set(i,c);return o}_parseAsync(e,s,r,n){const o=[],i=h=>{s._blockEntityCollection=!!this._assetContainer;const l=new H("GaussianSplatting",null,s,this._loadingOptions.keepInRam);l._parentContainer=this._assetContainer,l.viewDirectionFactor.set(1,-1,1),o.push(l),l.updateData(h.data,h.sh),s._blockEntityCollection=!1};if(typeof r=="string"){const h=JSON.parse(r);if(h&&h.means&&h.scales&&h.quats&&h.sh0)return new Promise(l=>{Ht(h,n,s).then(d=>{i(d),l(o)}).catch(()=>{throw new Error("Failed to parse SOG data.")})})}const c=r instanceof ArrayBuffer?new Uint8Array(r):r;if(c[0]===80&&c[1]===75)return new Promise(h=>{this._unzipWithFFlateAsync(c).then(l=>{Ht(l,n,s).then(d=>{i(d),h(o)}).catch(()=>{throw new Error("Failed to parse SOG zip data.")})})});const f=new ReadableStream({start(h){h.enqueue(new Uint8Array(r)),h.close()}}),a=new DecompressionStream("gzip"),_=f.pipeThrough(a);return new Promise(h=>{new Response(_).arrayBuffer().then(l=>{Os(l,s,this._loadingOptions).then(d=>{s._blockEntityCollection=!!this._assetContainer;const x=new H("GaussianSplatting",null,s,this._loadingOptions.keepInRam);if(d.trainedWithAntialiasing){const C=x.material;C.kernelSize=.1,C.compensation=!0}x._parentContainer=this._assetContainer,o.push(x),x.updateData(d.data,d.sh),s._blockEntityCollection=!1,h(o)})}).catch(()=>{Y._ConvertPLYToSplat(r).then(async l=>{switch(s._blockEntityCollection=!!this._assetContainer,l.mode){case 0:{const d=new H("GaussianSplatting",null,s,this._loadingOptions.keepInRam);d._parentContainer=this._assetContainer,o.push(d),d.updateData(l.data,l.sh),(l.compressed||!l.rawSplat)&&d.viewDirectionFactor.set(-1,-1,1)}break;case 1:{const d=new Fs("PointCloud",1,s);Y._BuildPointCloud(d,l.data)?await d.buildMeshAsync().then(x=>{o.push(x)}):d.dispose()}break;case 2:if(l.faces)o.push(Y._BuildMesh(s,l));else throw new Error("PLY mesh doesn't contain face informations.");break;default:throw new Error("Unsupported Splat mode")}s._blockEntityCollection=!1,h(o)})})})}loadAssetContainerAsync(e,s,r){const n=new as(e);return this._assetContainer=n,this.importMeshAsync(null,e,s,r).then(o=>{for(const i of o.meshes)n.meshes.push(i);return this._assetContainer=null,n}).catch(o=>{throw this._assetContainer=null,o})}loadAsync(e,s,r){return this.importMeshAsync(null,e,s,r).then(()=>{})}static _ConvertPLYToSplat(e){const s=new Uint8Array(e),r=new TextDecoder().decode(s.slice(0,1024*10)),n=`end_header
`,o=r.indexOf(n);if(o<0||!r)return new Promise(p=>{p({mode:0,data:e,rawSplat:!0})});const i=parseInt(/element vertex (\d+)\n/.exec(r)[1]),c=/element face (\d+)\n/.exec(r);let f=0;c&&(f=parseInt(c[1]));const a=/element chunk (\d+)\n/.exec(r);let _=0;a&&(_=parseInt(a[1]));let h=0,l=0;const d={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let x;(function(p){p[p.Vertex=0]="Vertex",p[p.Chunk=1]="Chunk",p[p.SH=2]="SH"})(x||(x={}));let C=1;const S=[],u=r.slice(0,o).split(`
`);for(const p of u)if(p.startsWith("property ")){const[,v,g]=p.split(" ");C==1?l+=d[v]:C==0?(S.push({name:g,type:v,offset:h}),h+=d[v]):C==2&&S.push({name:g,type:v,offset:h}),d[v]||de.Warn(`Unsupported property type: ${v}.`)}else if(p.startsWith("element ")){const[,v]=p.split(" ");v=="chunk"?C=1:v=="vertex"?C=0:v=="sh"&&(C=2)}const b=h,m=l;return H.ConvertPLYWithSHToSplatAsync(e).then(async p=>{const v=new DataView(e,o+n.length);let g=m*_+b*i;const y=[];if(f)for(let I=0;I<f;I++){const U=v.getUint8(g);if(U==3){g+=1;for(let k=0;k<U;k++){const P=v.getUint32(g+(2-k)*4,!0);y.push(P)}g+=12}}if(_)return await new Promise(I=>{I({mode:0,data:p.buffer,sh:p.sh,faces:y,hasVertexColors:!1,compressed:!0,rawSplat:!1})});let A=0,w=0;const D=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],O=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let I=0;I<S.length;I++){const U=S[I];D.includes(U.name)&&A++,O.includes(U.name)&&w++}const T=A==D.length&&w==3,B=f?2:T?0:1;return await new Promise(I=>{I({mode:B,data:p.buffer,sh:p.sh,faces:y,hasVertexColors:!!w,compressed:!1,rawSplat:!1})})})}}Y._DefaultLoadingOptions={keepInRam:!1,flipY:!1};ns(new Y);export{Y as SPLATFileLoader};
