@myned-ai/gsplat-flame-avatar-renderer 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +268 -0
- package/dist/gsplat-flame-avatar-renderer.esm.js +12755 -0
- package/dist/gsplat-flame-avatar-renderer.esm.js.map +1 -0
- package/dist/gsplat-flame-avatar-renderer.esm.min.js +2 -0
- package/dist/gsplat-flame-avatar-renderer.esm.min.js.map +1 -0
- package/dist/gsplat-flame-avatar-renderer.umd.js +12876 -0
- package/dist/gsplat-flame-avatar-renderer.umd.js.map +1 -0
- package/dist/gsplat-flame-avatar-renderer.umd.min.js +2 -0
- package/dist/gsplat-flame-avatar-renderer.umd.min.js.map +1 -0
- package/dist/gsplat-flame-avatar.esm.js +12755 -0
- package/dist/gsplat-flame-avatar.esm.js.map +1 -0
- package/dist/gsplat-flame-avatar.esm.min.js +2 -0
- package/dist/gsplat-flame-avatar.esm.min.js.map +1 -0
- package/dist/gsplat-flame-avatar.umd.js +12876 -0
- package/dist/gsplat-flame-avatar.umd.js.map +1 -0
- package/dist/gsplat-flame-avatar.umd.min.js +2 -0
- package/dist/gsplat-flame-avatar.umd.min.js.map +1 -0
- package/dist/index.d.ts +349 -0
- package/package.json +66 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three"),require("three/examples/jsm/loaders/GLTFLoader.js"),require("jszip"),require("three/examples/jsm/controls/OrbitControls.js")):"function"==typeof define&&define.amd?define(["exports","three","three/examples/jsm/loaders/GLTFLoader.js","jszip","three/examples/jsm/controls/OrbitControls.js"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GsplatFlameAvatarRenderer={},e.THREE,e.THREE,e.JSZip,e.THREE)}(this,function(e,t,s,i,n){"use strict";function r(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var a=r(t);const o={None:0,Error:1,Warning:2,Info:3,Debug:4},l={Always:0,OnChange:1,Never:2},c={Ply:0},h=e=>e.endsWith(".ply")?c.Ply:null,d={Default:0,Gradual:1,Instant:2},u={ThreeD:0,TwoD:1};let p=class{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 A=p.SphericalHarmonics8BitCompressionRange,m=15e5,g={DirectToSplatBuffer:0,DirectToSplatArray:1,DownloadBeforeProcessing:2},f={Downloading:0,Processing:1,Done:2};class S extends Error{constructor(e){super(e),this.name="AbortedPromiseError"}}const C=function(e,t,s=!0,i){const n=new AbortController,r=n.signal;let a=!1,o=!1;const l=(e,s,i,n)=>{t&&!o&&(t(e,s,i,n),100===e&&(o=!0))},c=new Promise((t,n)=>{const o={signal:r};i&&(o.headers=i),fetch(e,o).then(async e=>{if(!e.ok){const t=await e.text();return void n(new Error(`Fetch failed: ${e.status} ${e.statusText} ${t}`))}const i=e.body.getReader();let r=0,o=e.headers.get("Content-Length"),c=o?parseInt(o):void 0;const h=[];for(;!a;)try{const{value:e,done:n}=await i.read();if(n){if(l(100,"100%",e,c),s){const e=new Blob(h).arrayBuffer();t(e)}else t();break}let a,o;r+=e.length,void 0!==c&&(a=r/c*100,o=`${a.toFixed(2)}%`),s&&h.push(e),l(a,o,e,c)}catch(e){return void n(e)}}).catch(e=>{"AbortError"===e.name?n(new S("Fetch aborted")):n(new S(e.message||e))})});return c.abort=e=>{a=!0,n.abort(e)},c.abortController=n,c},x=function(e,t,s){return Math.max(Math.min(e,s),t)},y=function(){return performance.now()/1e3},v=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)v(t)},I=(e,t)=>new Promise(s=>{window.setTimeout(()=>{s(e())},t?1:50)}),B=(e=0)=>{switch(e){case 1:return 9;case 2:return 24}return 0},T=()=>{let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}},b=e=>{let t,s;const i=new Promise((e,i)=>{t=e,s=i});return i.abort=e||(()=>{}),{promise:i,resolve:t,reject:s}};class D{constructor(e,t,s){this.major=e,this.minor=t,this.patch=s}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function M(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function w(){if(M()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new D(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}const E=t.DataUtils.toHalfFloat.bind(t.DataUtils),R=t.DataUtils.fromHalfFloat.bind(t.DataUtils),F=A/2,P=(e,t,s)=>{e=x(e,t,s);const i=s-t;return x(Math.floor((e-t)/i*255),0,255)},k=(e,t,s)=>e/255*(s-t)+t,L=(e,t,s)=>P(R(e),t,s),U=(e,t,s)=>E(k(e,t,s)),_=function(){const e=e=>e;return function(t,s,i,n=!1){if(s===i)return t;let r=e;return 2===s&&n?1===i?r=U:0===i&&(r=k):2===s||1===s?0===i?r=R:2===i&&(r=n?L:e):0===s&&(1===i?r=E:2===i&&(r=n?P:E)),r(t)}}(),H=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){e[0]=s;const i=t[0];let n=i>>16&32768,r=i>>12&2047;const a=i>>23&255;return a<103?n:a>142?(n|=31744,n|=(255==a?0:1)&&8388607&i,n):a<113?(r|=2048,n|=(r>>114-a)+(r>>113-a&1),n):(n|=a-112<<10|r>>1,n+=1&r,n)}}(),O=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),Q=function(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24)},z={Idle:"Idle",Listening:"Listening",Responding:"Responding",Thinking:"Thinking"},V=["browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","eyeBlinkLeft","eyeBlinkRight","eyeLookDownLeft","eyeLookDownRight","eyeLookInLeft","eyeLookInRight","eyeLookOutLeft","eyeLookOutRight","eyeLookUpLeft","eyeLookUpRight","eyeSquintLeft","eyeSquintRight","eyeWideLeft","eyeWideRight","jawForward","jawLeft","jawOpen","jawRight","mouthClose","mouthDimpleLeft","mouthDimpleRight","mouthFrownLeft","mouthFrownRight","mouthFunnel","mouthLeft","mouthLowerDownLeft","mouthLowerDownRight","mouthPressLeft","mouthPressRight","mouthPucker","mouthRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthSmileLeft","mouthSmileRight","mouthStretchLeft","mouthStretchRight","mouthUpperUpLeft","mouthUpperUpRight","noseSneerLeft","noseSneerRight","tongueOut"],N=["root","neck","jaw","leftEye","rightEye"],G=V.length,W=N.length;class q{constructor(e,t){this.isPlaying=!1,this.stage=0,this.actions=e||[],this.blendingTime=.5,this.isGroup=t||!1}dispose(){this.actions=[]}update(e){}}class K extends q{constructor(e,t){super(e,t)}update(e){if(this.actions&&0!==this.actions.length&&(void 0===Z.CurPlaying&&e===z.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,Z.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=t.LoopRepeat,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==Z.LastAction&&Z.PrepareCrossFade(Z.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),Z.CurPlaying===z.Idle&&e===z.Idle&&!0===this.isPlaying&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime)){let e=this.stage+1;e>=this.actions.length&&(e=0),this.actions[e].time=0,Z.SetWeight(this.actions[e],1),this.actions[e].loop=t.LoopRepeat,this.actions[e].play(),Z.PrepareCrossFade(this.actions[this.stage],this.actions[e],this.blendingTime),this.stage=e}}}class j extends q{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===Z.CurPlaying&&e===z.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,Z.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=t.LoopRepeat,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==Z.LastAction&&Z.PrepareCrossFade(Z.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),Z.CurPlaying===z.Idle&&e!==z.Idle&&!0===this.isPlaying&&0===this.stage&&(this.actions[this.stage].loop=t.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Z.LastAction=this.actions[this.stage]))}}class J extends q{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===Z.CurPlaying&&e===z.Listening&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),Z.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=this.isGroup?t.LoopOnce:t.LoopRepeat,this.actions[this.stage].clampWhenFinished=!!this.isGroup,void 0!==Z.LastAction&&Z.PrepareCrossFade(Z.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(Z.CurPlaying===z.Listening&&e===z.Listening&&!0===this.isPlaying&&0===this.stage&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime&&(this.actions[this.stage+1].time=0,Z.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=t.LoopRepeat,this.actions[this.stage+1].play(),Z.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),Z.CurPlaying!==z.Listening||e===z.Listening||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),Z.SetWeight(this.actions[2],1),this.actions[2].loop=t.LoopOnce,Z.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),Z.CurPlaying===z.Listening&&e!==z.Listening&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=t.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Z.LastAction=this.actions[this.stage]))}}class X extends q{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===Z.CurPlaying&&e===z.Thinking&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),Z.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=t.LoopOnce,void 0!==Z.LastAction&&Z.PrepareCrossFade(Z.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(Z.CurPlaying===z.Thinking&&e===z.Thinking&&!0===this.isPlaying&&0===this.stage&&this.actions[this.stage].time>this.actions[this.stage].getClip().duration-this.blendingTime&&(this.actions[this.stage+1].time=0,Z.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=t.LoopRepeat,this.actions[this.stage+1].play(),Z.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),Z.CurPlaying!==z.Thinking||e===z.Thinking||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),Z.SetWeight(this.actions[2],1),this.actions[2].loop=t.LoopOnce,Z.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),Z.CurPlaying===z.Thinking&&e!==z.Thinking&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=t.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Z.LastAction=this.actions[this.stage]))}}class Y extends q{constructor(e,t){super(e,t),console.log("[SPEAK] Initialized with",e?.length||0,"actions, isGroup:",t)}getRandomNumber(e,t){const s=e-t;return t+Math.round(Math.random()*s)}update(e){if(this.actions&&0!==this.actions.length){if(void 0===Z.CurPlaying&&e===z.Responding&&!1===this.isPlaying&&(this.stage=Math.ceil(this.getRandomNumber(0,this.actions.length-1)),console.log("[SPEAK] Starting animation, stage:",this.stage,"of",this.actions.length),this.actions[this.stage].time=0,this.actions[this.stage].play(),Z.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=t.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,void 0!==Z.LastAction&&Z.PrepareCrossFade(Z.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),Z.CurPlaying===z.Responding&&e===z.Responding&&!0===this.isPlaying&&this.actions[this.stage].time>=this.actions[this.stage].getClip().duration-this.blendingTime){const e=this.actions[this.stage];this.stage=(this.stage+Math.ceil(this.getRandomNumber(1,this.actions.length-1)))%this.actions.length,console.log("[SPEAK] Cycling to next animation, stage:",this.stage),this.actions[this.stage].time=0,this.actions[this.stage].play(),Z.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=t.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,Z.PrepareCrossFade(e,this.actions[this.stage],this.blendingTime)}Z.CurPlaying===z.Responding&&e!==z.Responding&&!0===this.isPlaying&&(this.actions[this.stage].loop=t.LoopOnce,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,Z.LastAction=this.actions[this.stage])}else this._warnedNoActions||(console.warn("[SPEAK] No actions available!"),this._warnedNoActions=!0)}}class Z{static IsBlending=!1;static actions=[];static NeedReset=!1;static NeedFullReset=!1;static LastAction=void 0;static CurPlaying=void 0;static SetWeight(e,t){e.enabled=!0,e.setEffectiveTimeScale(1),e.setEffectiveWeight(t)}static PrepareCrossFade(e,t,s){const i=s;Z.UnPauseAllActions(),Z.ExecuteCrossFade(e,t,i),Z.IsBlending=!0,setTimeout(()=>{Z.IsBlending=!1},s+.1)}static PauseAllActions(){Z.actions.forEach(function(e){e.paused=!0})}static UnPauseAllActions(){Z.actions.forEach(function(e){e.paused=!1})}static ExecuteCrossFade(e,t,s){Z.SetWeight(t,1),t.time=0,e.crossFadeTo(t,s,!0)}constructor(e,t,s){const i=[],n=[],r=[],a=[],o=[];this.mixer=e;const l=s?.hello?.size||0,c=(s?.idle?.size||0)+l,h=(s?.listen?.size||0)+c,d=(s?.speak?.size||0)+h,u=(s?.think?.size||0)+d;if(t&&t.length>0)for(let s=0;s<t.length;s++){const p=t[s],A=e.clipAction(p);s<l?i.push(A):s<c?(n.push(A),h===c&&r.push(e.clipAction(p.clone())),d===h&&a.push(e.clipAction(p.clone())),u===d&&o.push(e.clipAction(p.clone()))):s<h?r.push(A):s<d?a.push(A):s<u&&o.push(A),Z.actions.push(A),Z.SetWeight(A,0)}this.hello=new K(i,s?.hello?.isGroup||!1),this.idle=new j(n,s?.idle?.isGroup||!1),this.listen=new J(r,s?.listen?.isGroup||!1),this.think=new X(o,s?.think?.isGroup||!1),this.speak=new Y(a,s?.speak?.isGroup||!1)}curPlaying(){return this.hello.isPlaying||this.idle.isPlaying?z.Idle:this.listen.isPlaying?z.Listening:this.think.isPlaying?z.Thinking:this.speak.isPlaying?z.Responding:void 0}dispose(){this.hello.dispose(),this.idle.dispose(),this.listen.dispose(),this.think.dispose(),this.speak.dispose(),Z.actions=[]}resetAllActions(e=!1){switch(this.curPlaying()){case z.Idle:Z.LastAction=this.hello.actions[this.hello.stage];break;case z.Listening:Z.LastAction=this.listen.actions[this.listen.stage];break;case z.Thinking:Z.LastAction=this.think.actions[this.think.stage];break;case z.Responding:Z.LastAction=this.speak.actions[this.speak.stage];break;default:Z.LastAction=void 0}Z.LastAction&&(Z.LastAction.loop=t.LoopOnce,Z.LastAction.clampWhenFinished=!0,Z.SetWeight(Z.LastAction,1)),e&&(Z.PauseAllActions(),Z.actions.forEach(function(e){e.time=0,Z.SetWeight(e,0)}),Z.LastAction=void 0),this.hello.isPlaying=!1,this.idle.isPlaying=!1,this.listen.isPlaying=!1,this.think.isPlaying=!1,this.speak.isPlaying=!1}update(e){if(!Z.IsBlending)if(Z.CurPlaying=this.curPlaying(),void 0===Z.CurPlaying)switch(e){case z.Idle:this.idle.update(e);break;case z.Listening:this.listen.update(e);break;case z.Thinking:this.think.update(e);break;case z.Responding:this.speak.update(e);break;default:this.idle.update(e)}else switch(Z.CurPlaying){case z.Idle:this.idle.update(e);break;case z.Listening:this.listen.update(e);break;case z.Thinking:this.think.update(e);break;case z.Responding:this.speak.update(e);break;default:this.idle.update(e)}}}class $ extends t.Object3D{constructor(e,s=new t.Vector3,i=new t.Quaternion,n=new t.Vector3(1,1,1),r=1,a=1,o=!0){super(),this.splatBuffer=e,this.position.copy(s),this.quaternion.copy(i),this.scale.copy(n),this.transform=new t.Matrix4,this.minimumAlpha=r,this.opacity=a,this.visible=o}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 ee{static build(e){const s=new t.BufferGeometry;s.setIndex([0,1,2,0,2,3]);const i=new Float32Array(12),n=new t.BufferAttribute(i,3);s.setAttribute("position",n),n.setXYZ(0,-1,-1,0),n.setXYZ(1,-1,1,0),n.setXYZ(2,1,1,0),n.setXYZ(3,1,-1,0),n.needsUpdate=!0;const r=(new t.InstancedBufferGeometry).copy(s),a=new Uint32Array(e),o=new t.InstancedBufferAttribute(a,1,!1);return o.setUsage(t.DynamicDrawUsage),r.setAttribute("splatIndex",o),r.instanceCount=0,r}}class te{constructor(){this.rootNode=null,this.splatMesh=null}static convertWorkerSubTree(e,t){const s=new te;return s.rootNode=e.rootNode,s.splatMesh=t,s}}class se{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=(e,s=()=>!0,i,n)=>{this.splatTreeWorker||(this.splatTreeWorker=null),this.splatMesh=e,this.subTrees=[];const r=new t.Vector3,a=(t,i)=>{const n=new Float32Array(4*i);let a=0;for(let o=0;o<i;o++){const i=o+t;if(s(i)){e.getSplatCenter(i,r);const t=4*a;n[t]=r.x,n[t+1]=r.y,n[t+2]=r.z,n[t+3]=i,a++}}return n};return new Promise(t=>{const s=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),t(),!0);i&&i(!1),I(()=>{if(s())return;const r=[];if(e.dynamicMode){let t=0;for(let s=0;s<e.scenes.length;s++){const i=e.getScene(s).splatBuffer.getSplatCount(),n=a(t,i);r.push(n),t+=i}}else{const t=a(0,e.getSplatCount());r.push(t)}this.splatTreeWorker.onmessage=i=>{s()||i.data.subTrees&&(n&&n(!1),I(()=>{if(!s()){for(let t of i.data.subTrees){const s=te.convertWorkerSubTree(t,e);this.subTrees.push(s)}this.diposeSplatTreeWorker(),n&&n(!0),I(()=>{t()})}}))},I(()=>{if(s())return;i&&i(!0);const e=r.map(e=>e.buffer);var t,n,a,o,l;t=this.splatTreeWorker,n=r,a=e,o=this.maxDepth,l=this.maxCentersPerNode,t&&t.postMessage({process:{centers:n,maxDepth:o,maxCentersPerNode:l}},a)})})})};countLeaves(){let e=0;return this.visitLeaves(()=>{e++}),e}visitLeaves(e){const t=(e,s)=>{0===e.children.length&&s(e);for(let i of e.children)t(i,s)};for(let s of this.subTrees)t(s.rootNode,e)}}class ie{static buildVertexShaderBase(e=!1,t=!1,s=0,i="",n=!0){let r="";return r+=1==n?"#define USE_FLAME":"#define USE_SKINNING",r+="\n precision highp float;\n #include <common>\n\n attribute uint splatIndex;\n uniform highp usampler2D flameModelTexture;\n uniform highp usampler2D boneTexture;\n uniform highp usampler2D boneWeightTexture;\n\n\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 uniform int gaussianSplatCount;\n uniform int bsCount;\n uniform float headBoneIndex;\n #ifdef USE_SKINNING\n attribute vec4 skinIndex;\n attribute vec4 skinWeight;\n #endif\n ",t&&(r+=`\n uniform float sceneOpacity[${p.MaxScenes}];\n uniform int sceneVisibility[${p.MaxScenes}];\n `),e&&(r+=`\n uniform highp mat4 transforms[${p.MaxScenes}];\n `),r+=`\n ${i}\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 vec2 flameModelTextureSize;\n uniform vec2 boneWeightTextureSize;\n uniform vec2 boneTextureSize;\n\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[${p.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${p.MaxScenes}];\n\n varying vec4 vColor;\n varying vec2 vUv;\n varying vec2 vPosition;\n varying vec2 vSplatIndex;\n #ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture0;\n mat4 getBoneMatrix0( const in float i ) {\n int size = textureSize( boneTexture0, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( boneTexture0, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( boneTexture0, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( boneTexture0, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( boneTexture0, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n #endif\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 int internal = 1;//show a gaussian splatting point every internal points.\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 float getRealIndex(int sIndex, int reducedFactor) {\n int remainder = sIndex % reducedFactor;\n\n if(remainder == int(0)) {\n return float(sIndex);\n }\n else\n {\n return float(sIndex - remainder);\n }\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(uint(getRealIndex(int(splatIndex), internal)) * 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 getFlameDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(int(splatIndex) / internal) * uint(stride) + uint(offset) + uint(gaussianSplatCount * bsCount)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getBoneWeightUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(int(splatIndex) / internal) * 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 getBSFlameDataUV(in int bsInedex, in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(int(splatIndex) / internal) * uint(stride) + uint(offset) + uint(gaussianSplatCount * bsInedex)) / 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(getRealIndex(int(sIndex), internal)) * 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 mat4 getBoneMatrix( float i ) {\n float y = i;\n float x = 0.0;\n\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(i * 4.0) / boneTextureSize.x;//4\n samplerUV.y = float(floor(d)) / boneTextureSize.y;//5\n samplerUV.x = fract(d);\n\n vec4 v1 = uintBitsToFloat(texture( boneTexture, samplerUV ));\n vec4 v2 = uintBitsToFloat(texture( boneTexture, vec2(samplerUV.x + 1.0 / boneTextureSize.x, samplerUV.y)));\n vec4 v3 = uintBitsToFloat(texture( boneTexture, vec2(samplerUV.x + 2.0 / boneTextureSize.x, samplerUV.y) ));\n vec4 v4 = uintBitsToFloat(texture( boneTexture, vec2(samplerUV.x + 3.0 / boneTextureSize.x, samplerUV.y)));\n\n return mat4( v1, v2, v3, v4 );\n }\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 uvec3 sampledCenter = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize)).gba;\n vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenter));\n\n vec2 flameTextureUV = getBSFlameDataUV(bsCount, 1, 0, flameModelTextureSize);\n uvec3 sampledflamePos = texture(flameModelTexture, flameTextureUV).rgb;\n // splatCenter += uintBitsToFloat(uvec3(sampledflamePos.rgb));\n\n for(int i = 0; i < bsCount; ++i) {\n vec2 flameBSTextureUV = getBSFlameDataUV(i, 1, 0, flameModelTextureSize);\n uvec3 sampledBSPos = texture(flameModelTexture, flameBSTextureUV).rgb;\n\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(i / 4 + 5 * 4) / boneTextureSize.x;//4\n samplerUV.y = float(floor(d)) / boneTextureSize.y;//32\n samplerUV.x = fract(d);\n\n vec4 bsWeight = uintBitsToFloat(texture(boneTexture, samplerUV));\n float weight = bsWeight.r;\n if(i % 4 == 1) {\n weight = bsWeight.g;\n }\n if(i % 4 == 2) {\n weight = bsWeight.b;\n }\n if(i % 4 == 3) {\n weight = bsWeight.a;\n }\n\n splatCenter = splatCenter + weight * uintBitsToFloat(sampledBSPos);\n }\n\n\n #ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix0( skinIndex.x );\n mat4 boneMatY = getBoneMatrix0( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix0( skinIndex.z );\n mat4 boneMatW = getBoneMatrix0( skinIndex.w );\n #endif\n #ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n // skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n #endif\n vec3 transformed = vec3(splatCenter.xyz);\n #ifdef USE_SKINNING\n // vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinVertex = vec4( transformed, 1.0 );\n\n vec4 skinned = vec4( 0.0 );\n // There is an offset between the Gaussian point and the mesh vertex,\n // which will cause defects in the skeletal animation driving the Gaussian point. \n //In order to circumvent this problem, only the head bone(index is 110 currently) is used to drive\n\n if (headBoneIndex >= 0.0)\n {\n mat4 boneMat = getBoneMatrix0( headBoneIndex );\n skinned += boneMat * skinVertex * 1.0;\n }\n\n // skinned += boneMatX * skinVertex * skinWeight.x;\n // skinned += boneMatY * skinVertex * skinWeight.y;\n // skinned += boneMatZ * skinVertex * skinWeight.z;\n // skinned += boneMatW * skinVertex * skinWeight.w;\n\n // transformed = ( bindMatrixInverse * skinned ).xyz;\n transformed = skinned.xyz;\n\n #endif\n splatCenter = transformed.xyz;\n\n #ifdef USE_FLAME\n mat4 boneMatX = getBoneMatrix( 0.0 );\n mat4 boneMatY = getBoneMatrix( 1.0 );\n mat4 boneMatZ = getBoneMatrix( 2.0 );\n mat4 boneMatW = getBoneMatrix( 3.0 ); \n mat4 boneMat0 = getBoneMatrix( 4.0 ); \n \n vec2 boneWeightUV0 = getBoneWeightUV(2, 0, boneWeightTextureSize);\n vec2 boneWeightUV1 = getBoneWeightUV(2, 1, boneWeightTextureSize);\n\n uvec4 sampledBoneMatrixValue = texture(boneWeightTexture, boneWeightUV0);\n uvec4 sampledBoneMatrixValue0 = texture(boneWeightTexture, boneWeightUV1);\n\n vec4 boneMatrixValue = uintBitsToFloat(sampledBoneMatrixValue);\n vec4 boneMatrixValue0 = uintBitsToFloat(sampledBoneMatrixValue0);\n\n vec4 skinVertex = vec4( splatCenter, 1.0 );\n vec4 skinned = vec4( 0.0 );\n float minWeight = min(boneMatrixValue.x,min(boneMatrixValue.y, min(boneMatrixValue.z, min(boneMatrixValue.w, boneMatrixValue0.x))));\n \n if(boneMatrixValue.x > 0.0 && boneMatrixValue.x > minWeight)\n skinned += boneMatX * skinVertex * boneMatrixValue.x;\n \n if(boneMatrixValue.y > 0.0 && boneMatrixValue.y > minWeight)\n skinned += boneMatY * skinVertex * boneMatrixValue.y;\n \n if(boneMatrixValue.z > 0.0 && boneMatrixValue.z > minWeight)\n skinned += boneMatZ * skinVertex * boneMatrixValue.z;\n \n if(boneMatrixValue.w > 0.0 && boneMatrixValue.w > minWeight)\n skinned += boneMatW * skinVertex * boneMatrixValue.w;\n \n if(boneMatrixValue0.x > 0.0 && boneMatrixValue0.x > minWeight)\n skinned += boneMat0 * skinVertex * boneMatrixValue0.x;\n \n splatCenter = skinned.xyz;\n #endif\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 #ifdef USE_SKINNING\n transformModelViewMatrix = transformModelViewMatrix * skinMatrix;\n #endif\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 vSplatIndex = vec2(splatIndex, splatIndex);\n\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(e=!1,s=!1,i=0,n=1,r=!1){const a={sceneCenter:{type:"v3",value:new t.Vector3},fadeInComplete:{type:"i",value:0},orthographicMode:{type:"i",value:0},visibleRegionFadeStartRadius:{type:"f",value:0},visibleRegionRadius:{type:"f",value:0},bindMatrix:{type:"m4",value:new t.Matrix4},bindMatrixInverse:{type:"m4",value:new t.Matrix4},currentTime:{type:"f",value:0},firstRenderTime:{type:"f",value:0},centersColorsTexture:{type:"t",value:null},flameModelTexture:{type:"t",value:null},boneTexture:{type:"t",value:null},boneTexture0:{type:"t",value:null},boneWeightTexture:{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 t.Vector2},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new t.Vector2},basisViewport:{type:"v2",value:new t.Vector2},debugColor:{type:"v3",value:new t.Color},centersColorsTextureSize:{type:"v2",value:new t.Vector2(1024,1024)},flameModelTextureSize:{type:"v2",value:new t.Vector2(4096,2048)},boneTextureSize:{type:"v2",value:new t.Vector2(4,32)},boneWeightTextureSize:{type:"v2",value:new t.Vector2(512,512)},sphericalHarmonicsDegree:{type:"i",value:i},sphericalHarmonicsTextureSize:{type:"v2",value:new t.Vector2(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:n},pointCloudModeEnabled:{type:"i",value:r?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new t.Vector2(1024,1024)},sceneCount:{type:"i",value:1},gaussianSplatCount:{type:"i",value:1},bsCount:{type:"i",value:1},headBoneIndex:{type:"f",value:-1}};for(let e=0;e<p.MaxScenes;e++)a.sphericalHarmonics8BitCompressionRangeMin.value.push(-p.SphericalHarmonics8BitCompressionRange/2),a.sphericalHarmonics8BitCompressionRangeMax.value.push(p.SphericalHarmonics8BitCompressionRange/2);if(s){const e=[];for(let t=0;t<p.MaxScenes;t++)e.push(1);a.sceneOpacity={type:"f",value:e};const t=[];for(let e=0;e<p.MaxScenes;e++)t.push(1);a.sceneVisibility={type:"i",value:t}}if(e){const e=[];for(let s=0;s<p.MaxScenes;s++)e.push(new t.Matrix4);a.transforms={type:"mat4",value:e}}return a}}class ne{static build(e=!1,s=!1,i=!1,n=2048,r=1,a=!1,o=0,l=.3,c=!0){let h=ie.buildVertexShaderBase(e,s,o,"\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);h+=ne.buildVertexShaderProjection(i,s,n,l);const d=ne.buildFragmentShader(),u=ie.getUniforms(e,s,o,r,a);u.covariancesTextureSize={type:"v2",value:new t.Vector2(1024,1024)},u.covariancesTexture={type:"t",value:null},u.covariancesTextureHalfFloat={type:"t",value:null},u.covariancesAreHalfFloat={type:"i",value:0};return new t.ShaderMaterial({uniforms:u,vertexShader:h,fragmentShader:d,transparent:!0,alphaTest:1,blending:t.NormalBlending,depthTest:!0,depthWrite:!1,side:t.DoubleSide})}static buildVertexShaderProjection(e,t,s,i){let n="\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 n+=e?`\n float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n cov2Dm[0][0] += ${i};\n cov2Dm[1][1] += ${i};\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] += ${i};\n cov2Dm[1][1] += ${i};\n `,n+=`\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&&(n+="\n vColor.a *= splatOpacityFromScene;\n "),n+="\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 ",n+=ie.getVertexShaderFadeIn(),n+="}",n}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 varying vec2 vSplatIndex;\n\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\n // if(vSplatIndex.x > 20000.0) discard;\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 if(opacity < 1.0 / 255.0)\n discard;\n\n // uint a = uint(255);\n // vec3 c = vec3(vSplatIndex.x / 256.0 / 256.0, float(uint(vSplatIndex.x / 256.0 )% a) / 256.0, float(uint(vSplatIndex.x)% a) / 256.0);\n // gl_FragColor = vec4(c, 1.0);\n gl_FragColor = vec4(color, opacity);\n\n\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 varying vec2 vSplatIndex;\n\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\n // if(vSplatIndex.x > 20000.0) discard;\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 if(opacity < 1.0 / 255.0)\n discard;\n\n // uint a = uint(255);\n // vec3 c = vec3(vSplatIndex.x / 256.0 / 256.0, float(uint(vSplatIndex.x / 256.0 )% a) / 256.0, float(uint(vSplatIndex.x)% a) / 256.0);\n // gl_FragColor = vec4(c, 1.0);\n gl_FragColor = vec4(color, opacity);\n\n\n }\n "}}class re{static build(e=!1,s=!1,i=1,n=!1,r=0){let a=ie.buildVertexShaderBase(e,s,r,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");a+=re.buildVertexShaderProjection();const o=re.buildFragmentShader(),l=ie.getUniforms(e,s,r,i,n);l.scaleRotationsTexture={type:"t",value:null},l.scaleRotationsTextureSize={type:"v2",value:new t.Vector2(1024,1024)};return new t.ShaderMaterial({uniforms:l,vertexShader:a,fragmentShader:o,transparent:!0,alphaTest:1,blending:t.NormalBlending,depthTest:!0,depthWrite:!1,side:t.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+=ie.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 "}}const ae=new t.BufferGeometry,oe=new t.MeshBasicMaterial;function le(e){const t={};function s(s){if(void 0!==t[s])return t[s];let i;switch(s){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=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":i=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":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(s)}return t[s]=i,i}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 ce(e,t,s){let i;function n(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 r="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let a=void 0!==s.precision?s.precision:"highp";const o=n(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=r||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),u=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),A=e.getParameter(e.MAX_VERTEX_ATTRIBS),m=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),g=e.getParameter(e.MAX_VARYING_VECTORS),f=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),S=d>0,C=r||t.has("OES_texture_float");return{isWebGL2:r,drawBuffers:l,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:n,precision:a,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:d,maxTextureSize:u,maxCubemapSize:p,maxAttributes:A,maxVertexUniforms:m,maxVaryings:g,maxFragmentUniforms:f,vertexTextures:S,floatFragmentTextures:C,floatVertexTextures:S&&C,maxSamples:r?e.getParameter(e.MAX_SAMPLES):0}}function he(e,s,i){const n=i.isWebGL2;return{convert:function(i,r){let a;if(i===t.UnsignedByteType)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(i===t.FloatType)return e.FLOAT;if(i===t.HalfFloatType)return n?e.HALF_FLOAT:(a=s.get("OES_texture_half_float"),null!==a?a.HALF_FLOAT_OES:null);if(1021===i)return e.ALPHA;if(1022===i)return e.RGB;if(i===t.RGBAFormat)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(i===t.RedFormat)return e.RED;if(i===t.RedIntegerFormat)return e.RED_INTEGER;if(i===t.RGFormat)return e.RG;if(i===t.RGIntegerFormat)return e.RG_INTEGER;if(i===t.RGBIntegerFormat)return e.RGB_INTEGER;if(i===t.RGBAIntegerFormat)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i){if(a=s.get("WEBGL_compressed_texture_s3tc"),null===a)return null;if(33776===i)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){if(a=s.get("WEBGL_compressed_texture_pvrtc"),null===a)return null;if(35840===i)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i)return a=s.get("WEBGL_compressed_texture_etc1"),null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null;if(i>=37808&&i<=37814||i>=37840&&i<=37846)return a=s.get("WEBGL_compressed_texture_astc"),null!==a?i:null;if(36492===i||36494===i||36495===i)return a=s.get("EXT_texture_compression_bptc"),null!==a?i:null;if(34042===i)return e.UNSIGNED_INT_24_8;if(n){if(6407===i)return e.RGB;if(6408===i)return e.RGBA}return void 0!==e[i]?e[i]:null}}}const de=16777216;class ue extends t.Mesh{constructor(e=u.ThreeD,s=!1,i=!1,n=!1,r=1,a=!0,l=!1,c=!1,h=1024,d=o.None,p=0,A=1,m=.3){super(ae,oe),this.renderer=void 0,this.splatRenderMode=e,this.dynamicMode=s,this.enableOptionalEffects=i,this.halfPrecisionCovariancesOnGPU=n,this.devicePixelRatio=r,this.enableDistancesComputationOnGPU=a,this.integerBasedDistancesComputation=l,this.antialiased=c,this.kernel2DSize=m,this.maxScreenSpaceSplatSize=h,this.logLevel=d,this.sphericalHarmonicsDegree=p,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=A,this.scenes=[],this.splatTree=null,this.baseSplatTree=null,this.splatDataTextures={},this.flameModel=null,this.expressionBSNum=0,this.bsWeight=[],this.bonesMatrix=null,this.bonesNum=null,this.bonesWeight=null,this.gaussianSplatCount=null,this.useFlameModel=!0,this.morphTargetDictionary=null,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 t.Box3,this.calculatedSceneCenter=new t.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(e,s,i){const n=[];n.length=s.length;for(let r=0;r<s.length;r++){const a=s[r],o=i[r]||{};let l=o.position||[0,0,0],c=o.rotation||[0,0,0,1],h=o.scale||[1,1,1];const d=(new t.Vector3).fromArray(l),u=(new t.Quaternion).fromArray(c),p=(new t.Vector3).fromArray(h),A=ue.createScene(a,d,u,p,o.splatAlphaRemovalThreshold||1,o.opacity,o.visible);e.add(A),n[r]=A}return n}static createScene(e,t,s,i,n,r=1,a=!0){return new $(e,t,s,i,n,r,a)}static buildSplatIndexMaps(e){const t=[],s=[];let i=0;for(let n=0;n<e.length;n++){const r=e[n].getMaxSplatCount();for(let e=0;e<r;e++)t[i]=e,s[i]=n,i++}return{localSplatIndexMap:t,sceneIndexMap:s}}buildSplatTree=(e=[],s,i)=>new Promise(n=>{this.disposeSplatTree(),this.baseSplatTree=new se(8,1e3);const r=performance.now(),a=new t.Vector4;this.baseSplatTree.processSplatMesh(this,t=>{this.getSplatColor(t,a);const s=this.getSceneIndexForSplat(t),i=e[s]||1;return a.w>=i},s,i).then(()=>{const e=performance.now()-r;if(this.logLevel>=o.Info&&console.log("SplatTree build: "+e+" ms"),this.disposed)n();else{this.splatTree=this.baseSplatTree,this.baseSplatTree=null;let e=0,t=0,s=0;this.splatTree.visitLeaves(i=>{const n=i.data.indexes.length;n>0&&(t+=n,s++,e++)}),this.logLevel>=o.Info&&(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()}`)),n()}})});build(e,s,i=!0,n=!1,r,a,o=!0){this.sceneOptions=s,this.finalBuild=n;const l=ue.getTotalMaxSplatCountForSplatBuffers(e),c=ue.buildScenes(this,e,s);if(i)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 t of e){const e=t.getMinSphericalHarmonicsDegree();e<h&&(h=e)}this.minSphericalHarmonicsDegree=Math.min(h,this.sphericalHarmonicsDegree);let d=!1;if(e.length!==this.lastBuildScenes.length)d=!0;else for(let t=0;t<e.length;t++){if(e[t]!==this.lastBuildScenes[t].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 t.Box3,o||(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=ee.build(l),this.splatRenderMode===u.ThreeD?this.material=ne.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize,this.useFlameModel):this.material=re.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const s=ue.buildSplatIndexMaps(e);this.globalSplatIndexToLocalSplatIndexMap=s.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=s.sceneIndexMap}const A=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=A,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,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.flameModelPosTexture.texture.needsUpdate=!0,this.splatDataTextures.flameModelPosTexture.texture.onUpdate=()=>{e(this.splatDataTextures.flameModelPosTexture.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 t.Box3,this.calculatedSceneCenter=new t.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!==ae&&(this.geometry.dispose(),this.geometry=null),this.material&&(this.material.dispose(),this.material=null)}disposeTextures(){for(let e in this.splatDataTextures)if(Object.hasOwn(this.splatDataTextures,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:i,sceneIndexes:n}=this.getDataForDistancesComputation(s,t-1);return this.enableDistancesComputationOnGPU&&this.refreshGPUBuffersForDistancesComputation(i,n,e),{from:s,to:t-1,count:t-s,centers:i,sceneIndexes:n}}refreshGPUBuffersForDistancesComputation(e,t,s=!1){const i=s?this.lastBuildSplatCount:0;this.updateGPUCentersBufferForDistancesComputation(s,e,i),this.updateGPUTransformIndexesBufferForDistancesComputation(s,t,i)}refreshDataTexturesFromSplatBuffers(e){const t=this.getSplatCount(!0),s=this.lastBuildSplatCount,i=t-1;e?this.updateBaseDataFromSplatBuffers(s,i):(this.setupDataTextures(),this.updateBaseDataFromSplatBuffers()),this.updateDataTexturesFromBaseData(s,i),this.updateVisibleRegion(e)}setupDataTextures(){const e=this.getMaxSplatCount(),s=this.getSplatCount(!0);this.disposeTextures();const i=(s,i)=>{const n=new t.Vector2(4096,1024);for(;n.x*n.y*s<e*i;)n.y*=2;return n},n=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:i(t,6)}};let r=this.getTargetCovarianceCompressionLevel();const a=this.getTargetSphericalHarmonicsCompressionLevel();let o,l,c;if(this.splatRenderMode===u.ThreeD){const t=n(r);t.texSize.x*t.texSize.y>de&&0===r&&(r=1),o=new Float32Array(6*e)}else l=new Float32Array(3*e),c=new Float32Array(4*e);const h=new Float32Array(3*e),d=new Uint8Array(4*e);let p=Float32Array;1===a?p=Uint16Array:2===a&&(p=Uint8Array);const A=B(this.minSphericalHarmonicsDegree),m=this.minSphericalHarmonicsDegree?new p(e*A):void 0,g=i(4,4),f=new Uint32Array(g.x*g.y*4);ue.updateCenterColorsPaddedData(0,s-1,h,d,f);const S=new t.DataTexture(f,g.x,g.y,t.RGBAIntegerFormat,t.UnsignedIntType);if(S.internalFormat="RGBA32UI",S.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=S,this.material.uniforms.centersColorsTextureSize.value.copy(g),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:o,scales:l,rotations:c,centers:h,colors:d,sphericalHarmonics:m},centerColors:{data:f,texture:S,size:g}},this.splatRenderMode===u.ThreeD){const e=n(r),s=e.elementsPerTexelStored,i=e.texSize;const a=r>=1?8:4,l=new(r>=1?Uint32Array:Float32Array)(i.x*i.y*a);let c;if(0===r?l.set(o):ue.updatePaddedCompressedCovariancesTextureData(o,l,0,0,o.length),r>=1)c=new t.DataTexture(l,i.x,i.y,t.RGBAIntegerFormat,t.UnsignedIntType),c.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=c;else{c=new t.DataTexture(l,i.x,i.y,t.RGBAFormat,t.FloatType),this.material.uniforms.covariancesTexture.value=c;const e=new t.DataTexture(new Uint32Array(32),2,2,t.RGBAIntegerFormat,t.UnsignedIntType);e.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=e,e.needsUpdate=!0}c.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=r>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(i),this.splatDataTextures.covariances={data:l,texture:c,size:i,compressionLevel:r,elementsPerTexelStored:s,elementsPerTexelAllocated:a}}else{const e=i(4,6);let n=Float32Array,r=t.FloatType;const a=new n(e.x*e.y*4);ue.updateScaleRotationsPaddedData(0,s-1,l,c,a);const o=new t.DataTexture(a,e.x,e.y,t.RGBAFormat,r);o.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=o,this.material.uniforms.scaleRotationsTextureSize.value.copy(e),this.splatDataTextures.scaleRotations={data:a,texture:o,size:e,compressionLevel:0}}if(m){const e=2===a?t.UnsignedByteType:t.HalfFloatType;let n=A;n%2!=0&&n++;const r=2===this.minSphericalHarmonicsDegree?4:2,o=4===r?t.RGBAFormat:t.RGFormat;let l=i(r,n);if(l.x*l.y<=de){const i=new p(l.x*l.y*r);for(let e=0;e<s;e++){const t=A*e,s=n*e;for(let e=0;e<A;e++)i[s+e]=m[t+e]}const c=new t.DataTexture(i,l.x,l.y,o,e);c.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=c,this.splatDataTextures.sphericalHarmonics={componentCount:A,paddedComponentCount:n,data:i,textureCount:1,texture:c,size:l,compressionLevel:a,elementsPerTexel:r}}else{const c=A/3;n=c,n%2!=0&&n++,l=i(r,n);const h=l.x*l.y*r,d=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],u=[],g=[];for(let i=0;i<3;i++){const r=new p(h);u.push(r);for(let e=0;e<s;e++){const t=A*e,s=n*e;if(c>=3){for(let e=0;e<3;e++)r[s+e]=m[t+3*i+e];if(c>=8)for(let e=0;e<5;e++)r[s+3+e]=m[t+9+5*i+e]}}const a=new t.DataTexture(r,l.x,l.y,o,e);g.push(a),a.needsUpdate=!0,d[i].value=a}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:A,componentCountPerChannel:c,paddedComponentCount:n,data:u,textureCount:3,textures:g,size:l,compressionLevel:a,elementsPerTexel:r}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(l),this.material.uniforms.sphericalHarmonics8BitMode.value=2===a?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 C=i(1,4),x=new Uint32Array(C.x*C.y*1);for(let e=0;e<s;e++)x[e]=this.globalSplatIndexToSceneIndexMap[e];const y=new t.DataTexture(x,C.x,C.y,t.RedIntegerFormat,t.UnsignedIntType);y.internalFormat="R32UI",y.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=y,this.material.uniforms.sceneIndexesTextureSize.value.copy(C),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:x,texture:y,size:C},this.material.uniforms.sceneCount.value=this.scenes.length,this.expressionBSNum=this.flameModel.geometry.morphAttributes.position.length,this.material.uniforms.bsCount.value=this.expressionBSNum,this.flameModel.skeleton.bones.forEach((e,t)=>{"head"==e.name&&(this.material.uniforms.headBoneIndex.value=t)}),this.buildModelTexture(this.flameModel),this.buildBoneMatrixTexture(),this.useFlameModel&&this.buildBoneWeightTexture(this.flameModel)}buildBoneMatrixTexture(){if(!this.bsWeight)return;const e=new t.Vector2(4,32);let s=new Float32Array(this.bonesMatrix),i=new Uint32Array(e.x*e.y*4);if(this.morphTargetDictionary=this.flameModel.morphTargetDictionary,this.useFlameModel){for(let e=0;e<16*this.bonesNum;e++)i[e]=O(s[e]);this.flameModel&&this.flameModel.skeleton&&(this.material.uniforms.boneTexture0.value=this.flameModel.skeleton.boneTexture,this.material.uniforms.bindMatrix.value=this.flameModel.bindMatrix,this.material.uniforms.bindMatrixInverse.value=this.flameModel.bindMatrixInverse)}for(const e in this.bsWeight)if(Object.hasOwn(this.bsWeight,e)){const t=this.bsWeight[e];i[this.morphTargetDictionary[e]+16*this.bonesNum]=O(t)}const n=new t.DataTexture(i,e.x,e.y,t.RGBAIntegerFormat,t.UnsignedIntType);n.internalFormat="RGBA32UI",n.needsUpdate=!0,this.material.uniforms.boneTexture.value=n,this.material.uniforms.boneTextureSize.value.copy(e),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneMatrix={data:i,texture:n,size:e},this.splatDataTextures.baseData.boneMatrix=i}updateBoneMatrixTexture(e=!1){if(this.bsWeight&&this.morphTargetDictionary){if(1==e){let e=new Float32Array(this.bonesMatrix);for(let t=0;t<16*this.bonesNum;t++)this.splatDataTextures.baseData.boneMatrix[t]=O(e[t])}for(const e in this.bsWeight)if(Object.hasOwn(this.bsWeight,e)){const t=this.bsWeight[e],s=this.morphTargetDictionary[e];this.splatDataTextures.baseData.boneMatrix[s+16*this.bonesNum]=O(t)}this.splatDataTextures.boneMatrix.texture.data=this.splatDataTextures.baseData.boneMatrix,this.splatDataTextures.boneMatrix.texture.needsUpdate=!0,this.material.uniforms.boneTexture.value=this.splatDataTextures.boneMatrix.texture,this.flameModel.skeleton&&(this.material.uniforms.boneTexture0.value=this.flameModel.skeleton.boneTexture,this.material.uniforms.bindMatrix.value=this.flameModel.bindMatrix,this.material.uniforms.bindMatrixInverse.value=this.flameModel.bindMatrixInverse),this.material.uniformsNeedUpdate=!0}}buildBoneWeightTexture(e){let s=e.geometry.attributes.position.array.length/3;const i=new t.Vector2(512,512);let n=new Float32Array(i.x*i.y*4),r=new Uint32Array(i.x*i.y*4);for(let e=0;e<s;e++)n[8*e+0]=this.bonesWeight[e][0],n[8*e+1]=this.bonesWeight[e][1],n[8*e+2]=this.bonesWeight[e][2],n[8*e+3]=this.bonesWeight[e][3],n[8*e+4]=this.bonesWeight[e][4],r[8*e+0]=O(this.bonesWeight[e][0]),r[8*e+1]=O(this.bonesWeight[e][1]),r[8*e+2]=O(this.bonesWeight[e][2]),r[8*e+3]=O(this.bonesWeight[e][3]),r[8*e+4]=O(this.bonesWeight[e][4]);const a=new t.DataTexture(r,i.x,i.y,t.RGBAIntegerFormat,t.UnsignedIntType);a.internalFormat="RGBA32UI",a.needsUpdate=!0,this.material.uniforms.boneWeightTexture.value=a,this.material.uniforms.boneWeightTextureSize.value.copy(i),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneWeight={data:r,texture:a,size:i},this.splatDataTextures.baseData.boneWeight=r}buildModelTexture(e){const s=new t.Vector2(4096,2048);var i=e.geometry.attributes.position.array,n=[];let r=i.length/3,a=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach((t,s)=>{const i=e.morphTargetDictionary[t];var r=e.geometry.morphAttributes.position[i];n=n.concat(Array.from(r.array))}),n=n.concat(Array.from(i));let o=new Float32Array(s.x*s.y*4),l=new Uint32Array(s.x*s.y*4);for(let e=0;e<r*(a+1);e++)o[4*e+0]=n[3*e+0],o[4*e+1]=n[3*e+1],o[4*e+2]=n[3*e+2],l[4*e+0]=O(o[4*e+0]),l[4*e+1]=O(o[4*e+1]),l[4*e+2]=O(o[4*e+2]);const c=new t.DataTexture(l,s.x,s.y,t.RGBAIntegerFormat,t.UnsignedIntType);c.internalFormat="RGBA32UI",c.needsUpdate=!0,this.material.uniforms.flameModelTexture.value=c,this.material.uniforms.flameModelTextureSize.value.copy(s),this.material.uniformsNeedUpdate=!0,this.material.uniforms.gaussianSplatCount.value=this.gaussianSplatCount,this.splatDataTextures.flameModel={data:l,texture:c,size:s},this.splatDataTextures.baseData.flameModelPos=o}updateTetureAfterBSAndSkeleton(e,s,i=!0){const n=new t.Matrix4;this.getSceneTransform(0,n),this.getScene(0).splatBuffer.fillSplatCenterArray(this.morphedMesh,this.splatDataTextures.baseData.centers,n,e,s,0);const r=this.splatDataTextures.centerColors,a=r.data,o=r.texture;ue.updateCenterColorsPaddedData(e,s,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,a);const l=this.renderer?this.renderer.properties.get(o):null;l&&l.__webglTexture?this.updateDataTexture(a,r.texture,r.size,l,4,4,4,e,s):o.needsUpdate=!0,this.updateBoneMatrixTexture(i)}updateBaseDataFromSplatBuffers(e,t){const s=this.splatDataTextures.covariances,i=s?s.compressionLevel:void 0,n=this.splatDataTextures.scaleRotations,r=n?n.compressionLevel:void 0,a=this.splatDataTextures.sphericalHarmonics,o=a?a.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,this.splatDataTextures.baseData.flameModelPos,void 0,i,r,o,e,t,e)}updateDataTexturesFromBaseData(e,t){const s=this.splatDataTextures.covariances,i=s?s.compressionLevel:void 0,n=this.splatDataTextures.scaleRotations,r=n?n.compressionLevel:void 0,a=this.splatDataTextures.sphericalHarmonics,o=a?a.compressionLevel:0,l=this.splatDataTextures.flameModel,c=l.data,h=l.texture,d=this.renderer?this.renderer.properties.get(h):null;d&&d.__webglTexture?this.updateDataTexture(c,l.texture,l.size,d,4,4,3,e,t):h.needsUpdate=!0;const u=this.splatDataTextures.centerColors,p=u.data,A=u.texture;ue.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,p);const m=this.renderer?this.renderer.properties.get(A):null;if(m&&m.__webglTexture?this.updateDataTexture(p,u.texture,u.size,m,4,4,4,e,t):A.needsUpdate=!0,s){const n=s.texture,r=6*e,a=6*t;if(0===i)for(let e=r;e<=a;e++){const t=this.splatDataTextures.baseData.covariances[e];s.data[e]=t}else ue.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,s.data,e*s.elementsPerTexelAllocated,r,a);const o=this.renderer?this.renderer.properties.get(n):null;o&&o.__webglTexture?0===i?this.updateDataTexture(s.data,s.texture,s.size,o,s.elementsPerTexelStored,6,4,e,t):this.updateDataTexture(s.data,s.texture,s.size,o,s.elementsPerTexelAllocated,s.elementsPerTexelAllocated,2,e,t):n.needsUpdate=!0}if(n){const s=n.data,i=n.texture,a=6,o=0===r?4:2;ue.updateScaleRotationsPaddedData(e,t,this.splatDataTextures.baseData.scales,this.splatDataTextures.baseData.rotations,s);const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(s,n.texture,n.size,l,4,a,o,e,t):i.needsUpdate=!0}const g=this.splatDataTextures.baseData.sphericalHarmonics;if(g){let s=4;1===o?s=2:2===o&&(s=1);const i=(i,n,r,a,o)=>{const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(a,i,n,l,r,o,s,e,t):i.needsUpdate=!0},n=a.componentCount,r=a.paddedComponentCount;if(1===a.textureCount){const s=a.data;for(let i=e;i<=t;i++){const e=n*i,t=r*i;for(let i=0;i<n;i++)s[t+i]=g[e+i]}i(a.texture,a.size,a.elementsPerTexel,s,r)}else{const s=a.componentCountPerChannel;for(let o=0;o<3;o++){const l=a.data[o];for(let i=e;i<=t;i++){const e=n*i,t=r*i;if(s>=3){for(let s=0;s<3;s++)l[t+s]=g[e+3*o+s];if(s>=8)for(let s=0;s<5;s++)l[t+3+s]=g[e+9+5*o+s]}}i(a.textures[o],a.size,a.elementsPerTexel,l,r)}}}const f=this.splatDataTextures.sceneIndexes,S=f.data;for(let e=this.lastBuildSplatCount;e<=t;e++)S[e]=this.globalSplatIndexToSceneIndexMap[e];const C=f.texture,x=this.renderer?this.renderer.properties.get(C):null;x&&x.__webglTexture?this.updateDataTexture(S,f.texture,f.size,x,1,1,1,this.lastBuildSplatCount,t):C.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,i,n){const r=n/i,a=e*r,o=Math.floor(a/s),l=o*s*i,c=t*r,h=Math.floor(c/s);return{dataStart:l,dataEnd:h*s*i+s*i,startRow:o,endRow:h}}updateDataTexture(e,t,s,i,n,r,a,o,l){const c=this.renderer.getContext(),h=ue.computeTextureUpdateRegion(o,l,s.x,n,r),d=h.dataEnd-h.dataStart,u=new e.constructor(e.buffer,h.dataStart*a,d),p=h.endRow-h.startRow+1,A=this.webGLUtils.convert(t.type),m=this.webGLUtils.convert(t.format,t.colorSpace),g=c.getParameter(c.TEXTURE_BINDING_2D);c.bindTexture(c.TEXTURE_2D,i.__webglTexture),c.texSubImage2D(c.TEXTURE_2D,0,0,h.startRow,s.x,p,m,A,u),c.bindTexture(c.TEXTURE_2D,g)}static updatePaddedCompressedCovariancesTextureData(e,t,s,i,n){let r=new DataView(t.buffer),a=s,o=0;for(let t=i;t<=n;t+=2)r.setUint16(2*a,e[t],!0),r.setUint16(2*a+2,e[t+1],!0),a+=2,o++,o>=3&&(a+=2,o=0)}static updateCenterColorsPaddedData(e,t,s,i,n){for(let r=e;r<=t;r++){const e=4*r,t=3*r,a=4*r;n[a]=Q(i,e),n[a+1]=O(s[t]),n[a+2]=O(s[t+1]),n[a+3]=O(s[t+2])}}static updateScaleRotationsPaddedData(e,t,s,i,n){for(let r=e;r<=t;r++){const e=3*r,t=4*r,a=6*r;n[a]=s[e],n[a+1]=s[e+1],n[a+2]=s[e+2],n[a+3]=i[t],n[a+4]=i[t+1],n[a+5]=i[t+2]}}updateVisibleRegion(e){const s=this.getSplatCount(!0),i=new t.Vector3;if(!e){const e=new t.Vector3;this.scenes.forEach(t=>{e.add(t.splatBuffer.sceneCenter)}),e.multiplyScalar(1/this.scenes.length),this.calculatedSceneCenter.copy(e),this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter),this.material.uniformsNeedUpdate=!0}for(let t=e?this.lastBuildSplatCount:0;t<s;t++){this.getSplatCenter(this.morphedMesh,t,i,!0);const e=i.sub(this.calculatedSceneCenter).length();e>this.maxSplatDistanceFromSceneCenter&&(this.maxSplatDistanceFromSceneCenter=e)}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=d.Default){const t=.012*this.sceneFadeInRateMultiplier,s=.003*this.sceneFadeInRateMultiplier,i=this.finalBuild?t:s,n=e===d.Default?i:s;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*n+this.visibleRegionFadeStartRadius;const r=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,a=r||e===d.Instant?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=a,this.material.uniformsNeedUpdate=!0,this.visibleRegionChanging=!r}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 e=new t.Vector2;return function(t,s,i,n,r,a){if(this.getSplatCount()>0){if(e.set(t.x*this.devicePixelRatio,t.y*this.devicePixelRatio),this.material.uniforms.viewport.value.copy(e),this.material.uniforms.basisViewport.value.set(1/e.x,1/e.y),this.material.uniforms.focal.value.set(s,i),this.material.uniforms.orthographicMode.value=n?1:0,this.material.uniforms.orthoZoom.value=r,this.material.uniforms.inverseFocalAdjustment.value=a,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]=x(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?ue.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 ue.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(e){if(e!==this.renderer){this.renderer=e;const t=this.renderer.getContext(),s=new le(t),i=new ce(t,s,{});if(s.init(i),this.webGLUtils=new he(t,s,i),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()=>{const t=this.getMaxSplatCount();if(!this.renderer)return;const s=this.lastRenderer!==this.renderer,i=e!==t;if(!s&&!i)return;s?this.disposeDistancesComputationGPUResources():i&&this.disposeDistancesComputationGPUBufferResources();const n=this.renderer.getContext(),r=(e,t,s)=>{const i=e.createShader(t);if(!i)return console.error("Fatal error: gl could not create a shader object."),null;e.shaderSource(i,s),e.compileShader(i);if(!e.getShaderParameter(i,e.COMPILE_STATUS)){let s="unknown";t===e.VERTEX_SHADER?s="vertex shader":t===e.FRAGMENT_SHADER&&(s="fragement shader");const n=e.getShaderInfoLog(i);return console.error("Failed to compile "+s+" with these errors:"+n),e.deleteShader(i),null}return i};let a;this.integerBasedDistancesComputation?(a="#version 300 es\n in ivec4 center;\n flat out int distance;",this.dynamicMode?a+=`\n in uint sceneIndex;\n uniform ivec4 transforms[${p.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 `:a+="\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "):(a="#version 300 es\n in vec4 center;\n flat out float distance;",this.dynamicMode?a+=`\n in uint sceneIndex;\n uniform mat4 transforms[${p.MaxScenes}];\n void main(void) {\n vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n `:a+="\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 o=n.getParameter(n.VERTEX_ARRAY_BINDING),l=n.getParameter(n.CURRENT_PROGRAM),c=!!l&&n.getProgramParameter(l,n.DELETE_STATUS);if(s&&(this.distancesTransformFeedback.vao=n.createVertexArray()),n.bindVertexArray(this.distancesTransformFeedback.vao),s){const e=n.createProgram(),t=r(n,n.VERTEX_SHADER,a),s=r(n,n.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.");n.attachShader(e,t),n.attachShader(e,s),n.transformFeedbackVaryings(e,["distance"],n.SEPARATE_ATTRIBS),n.linkProgram(e);if(!n.getProgramParameter(e,n.LINK_STATUS)){const i=n.getProgramInfoLog(e);throw console.error("Fatal error: Failed to link program: "+i),n.deleteProgram(e),n.deleteShader(s),n.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(n.useProgram(this.distancesTransformFeedback.program),this.distancesTransformFeedback.centersLoc=n.getAttribLocation(this.distancesTransformFeedback.program,"center"),this.dynamicMode){this.distancesTransformFeedback.sceneIndexesLoc=n.getAttribLocation(this.distancesTransformFeedback.program,"sceneIndex");for(let e=0;e<this.scenes.length;e++)this.distancesTransformFeedback.transformsLocs[e]=n.getUniformLocation(this.distancesTransformFeedback.program,`transforms[${e}]`)}else this.distancesTransformFeedback.modelViewProjLoc=n.getUniformLocation(this.distancesTransformFeedback.program,"modelViewProj");(s||i)&&(this.distancesTransformFeedback.centersBuffer=n.createBuffer(),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&&(this.distancesTransformFeedback.sceneIndexesBuffer=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),n.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),n.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,n.UNSIGNED_INT,0,0))),(s||i)&&(this.distancesTransformFeedback.outDistancesBuffer=n.createBuffer()),n.bindBuffer(n.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),n.bufferData(n.ARRAY_BUFFER,4*t,n.STATIC_READ),s&&(this.distancesTransformFeedback.id=n.createTransformFeedback()),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),n.bindBufferBase(n.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),l&&!0!==c&&n.useProgram(l),o&&n.bindVertexArray(o),this.lastRenderer=this.renderer,e=t}}();updateGPUCentersBufferForDistancesComputation(e,t,s){if(!this.renderer)return;const i=this.renderer.getContext(),n=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const r=this.integerBasedDistancesComputation?Uint32Array:Float32Array,a=16*s;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,a,t);else{const e=new r(16*this.getMaxSplatCount());e.set(t),i.bufferData(i.ARRAY_BUFFER,e,i.STATIC_DRAW)}i.bindBuffer(i.ARRAY_BUFFER,null),n&&i.bindVertexArray(n)}updateGPUTransformIndexesBufferForDistancesComputation(e,t,s){if(!this.renderer||!this.dynamicMode)return;const i=this.renderer.getContext(),n=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao);const r=4*s;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,r,t);else{const e=new Uint32Array(4*this.getMaxSplatCount());e.set(t),i.bufferData(i.ARRAY_BUFFER,e,i.STATIC_DRAW)}i.bindBuffer(i.ARRAY_BUFFER,null),n&&i.bindVertexArray(n)}getSceneIndexes(e,t){let s;s=new Uint32Array(t-e+1);for(let i=e;i<=t;i++)s[i]=this.globalSplatIndexToSceneIndexMap[i];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 i=0;i<16;i++)e[16*t+i]=s[i]}t.set(e)}}();computeDistancesOnGPU=function(){const e=new t.Matrix4;return(t,s)=>{if(!this.renderer)return;const i=this.renderer.getContext(),n=i.getParameter(i.VERTEX_ARRAY_BINDING),r=i.getParameter(i.CURRENT_PROGRAM),a=!!r&&i.getProgramParameter(r,i.DELETE_STATUS);if(i.bindVertexArray(this.distancesTransformFeedback.vao),i.useProgram(this.distancesTransformFeedback.program),i.enable(i.RASTERIZER_DISCARD),this.dynamicMode)for(let s=0;s<this.scenes.length;s++)if(e.copy(this.getScene(s).transform),e.premultiply(t),this.integerBasedDistancesComputation){const t=ue.getIntegerMatrixArray(e),n=[t[2],t[6],t[10],t[14]];i.uniform4i(this.distancesTransformFeedback.transformsLocs[s],n[0],n[1],n[2],n[3])}else i.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[s],!1,e.elements);else if(this.integerBasedDistancesComputation){const e=ue.getIntegerMatrixArray(t),s=[e[2],e[6],e[10]];i.uniform3i(this.distancesTransformFeedback.modelViewProjLoc,s[0],s[1],s[2])}else{const e=[t.elements[2],t.elements[6],t.elements[10]];i.uniform3f(this.distancesTransformFeedback.modelViewProjLoc,e[0],e[1],e[2])}i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),i.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc),this.integerBasedDistancesComputation?i.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc,4,i.INT,0,0):i.vertexAttribPointer(this.distancesTransformFeedback.centersLoc,4,i.FLOAT,!1,0,0),this.dynamicMode&&(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),i.enableVertexAttribArray(this.distancesTransformFeedback.sceneIndexesLoc),i.vertexAttribIPointer(this.distancesTransformFeedback.sceneIndexesLoc,1,i.UNSIGNED_INT,0,0)),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,this.distancesTransformFeedback.id),i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,0,this.distancesTransformFeedback.outDistancesBuffer),i.beginTransformFeedback(i.POINTS),i.drawArrays(i.POINTS,0,this.getSplatCount()),i.endTransformFeedback(),i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,0,null),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),i.disable(i.RASTERIZER_DISCARD);const o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);i.flush();const l=new Promise(e=>{const t=()=>{if(this.disposed)e();else{const n=0,r=0;switch(i.clientWaitSync(o,r,n)){case i.TIMEOUT_EXPIRED:return this.computeDistancesOnGPUSyncTimeout=setTimeout(t),this.computeDistancesOnGPUSyncTimeout;case i.WAIT_FAILED:throw new Error("should never get here");default:{this.computeDistancesOnGPUSyncTimeout=null,i.deleteSync(o);const t=i.getParameter(i.VERTEX_ARRAY_BINDING);i.bindVertexArray(this.distancesTransformFeedback.vao),i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.outDistancesBuffer),i.getBufferSubData(i.ARRAY_BUFFER,0,s),i.bindBuffer(i.ARRAY_BUFFER,null),t&&i.bindVertexArray(t),e()}}}};this.computeDistancesOnGPUSyncTimeout=setTimeout(t)});return r&&!0!==a&&i.useProgram(r),n&&i.bindVertexArray(n),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(e,s,i,n,r,a,o,l,c=0,h=0,d=1,p,A,m=0,g){const f=new t.Vector3;f.x=void 0,f.y=void 0,this.splatRenderMode===u.ThreeD?f.z=void 0:f.z=1;const S=new t.Matrix4;let C=0,x=this.scenes.length-1;null!=g&&g>=0&&g<=this.scenes.length&&(C=g,x=g);for(let t=C;t<=x;t++){null==l&&(l=!this.dynamicMode);const o=this.getScene(t),u=o.splatBuffer;let g;if(l&&(this.getSceneTransform(t,S),g=S),e&&u.fillSplatCovarianceArray(e,g,p,A,m,c),s||i){if(!s||!i)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');u.fillSplatScaleRotationArray(s,i,g,p,A,m,h,f)}n&&u.fillSplatCenterArray(this.morphedMesh,n,g,p,A,m),r&&u.fillSplatColorArray(r,o.minimumAlpha,p,A,m),a&&u.fillSphericalHarmonicsArray(a,this.minSphericalHarmonicsDegree,g,p,A,m,d),m+=u.getSplatCount()}}morphedMesh;getIntegerCenters(e,t,s=!1){const i=t-e+1,n=new Float32Array(3*i);let r;this.fillSplatDataArrays(null,null,null,n,null,null,void 0,void 0,void 0,void 0,e);let a=s?4:3;r=new Int32Array(i*a);for(let e=0;e<i;e++){for(let t=0;t<3;t++)r[e*a+t]=Math.round(1e3*n[3*e+t]);s&&(r[e*a+3]=1e3)}return r}getFloatCenters(e,t,s=!1){const i=t-e+1,n=new Float32Array(3*i);if(this.fillSplatDataArrays(null,null,null,n,null,null,void 0,void 0,void 0,void 0,e),!s)return n;let r=new Float32Array(4*i);for(let e=0;e<i;e++){for(let t=0;t<3;t++)r[4*e+t]=n[3*e+t];r[4*e+3]=1}return r}getSplatCenter=function(){const e={};return function(t,s,i,n){this.getLocalSplatParameters(s,e,n),e.splatBuffer.getSplatCenter(t,e.localIndex,i,e.sceneTransform)}}();getSplatScaleAndRotation=function(){const e={},s=new t.Vector3;return function(t,i,n,r){this.getLocalSplatParameters(t,e,r),s.x=void 0,s.y=void 0,s.z=void 0,this.splatRenderMode===u.TwoD&&(s.z=0),e.splatBuffer.getSplatScaleAndRotation(e.localIndex,i,n,e.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(e=!1,s){let i=this.getSplatCount();if(null!=s){if(s<0||s>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");i=this.scenes[s].splatBuffer.getSplatCount()}const n=new Float32Array(3*i);this.fillSplatDataArrays(null,null,null,n,null,null,e,void 0,void 0,void 0,void 0,s);const r=new t.Vector3,a=new t.Vector3;for(let e=0;e<i;e++){const t=3*e,s=n[t],i=n[t+1],o=n[t+2];(0===e||s<r.x)&&(r.x=s),(0===e||i<r.y)&&(r.y=i),(0===e||o<r.z)&&(r.z=o),(0===e||s>a.x)&&(a.x=s),(0===e||i>a.y)&&(a.y=i),(0===e||o>a.z)&&(a.z=o)}return new t.Box3(r,a)}}class pe extends Error{constructor(e){super(e),this.name="DirectLoadError"}}class Ae{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=B(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=B(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=Ae.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(e),e}addSplatFromComonents(e,t,s,i,n,r,a,o,l,c,h,d,u,p,...A){const m=[e,t,s,i,n,r,a,o,l,c,h,d,u,p,...this.defaultSphericalHarmonics];for(let e=0;e<A.length&&e<this.sphericalHarmonicsCount;e++)m[e]=A[e];return this.addSplat(m),m}addSplatFromArray(e,t){const s=e.splats[t],i=Ae.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<s.length;e++)i[e]=s[e];this.addSplat(i)}}const me=(e,t,s,i,n=0)=>{const r=new Uint8Array(e,t),a=new Uint8Array(s,i);for(let e=0;e<n;e++)a[e]=r[e]},ge=t.DataUtils.toHalfFloat.bind(t.DataUtils),fe=t.DataUtils.fromHalfFloat.bind(t.DataUtils),Se=(e,s,i=!1,n,r)=>0===s?e:1===s||2===s&&!i?t.DataUtils.fromHalfFloat(e):2===s?xe(e,n,r):void 0,Ce=(e,t,s)=>{e=x(e,t,s);const i=s-t;return x(Math.floor((e-t)/i*255),0,255)},xe=(e,t,s)=>e/255*(s-t)+t,ye=(e,t,s,i=!1)=>0===s?e.getFloat32(4*t,!0):1===s||2===s&&!i?e.getUint16(2*t,!0):e.getUint8(t,!0);class ve{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 i=e.fullBucketCount*e.bucketSize;if(t<i)s=Math.floor(t/e.bucketSize);else{let n=i;s=e.fullBucketCount;let r=0;for(;n<e.splatCount;){let i=e.partiallyFilledBucketLengths[r];if(t>=n&&t<n+i)break;n+=i,s++,r++}}return s}getSplatCenter(e,t,s,i){const n=this.globalSplatIndexToSectionMap[t],r=this.sections[n],a=t-r.splatCountOffset,o=r.bytesPerSplat*a,l=new DataView(this.bufferData,r.dataBase+o),c=ye(l,0,this.compressionLevel),h=ye(l,1,this.compressionLevel),d=ye(l,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(r,a)*ve.BucketStorageSizeFloats,t=r.compressionScaleFactor,i=r.compressionScaleRange;s.x=(c-i)*t+r.bucketArray[e],s.y=(h-i)*t+r.bucketArray[e+1],s.z=(d-i)*t+r.bucketArray[e+2]}else s.x=c,s.y=h,s.z=d;s.x+=e[3*t+0],s.y+=e[3*t+1],s.z+=e[3*t+2],i&&s.applyMatrix4(i)}getSplatScaleAndRotation=function(){const e=new t.Matrix4,s=new t.Matrix4,i=new t.Matrix4,n=new t.Vector3,r=new t.Vector3,a=new t.Quaternion;return function(t,o,l,c,h){const d=this.globalSplatIndexToSectionMap[t],u=this.sections[d],p=t-u.splatCountOffset,A=u.bytesPerSplat*p+ve.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,m=new DataView(this.bufferData,u.dataBase+A);r.set(Se(ye(m,0,this.compressionLevel),this.compressionLevel),Se(ye(m,1,this.compressionLevel),this.compressionLevel),Se(ye(m,2,this.compressionLevel),this.compressionLevel)),h&&(void 0!==h.x&&(r.x=h.x),void 0!==h.y&&(r.y=h.y),void 0!==h.z&&(r.z=h.z)),a.set(Se(ye(m,4,this.compressionLevel),this.compressionLevel),Se(ye(m,5,this.compressionLevel),this.compressionLevel),Se(ye(m,6,this.compressionLevel),this.compressionLevel),Se(ye(m,3,this.compressionLevel),this.compressionLevel)),c?(e.makeScale(r.x,r.y,r.z),s.makeRotationFromQuaternion(a),i.copy(e).multiply(s).multiply(c),i.decompose(n,l,o)):(o.copy(r),l.copy(a))}}();getSplatColor(e,t){const s=this.globalSplatIndexToSectionMap[e],i=this.sections[s],n=e-i.splatCountOffset,r=i.bytesPerSplat*n+ve.CompressionLevels[this.compressionLevel].ColorOffsetBytes,a=new Uint8Array(this.bufferData,i.dataBase+r,4);t.set(a[0],a[1],a[2],a[3])}fillSplatCenterArray(e,s,i,n,r,a){const o=this.splatCount;n=n||0,r=r||o-1,void 0===a&&(a=n);const l=new t.Vector3;for(let t=n;t<=r;t++){const r=this.globalSplatIndexToSectionMap[t],o=this.sections[r],c=t-o.splatCountOffset,h=(t-n+a)*ve.CenterComponentCount,d=o.bytesPerSplat*c,u=new DataView(this.bufferData,o.dataBase+d),p=ye(u,0,this.compressionLevel),A=ye(u,1,this.compressionLevel),m=ye(u,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(o,c)*ve.BucketStorageSizeFloats,t=o.compressionScaleFactor,s=o.compressionScaleRange;l.x=(p-s)*t+o.bucketArray[e],l.y=(A-s)*t+o.bucketArray[e+1],l.z=(m-s)*t+o.bucketArray[e+2]}else l.x=p,l.y=A,l.z=m;i&&l.applyMatrix4(i),s[h]=l.x+e[3*t+0],s[h+1]=l.y+e[3*t+1],s[h+2]=l.z+e[3*t+2]}}fillSplatScaleRotationArray=function(){const e=new t.Matrix4,s=new t.Matrix4,i=new t.Matrix4,n=new t.Vector3,r=new t.Quaternion,a=new t.Vector3,o=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(t,l,c,h,d,u,p,A){const m=this.splatCount;h=h||0,d=d||m-1,void 0===u&&(u=h);const g=(e,t)=>_(e,t,p);for(let p=h;p<=d;p++){const d=this.globalSplatIndexToSectionMap[p],m=this.sections[d],f=p-m.splatCountOffset,S=m.bytesPerSplat*f+ve.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,C=(p-h+u)*ve.ScaleComponentCount,x=(p-h+u)*ve.RotationComponentCount,y=new DataView(this.bufferData,m.dataBase+S),v=A&&void 0!==A.x?A.x:ye(y,0,this.compressionLevel),I=A&&void 0!==A.y?A.y:ye(y,1,this.compressionLevel),B=A&&void 0!==A.z?A.z:ye(y,2,this.compressionLevel),T=ye(y,3,this.compressionLevel),b=ye(y,4,this.compressionLevel),D=ye(y,5,this.compressionLevel),M=ye(y,6,this.compressionLevel);n.set(Se(v,this.compressionLevel),Se(I,this.compressionLevel),Se(B,this.compressionLevel)),r.set(Se(b,this.compressionLevel),Se(D,this.compressionLevel),Se(M,this.compressionLevel),Se(T,this.compressionLevel)).normalize(),c&&(a.set(0,0,0),e.makeScale(n.x,n.y,n.z),s.makeRotationFromQuaternion(r),i.identity().premultiply(e).premultiply(s),i.premultiply(c),i.decompose(a,r,n),r.normalize()),o(r),t&&(t[C]=g(n.x,0),t[C+1]=g(n.y,0),t[C+2]=g(n.z,0)),l&&(l[x]=g(r.x,0),l[x+1]=g(r.y,0),l[x+2]=g(r.z,0),l[x+3]=g(r.w,0))}}}();static computeCovariance=function(){const e=new t.Matrix4,s=new t.Matrix3,i=new t.Matrix3,n=new t.Matrix3,r=new t.Matrix3,a=new t.Matrix3,o=new t.Matrix3;return function(t,l,c,h,d=0,u){e.makeScale(t.x,t.y,t.z),s.setFromMatrix4(e),e.makeRotationFromQuaternion(l),i.setFromMatrix4(e),n.copy(i).multiply(s),r.copy(n).transpose().premultiply(n),c&&(a.setFromMatrix4(c),o.copy(a).transpose(),r.multiply(o),r.premultiply(a)),u>=1?(h[d]=ge(r.elements[0]),h[d+1]=ge(r.elements[3]),h[d+2]=ge(r.elements[6]),h[d+3]=ge(r.elements[4]),h[d+4]=ge(r.elements[7]),h[d+5]=ge(r.elements[8])):(h[d]=r.elements[0],h[d+1]=r.elements[3],h[d+2]=r.elements[6],h[d+3]=r.elements[4],h[d+4]=r.elements[7],h[d+5]=r.elements[8])}}();fillSplatCovarianceArray(e,s,i,n,r,a){const o=this.splatCount,l=new t.Vector3,c=new t.Quaternion;i=i||0,n=n||o-1,void 0===r&&(r=i);for(let t=i;t<=n;t++){const n=this.globalSplatIndexToSectionMap[t],o=this.sections[n],h=t-o.splatCountOffset,d=(t-i+r)*ve.CovarianceComponentCount,u=o.bytesPerSplat*h+ve.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,p=new DataView(this.bufferData,o.dataBase+u);l.set(Se(ye(p,0,this.compressionLevel),this.compressionLevel),Se(ye(p,1,this.compressionLevel),this.compressionLevel),Se(ye(p,2,this.compressionLevel),this.compressionLevel)),c.set(Se(ye(p,4,this.compressionLevel),this.compressionLevel),Se(ye(p,5,this.compressionLevel),this.compressionLevel),Se(ye(p,6,this.compressionLevel),this.compressionLevel),Se(ye(p,3,this.compressionLevel),this.compressionLevel)),ve.computeCovariance(l,c,s,e,d,a)}}fillSplatColorArray(e,t,s,i,n){const r=this.splatCount;s=s||0,i=i||r-1,void 0===n&&(n=s);for(let r=s;r<=i;r++){const i=this.globalSplatIndexToSectionMap[r],a=this.sections[i],o=r-a.splatCountOffset,l=(r-s+n)*ve.ColorComponentCount,c=a.bytesPerSplat*o+ve.CompressionLevels[this.compressionLevel].ColorOffsetBytes,h=new Uint8Array(this.bufferData,a.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 e=0;e<15;e++)new t.Vector3;const e=new t.Matrix3,s=new t.Matrix4,i=new t.Vector3,n=new t.Vector3,r=new t.Quaternion,a=[],o=[],l=[],c=[],h=[],d=[],u=[],p=[],A=[],m=[],g=[],f=[],S=[],C=[],x=[],y=[],v=[],I=[],T=e=>e,b=(e,t,s,i)=>{e[0]=t,e[1]=s,e[2]=i},D=(e,t,s,i,n)=>{e[0]=ye(t,i,n,!0),e[1]=ye(t,i+s,n,!0),e[2]=ye(t,i+s+s,n,!0)},M=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},w=(e,t,s,i)=>{t[s]=i(e[0]),t[s+1]=i(e[1]),t[s+2]=i(e[2])},E=(e,t,s,i,n)=>(t[0]=Se(e[0],s,!0,i,n),t[1]=Se(e[1],s,!0,i,n),t[2]=Se(e[2],s,!0,i,n),t);return function(t,R,F,P,k,L,U){const _=this.splatCount;P=P||0,k=k||_-1,void 0===L&&(L=P),F&&R>=1&&(s.copy(F),s.decompose(i,r,n),r.normalize(),s.makeRotationFromQuaternion(r),e.setFromMatrix4(s),b(a,e.elements[4],-e.elements[7],e.elements[1]),b(o,-e.elements[5],e.elements[8],-e.elements[2]),b(l,e.elements[3],-e.elements[6],e.elements[0]));const H=e=>((e,t,s)=>Ce(fe(e),t,s))(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),O=e=>Ce(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let e=P;e<=k;e++){const s=this.globalSplatIndexToSectionMap[e],i=this.sections[s];R=Math.min(R,i.sphericalHarmonicsDegree);const n=B(R),r=e-i.splatCountOffset,b=i.bytesPerSplat*r+ve.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,k=new DataView(this.bufferData,i.dataBase+b),_=(e-P+L)*n;let Q=F?0:this.compressionLevel,z=T;Q!==U&&(1===Q?0===U?z=fe:2==U&&(z=H):0===Q&&(1===U?z=ge:2==U&&(z=O)));const V=this.minSphericalHarmonicsCoeff,N=this.maxSphericalHarmonicsCoeff;R>=1&&(D(A,k,3,0,this.compressionLevel),D(m,k,3,1,this.compressionLevel),D(g,k,3,2,this.compressionLevel),F?(E(A,A,this.compressionLevel,V,N),E(m,m,this.compressionLevel,V,N),E(g,g,this.compressionLevel,V,N),ve.rotateSphericalHarmonics3(A,m,g,a,o,l,C,x,y)):(M(A,C),M(m,x),M(g,y)),w(C,t,_,z),w(x,t,_+3,z),w(y,t,_+6,z),R>=2&&(D(A,k,5,9,this.compressionLevel),D(m,k,5,10,this.compressionLevel),D(g,k,5,11,this.compressionLevel),D(f,k,5,12,this.compressionLevel),D(S,k,5,13,this.compressionLevel),F?(E(A,A,this.compressionLevel,V,N),E(m,m,this.compressionLevel,V,N),E(g,g,this.compressionLevel,V,N),E(f,f,this.compressionLevel,V,N),E(S,S,this.compressionLevel,V,N),ve.rotateSphericalHarmonics5(A,m,g,f,S,a,o,l,c,h,d,u,p,C,x,y,v,I)):(M(A,C),M(m,x),M(g,y),M(f,v),M(S,I)),w(C,t,_+9,z),w(x,t,_+12,z),w(y,t,_+15,z),w(v,t,_+18,z),w(I,t,_+21,z)))}}}();static dot3=(e,t,s,i,n)=>{n[0]=n[1]=n[2]=0;const r=i[0],a=i[1],o=i[2];ve.addInto3(e[0]*r,e[1]*r,e[2]*r,n),ve.addInto3(t[0]*a,t[1]*a,t[2]*a,n),ve.addInto3(s[0]*o,s[1]*o,s[2]*o,n)};static addInto3=(e,t,s,i)=>{i[0]=i[0]+e,i[1]=i[1]+t,i[2]=i[2]+s};static dot5=(e,t,s,i,n,r,a)=>{a[0]=a[1]=a[2]=0;const o=r[0],l=r[1],c=r[2],h=r[3],d=r[4];ve.addInto3(e[0]*o,e[1]*o,e[2]*o,a),ve.addInto3(t[0]*l,t[1]*l,t[2]*l,a),ve.addInto3(s[0]*c,s[1]*c,s[2]*c,a),ve.addInto3(i[0]*h,i[1]*h,i[2]*h,a),ve.addInto3(n[0]*d,n[1]*d,n[2]*d,a)};static rotateSphericalHarmonics3=(e,t,s,i,n,r,a,o,l)=>{ve.dot3(e,t,s,i,a),ve.dot3(e,t,s,n,o),ve.dot3(e,t,s,r,l)};static rotateSphericalHarmonics5=(e,t,s,i,n,r,a,o,l,c,h,d,u,p,A,m,g,f)=>{const S=Math.sqrt(1/4),C=Math.sqrt(3/4),x=Math.sqrt(1/3),y=Math.sqrt(4/3),v=Math.sqrt(1/12);l[0]=S*(o[2]*r[0]+o[0]*r[2]+(r[2]*o[0]+r[0]*o[2])),l[1]=o[1]*r[0]+r[1]*o[0],l[2]=C*(o[1]*r[1]+r[1]*o[1]),l[3]=o[1]*r[2]+r[1]*o[2],l[4]=S*(o[2]*r[2]-o[0]*r[0]+(r[2]*o[2]-r[0]*o[0])),ve.dot5(e,t,s,i,n,l,p),c[0]=S*(a[2]*r[0]+a[0]*r[2]+(r[2]*a[0]+r[0]*a[2])),c[1]=a[1]*r[0]+r[1]*a[0],c[2]=C*(a[1]*r[1]+r[1]*a[1]),c[3]=a[1]*r[2]+r[1]*a[2],c[4]=S*(a[2]*r[2]-a[0]*r[0]+(r[2]*a[2]-r[0]*a[0])),ve.dot5(e,t,s,i,n,c,A),h[0]=x*(a[2]*a[0]+a[0]*a[2])+-v*(o[2]*o[0]+o[0]*o[2]+(r[2]*r[0]+r[0]*r[2])),h[1]=y*a[1]*a[0]+-x*(o[1]*o[0]+r[1]*r[0]),h[2]=a[1]*a[1]+-S*(o[1]*o[1]+r[1]*r[1]),h[3]=y*a[1]*a[2]+-x*(o[1]*o[2]+r[1]*r[2]),h[4]=x*(a[2]*a[2]-a[0]*a[0])+-v*(o[2]*o[2]-o[0]*o[0]+(r[2]*r[2]-r[0]*r[0])),ve.dot5(e,t,s,i,n,h,m),d[0]=S*(a[2]*o[0]+a[0]*o[2]+(o[2]*a[0]+o[0]*a[2])),d[1]=a[1]*o[0]+o[1]*a[0],d[2]=C*(a[1]*o[1]+o[1]*a[1]),d[3]=a[1]*o[2]+o[1]*a[2],d[4]=S*(a[2]*o[2]-a[0]*o[0]+(o[2]*a[2]-o[0]*a[0])),ve.dot5(e,t,s,i,n,d,g),u[0]=S*(o[2]*o[0]+o[0]*o[2]-(r[2]*r[0]+r[0]*r[2])),u[1]=o[1]*o[0]-r[1]*r[0],u[2]=C*(o[1]*o[1]-r[1]*r[1]),u[3]=o[1]*o[2]-r[1]*r[2],u[4]=S*(o[2]*o[2]-o[0]*o[0]-(r[2]*r[2]-r[0]*r[0])),ve.dot5(e,t,s,i,n,u,f)};static parseHeader(e){const s=new Uint8Array(e,0,ve.HeaderSizeBytes),i=new Uint16Array(e,0,ve.HeaderSizeBytes/2),n=new Uint32Array(e,0,ve.HeaderSizeBytes/4),r=new Float32Array(e,0,ve.HeaderSizeBytes/4);return{versionMajor:s[0],versionMinor:s[1],maxSectionCount:n[1],sectionCount:n[2],maxSplatCount:n[3],splatCount:n[4],compressionLevel:i[10],sceneCenter:new t.Vector3(r[6],r[7],r[8]),minSphericalHarmonicsCoeff:r[9]||-F,maxSphericalHarmonicsCoeff:r[10]||F}}static writeHeaderCountsToBuffer(e,t,s){const i=new Uint32Array(s,0,ve.HeaderSizeBytes/4);i[2]=e,i[4]=t}static writeHeaderToBuffer(e,t){const s=new Uint8Array(t,0,ve.HeaderSizeBytes),i=new Uint16Array(t,0,ve.HeaderSizeBytes/2),n=new Uint32Array(t,0,ve.HeaderSizeBytes/4),r=new Float32Array(t,0,ve.HeaderSizeBytes/4);s[0]=e.versionMajor,s[1]=e.versionMinor,s[2]=0,s[3]=0,n[1]=e.maxSectionCount,n[2]=e.sectionCount,n[3]=e.maxSplatCount,n[4]=e.splatCount,i[10]=e.compressionLevel,r[6]=e.sceneCenter.x,r[7]=e.sceneCenter.y,r[8]=e.sceneCenter.z,r[9]=e.minSphericalHarmonicsCoeff||-F,r[10]=e.maxSphericalHarmonicsCoeff||F}static parseSectionHeaders(e,t,s=0,i){const n=e.compressionLevel,r=e.maxSectionCount,a=new Uint16Array(t,s,r*ve.SectionHeaderSizeBytes/2),o=new Uint32Array(t,s,r*ve.SectionHeaderSizeBytes/4),l=new Float32Array(t,s,r*ve.SectionHeaderSizeBytes/4),c=[];let h=0,d=h/2,u=h/4,p=ve.HeaderSizeBytes+e.maxSectionCount*ve.SectionHeaderSizeBytes,A=0;for(let e=0;e<r;e++){const t=o[u+1],s=o[u+2],r=o[u+3],m=l[u+4],g=m/2,f=a[d+10],S=o[u+6]||ve.CompressionLevels[n].ScaleRange,C=o[u+8],x=o[u+9],y=4*x,v=f*r+y,I=a[d+20],{bytesPerSplat:B}=ve.calculateComponentStorage(n,I),T=B*t,b=T+v,D={bytesPerSplat:B,splatCountOffset:A,splatCount:i?t:0,maxSplatCount:t,bucketSize:s,bucketCount:r,bucketBlockSize:m,halfBucketBlockSize:g,bucketStorageSizeBytes:f,bucketsStorageSizeBytes:v,splatDataStorageSizeBytes:T,storageSizeBytes:b,compressionScaleRange:S,compressionScaleFactor:g/S,base:p,bucketsBase:p+y,dataBase:p+v,fullBucketCount:C,partiallyFilledBucketCount:x,sphericalHarmonicsDegree:I};c[e]=D,p+=b,h+=ve.SectionHeaderSizeBytes,d=h/2,u=h/4,A+=t}return c}static writeSectionHeaderToBuffer(e,t,s,i=0){const n=new Uint16Array(s,i,ve.SectionHeaderSizeBytes/2),r=new Uint32Array(s,i,ve.SectionHeaderSizeBytes/4),a=new Float32Array(s,i,ve.SectionHeaderSizeBytes/4);r[0]=e.splatCount,r[1]=e.maxSplatCount,r[2]=t>=1?e.bucketSize:0,r[3]=t>=1?e.bucketCount:0,a[4]=t>=1?e.bucketBlockSize:0,n[10]=t>=1?ve.BucketStorageSizeBytes:0,r[6]=t>=1?e.compressionScaleRange:0,r[7]=e.storageSizeBytes,r[8]=t>=1?e.fullBucketCount:0,r[9]=t>=1?e.partiallyFilledBucketCount:0,n[20]=e.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(e,t,s=0){new Uint32Array(t,s,ve.SectionHeaderSizeBytes/4)[0]=e}constructFromBuffer(e,s){this.bufferData=e,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const i=ve.parseHeader(this.bufferData);this.versionMajor=i.versionMajor,this.versionMinor=i.versionMinor,this.maxSectionCount=i.maxSectionCount,this.sectionCount=s?i.maxSectionCount:0,this.maxSplatCount=i.maxSplatCount,this.splatCount=s?i.maxSplatCount:0,this.compressionLevel=i.compressionLevel,this.sceneCenter=(new t.Vector3).copy(i.sceneCenter),this.minSphericalHarmonicsCoeff=i.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=i.maxSphericalHarmonicsCoeff,this.sections=ve.parseSectionHeaders(i,this.bufferData,ve.HeaderSizeBytes,s),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,t){const s=ve.CompressionLevels[e].BytesPerCenter,i=ve.CompressionLevels[e].BytesPerScale,n=ve.CompressionLevels[e].BytesPerRotation,r=ve.CompressionLevels[e].BytesPerColor,a=B(t),o=ve.CompressionLevels[e].BytesPerSphericalHarmonicsComponent*a;return{bytesPerCenter:s,bytesPerScale:i,bytesPerRotation:n,bytesPerColor:r,sphericalHarmonicsComponentsPerSplat:a,sphericalHarmonicsBytesPerSplat:o,bytesPerSplat:s+i+n+r+o}}linkBufferArrays(){for(let e=0;e<this.maxSectionCount;e++){const t=this.sections[e];t.bucketArray=new Float32Array(this.bufferData,t.bucketsBase,t.bucketCount*ve.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 i=0;i<s.maxSplatCount;i++){const s=e+i;this.globalSplatIndexToLocalSplatIndexMap[s]=i,this.globalSplatIndexToSectionMap[s]=t}e+=s.maxSplatCount}}updateLoadedCounts(e,t){ve.writeHeaderCountsToBuffer(e,t,this.bufferData),this.sectionCount=e,this.splatCount=t}updateSectionLoadedCounts(e,t){const s=ve.HeaderSizeBytes+ve.SectionHeaderSizeBytes*e;ve.writeSectionHeaderSplatCountToBuffer(t,this.bufferData,s),this.sections[e].splatCount=t}static writeSplatDataToSectionBuffer=function(){const e=new ArrayBuffer(12),s=new ArrayBuffer(12),i=new ArrayBuffer(16),n=new ArrayBuffer(4),r=new ArrayBuffer(256),a=new t.Quaternion,o=new t.Vector3,l=new t.Vector3,{X:c,Y:h,Z:d,SCALE0:u,SCALE1:p,SCALE2:A,ROTATION0:m,ROTATION1:g,ROTATION2:f,ROTATION3:S,FDC0:C,FDC1:y,FDC2:v,OPACITY:I,FRC0:T,FRC9:b}=Ae.OFFSET,D=(e,t,s)=>{const i=2*s+1;return e=Math.round(e*t)+s,x(e,0,i)};return function(t,x,M,w,E,R,P,k,L=-F,U=F){const _=B(E),H=M,O=H+ve.CompressionLevels[w].BytesPerCenter,Q=O+ve.CompressionLevels[w].BytesPerScale,z=Q+ve.CompressionLevels[w].BytesPerRotation,V=z+ve.CompressionLevels[w].BytesPerColor;if(void 0!==t[m]?(a.set(t[m],t[g],t[f],t[S]),a.normalize()):a.set(1,0,0,0),void 0!==t[u]?o.set(t[u]||0,t[p]||0,t[A]||0):o.set(0,0,0),0===w){const e=new Float32Array(x,H,ve.CenterComponentCount),s=new Float32Array(x,Q,ve.RotationComponentCount),i=new Float32Array(x,O,ve.ScaleComponentCount);if(s.set([a.x,a.y,a.z,a.w]),i.set([o.x,o.y,o.z]),e.set([t[c],t[h],t[d]]),E>0){const e=new Float32Array(x,V,_);if(E>=1){for(let s=0;s<9;s++)e[s]=t[T+s]||0;if(E>=2)for(let s=0;s<15;s++)e[s+9]=t[b+s]||0}}}else{const n=new Uint16Array(e,0,ve.CenterComponentCount),u=new Uint16Array(i,0,ve.RotationComponentCount),p=new Uint16Array(s,0,ve.ScaleComponentCount);if(u.set([ge(a.x),ge(a.y),ge(a.z),ge(a.w)]),p.set([ge(o.x),ge(o.y),ge(o.z)]),l.set(t[c],t[h],t[d]).sub(R),l.x=D(l.x,P,k),l.y=D(l.y,P,k),l.z=D(l.z,P,k),n.set([l.x,l.y,l.z]),E>0){const e=1===w?2:1,s=new(1===w?Uint16Array:Uint8Array)(r,0,_);if(E>=1){for(let e=0;e<9;e++){const i=t[T+e]||0;s[e]=1===w?ge(i):Ce(i,L,U)}const i=9*e;if(me(s.buffer,0,x,V,i),E>=2){for(let e=0;e<15;e++){const i=t[b+e]||0;s[e+9]=1===w?ge(i):Ce(i,L,U)}me(s.buffer,i,x,V+i,15*e)}}}me(n.buffer,0,x,H,6),me(p.buffer,0,x,O,6),me(u.buffer,0,x,Q,8)}const N=new Uint8ClampedArray(n,0,4);N.set([t[C]||0,t[y]||0,t[v]||0]),N[3]=t[I]||0,me(N.buffer,0,x,z,4)}}();static generateFromUncompressedSplatArrays(e,s,i,n,r,a,o=[]){let l,c,h=0;for(let t=0;t<e.length;t++){const s=e[t];h=Math.max(s.sphericalHarmonicsDegree,h)}for(let t=0;t<e.length;t++){const s=e[t];for(let e=0;e<s.splats.length;e++){const t=s.splats[e];for(let e=Ae.OFFSET.FRC0;e<Ae.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-F,c=c||F;const{bytesPerSplat:d}=ve.calculateComponentStorage(i,h),u=ve.CompressionLevels[i].ScaleRange,p=[],A=[];let m=0;for(let n=0;n<e.length;n++){const g=e[n],f=new Ae(h);for(let e=0;e<g.splatCount;e++){const t=g.splats[e];(t[Ae.OFFSET.OPACITY]||0)>=s&&f.addSplat(t)}const S=o[n]||{},C=(S.blockSizeFactor||1)*(r||ve.BucketBlockSize),x=Math.ceil((S.bucketSizeFactor||1)*(a||ve.BucketSize)),y=ve.computeBucketsForUncompressedSplatArray(f,C,x),v=y.fullBuckets.length,I=y.partiallyFullBuckets.map(e=>e.splats.length),B=I.length,T=[...y.fullBuckets,...y.partiallyFullBuckets],b=f.splats.length*d,D=4*B,M=i>=1?T.length*ve.BucketStorageSizeBytes+D:0,w=b+M,E=new ArrayBuffer(w),R=u/(.5*C),F=new t.Vector3;let P=0;for(let e=0;e<T.length;e++){const t=T[e];F.fromArray(t.center);for(let e=0;e<t.splats.length;e++){let s=t.splats[e];const n=f.splats[s],r=M+P*d;ve.writeSplatDataToSectionBuffer(n,E,r,i,h,F,R,u,l,c),P++}}if(m+=P,i>=1){const e=new Uint32Array(E,0,4*I.length);for(let t=0;t<I.length;t++)e[t]=I[t];const t=new Float32Array(E,D,T.length*ve.BucketStorageSizeFloats);for(let e=0;e<T.length;e++){const s=T[e],i=3*e;t[i]=s.center[0],t[i+1]=s.center[1],t[i+2]=s.center[2]}}p.push(E);const k=new ArrayBuffer(ve.SectionHeaderSizeBytes);ve.writeSectionHeaderToBuffer({maxSplatCount:P,splatCount:P,bucketSize:x,bucketCount:T.length,bucketBlockSize:C,compressionScaleRange:u,storageSizeBytes:w,fullBucketCount:v,partiallyFilledBucketCount:B,sphericalHarmonicsDegree:h},i,k,0),A.push(k)}let g=0;for(let e of p)g+=e.byteLength;const f=ve.HeaderSizeBytes+ve.SectionHeaderSizeBytes*p.length+g,S=new ArrayBuffer(f);ve.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:p.length,sectionCount:p.length,maxSplatCount:m,splatCount:m,compressionLevel:i,sceneCenter:n,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},S);let C=ve.HeaderSizeBytes;for(let e of A)new Uint8Array(S,C,ve.SectionHeaderSizeBytes).set(new Uint8Array(e)),C+=ve.SectionHeaderSizeBytes;for(let e of p)new Uint8Array(S,C,e.byteLength).set(new Uint8Array(e)),C+=e.byteLength;return new ve(S)}static computeBucketsForUncompressedSplatArray(e,s,i){let n=e.splatCount;const r=s/2,a=new t.Vector3,o=new t.Vector3;for(let t=0;t<n;t++){const s=e.splats[t],i=[s[Ae.OFFSET.X],s[Ae.OFFSET.Y],s[Ae.OFFSET.Z]];(0===t||i[0]<a.x)&&(a.x=i[0]),(0===t||i[0]>o.x)&&(o.x=i[0]),(0===t||i[1]<a.y)&&(a.y=i[1]),(0===t||i[1]>o.y)&&(o.y=i[1]),(0===t||i[2]<a.z)&&(a.z=i[2]),(0===t||i[2]>o.z)&&(o.z=i[2])}const l=(new t.Vector3).copy(o).sub(a),c=Math.ceil(l.y/s),h=Math.ceil(l.z/s),d=new t.Vector3,u=[],p={};for(let t=0;t<n;t++){const n=e.splats[t],o=[n[Ae.OFFSET.X],n[Ae.OFFSET.Y],n[Ae.OFFSET.Z]],l=Math.floor((o[0]-a.x)/s),A=Math.floor((o[1]-a.y)/s),m=Math.floor((o[2]-a.z)/s);d.x=l*s+a.x+r,d.y=A*s+a.y+r,d.z=m*s+a.z+r;const g=l*(c*h)+A*h+m;let f=p[g];f||(p[g]=f={splats:[],center:d.toArray()}),f.splats.push(t),f.splats.length>=i&&(u.push(f),p[g]=null)}const A=[];for(let e in p)if(Object.hasOwn(p,e)){const t=p[e];t&&A.push(t)}return{fullBuckets:u,partiallyFullBuckets:A}}}class Ie{constructor(e,t,s,i){this.sectionCount=e,this.sectionFilters=t,this.groupingParameters=s,this.partitionGenerator=i}partitionUncompressedSplatArray(e){let t,s,i;if(this.partitionGenerator){const n=this.partitionGenerator(e);t=n.groupingParameters,s=n.sectionCount,i=n.sectionFilters}else t=this.groupingParameters,s=this.sectionCount,i=this.sectionFilters;const n=[];for(let t=0;t<s;t++){const s=new Ae(e.sphericalHarmonicsDegree),r=i[t];for(let t=0;t<e.splatCount;t++)r(t)&&s.addSplat(e.splats[t]);n.push(s)}return{splatArrays:n,parameters:t}}static getStandardPartitioner(e=0,s=new t.Vector3,i=ve.BucketBlockSize,n=ve.BucketSize){return new Ie(void 0,void 0,void 0,r=>{const a=Ae.OFFSET.X,o=Ae.OFFSET.Y,l=Ae.OFFSET.Z;e<=0&&(e=r.splatCount);const c=new t.Vector3,h=.5;r.splats.forEach(e=>{var t;c.set(e[a],e[o],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()}),r.splats.sort((e,t)=>e.centerDist>t.centerDist?1:-1);const d=[],u=[];e=Math.min(r.splatCount,e);const p=Math.ceil(r.splatCount/e);let A=0;for(let t=0;t<p;t++){let t=A;d.push(s=>s>=t&&s<t+e),u.push({blocksSize:i,bucketSize:n}),A+=e}return{sectionCount:d.length,sectionFilters:d,groupingParameters:u}})}}class Be{constructor(e,s,i,n,r,a,o){this.splatPartitioner=e,this.alphaRemovalThreshold=s,this.compressionLevel=i,this.sectionSize=n,this.sceneCenter=r?(new t.Vector3).copy(r):void 0,this.blockSize=a,this.bucketSize=o}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return ve.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(e=1,s=1,i=0,n=new t.Vector3,r=ve.BucketBlockSize,a=ve.BucketSize){const o=Ie.getStandardPartitioner(i,n,r,a);return new Be(o,e,s,i,n,r,a)}}const Te={INRIAV1:0},be=0,De=1,Me=2,we=3,Ee=4,Re=5,Fe=6,Pe={double:0,int:1,uint:2,float:3,short:4,ushort:5,uchar:6},ke={[be]:8,[De]:4,[Me]:4,[we]:4,[Ee]:2,[Re]:2,[Fe]:1};class Le{static HeaderEndToken="end_header";constructor(){}decodeSectionHeader(e,t,s=0){const i=[];let n=!1,r=-1,a=0,o=!1,l=null;const c=[],h=[],d=[],u={};for(let p=s;p<e.length;p++){const A=e[p].trim();if(A.startsWith("element")){if(n){r--;break}{n=!0,s=p,r=p;const e=A.split(" ");let t=0;for(let s of e){const e=s.trim();e.length>0&&(t++,2===t?l=e:3===t&&(a=parseInt(e)))}}}else if(A.startsWith("property")){const e=A.match(/(\w+)\s+(\w+)\s+(\w+)/);if(e){const s=e[2],i=e[3];d.push(i);const n=t[i];u[i]=s;const r=Pe[s];void 0!==n&&(c.push(n),h[n]=r)}}if(A===Le.HeaderEndToken){o=!0;break}n&&(i.push(A),r++)}const p=[];let A=0;for(let e of d){const s=u[e];if(Object.hasOwn(u,e)){const s=t[e];void 0!==s&&(p[s]=A)}A+=ke[Pe[s]]}const m=this.decodeSphericalHarmonicsFromSectionHeader(d,t);return{headerLines:i,headerStartLine:s,headerEndLine:r,fieldTypes:h,fieldIds:c,fieldOffsets:p,bytesPerVertex:A,vertexCount:a,dataSizeBytes:A*a,endOfHeader:o,sectionName:l,sphericalHarmonicsDegree:m.degree,sphericalHarmonicsCoefficientsPerChannel:m.coefficientsPerChannel,sphericalHarmonicsDegree1Fields:m.degree1Fields,sphericalHarmonicsDegree2Fields:m.degree2Fields}}decodeSphericalHarmonicsFromSectionHeader(e,t){let s=0,i=0;for(let t of e)t.startsWith("f_rest")&&s++;i=s/3;let n=0;i>=3&&(n=1),i>=8&&(n=2);let r=[],a=[];for(let e=0;e<3;e++){if(n>=1)for(let s=0;s<3;s++)r.push(t["f_rest_"+(s+i*e)]);if(n>=2)for(let s=0;s<5;s++)a.push(t["f_rest_"+(s+i*e+3)])}return{degree:n,coefficientsPerChannel:i,degree1Fields:r,degree2Fields:a}}static getHeaderSectionNames(e){const t=[];for(let s of e)if(s.startsWith("element")){const e=s.split(" ");let i=0;for(let s of e){const e=s.trim();e.length>0&&(i++,2===i&&t.push(e))}}return t}static checkTextForEndHeader(e){return!!e.includes(Le.HeaderEndToken)}static checkBufferForEndHeader(e,t,s,i){const n=new Uint8Array(e,Math.max(0,t-s),s),r=i.decode(n);return Le.checkTextForEndHeader(r)}static extractHeaderFromBufferToText(e){const t=new TextDecoder;let s=0,i="";const n=100;for(;;){if(s+n>=e.byteLength)throw new Error("End of file reached while searching for end of header");const r=new Uint8Array(e,s,n);if(i+=t.decode(r),s+=n,Le.checkBufferForEndHeader(e,s,200,t))break}return i}readHeaderFromBuffer(e){const t=new TextDecoder;let s=0,i="";const n=100;for(;;){if(s+n>=e.byteLength)throw new Error("End of file reached while searching for end of header");const r=new Uint8Array(e,s,n);if(i+=t.decode(r),s+=n,Le.checkBufferForEndHeader(e,s,200,t))break}return i}static convertHeaderTextToLines(e){const t=e.split("\n"),s=[];for(let e=0;e<t.length;e++){const i=t[e].trim();if(s.push(i),i===Le.HeaderEndToken)break}return s}static determineHeaderFormatFromHeaderText(e){return Te.INRIAV1}static determineHeaderFormatFromPlyBuffer(e){const t=Le.extractHeaderFromBufferToText(e);return Le.determineHeaderFormatFromHeaderText(t)}static readVertex(e,t,s,i,n,r,a=!0){const o=s*t.bytesPerVertex+i,l=t.fieldOffsets,c=t.fieldTypes;for(let t of n){const s=c[t];3===s?r[t]=e.getFloat32(o+l[t],!0):4===s?r[t]=e.getInt16(o+l[t],!0):5===s?r[t]=e.getUint16(o+l[t],!0):1===s?r[t]=e.getInt32(o+l[t],!0):2===s?r[t]=e.getUint32(o+l[t],!0):6===s&&(r[t]=a?e.getUint8(o+l[t])/255:e.getUint8(o+l[t]))}}}const 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"],_e=Ue.map((e,t)=>t),[He,Oe,Qe,ze,Ve,Ne,Ge,We,qe,Ke,je,Je,Xe,Ye,Ze,$e,et,tt]=_e;class st{constructor(){this.plyParserutils=new Le}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 i=Array.from(Array(Math.max(s-1,0))).map((e,t)=>`f_rest_${t+1}`);const n=[...Ue,...i],r=n.map((e,t)=>t),a=r.reduce((e,t)=>(e[n[t]]=t,e),{}),o=this.plyParserutils.decodeSectionHeader(e,a,0);return o.splatCount=o.vertexCount,o.bytesPerSplat=o.bytesPerVertex,o.fieldsToReadIndexes=r,o}decodeHeaderText(e){const t=Le.convertHeaderTextToLines(e),s=this.decodeHeaderLines(t);return s.headerText=e,s.headerSizeBytes=e.indexOf(Le.HeaderEndToken)+Le.HeaderEndToken.length+1,s}decodeHeaderFromBuffer(e){const t=this.plyParserutils.readHeaderFromBuffer(e);return this.decodeHeaderText(t)}findSplatData(e,t){return new DataView(e,t.headerSizeBytes)}parseToUncompressedSplatBufferSection(e,t,s,i,n,r,a,o=0){o=Math.min(o,e.sphericalHarmonicsDegree);const l=ve.CompressionLevels[0].SphericalHarmonicsDegrees[o].BytesPerSplat;for(let c=t;c<=s;c++){const t=st.parseToUncompressedSplat(i,c,e,n,o),s=c*l+a;ve.writeSplatDataToSectionBuffer(t,r,s,0,o)}}parseToUncompressedSplatArraySection(e,t,s,i,n,r,a=0){a=Math.min(a,e.sphericalHarmonicsDegree);for(let o=t;o<=s;o++){const t=st.parseToUncompressedSplat(i,o,e,n,a);r.addSplat(t)}}decodeSectionSplatData(e,t,s,i){i=Math.min(i,s.sphericalHarmonicsDegree);const n=new Ae(i);for(let r=0;r<t;r++){const t=st.parseToUncompressedSplat(e,r,s,0,i);n.addSplat(t)}return n}static parseToUncompressedSplat=function(){let e=[];const s=new t.Quaternion,i=Ae.OFFSET.X,n=Ae.OFFSET.Y,r=Ae.OFFSET.Z,a=Ae.OFFSET.SCALE0,o=Ae.OFFSET.SCALE1,l=Ae.OFFSET.SCALE2,c=Ae.OFFSET.ROTATION0,h=Ae.OFFSET.ROTATION1,d=Ae.OFFSET.ROTATION2,u=Ae.OFFSET.ROTATION3,p=Ae.OFFSET.FDC0,A=Ae.OFFSET.FDC1,m=Ae.OFFSET.FDC2,g=Ae.OFFSET.OPACITY,f=[];for(let e=0;e<45;e++)f[e]=Ae.OFFSET.FRC0+e;return function(t,S,C,y=0,v=0){v=Math.min(v,C.sphericalHarmonicsDegree),st.readSplat(t,C,S,y,e);const I=Ae.createSplat(v);if(void 0!==e[He]?(I[a]=Math.exp(e[He]),I[o]=Math.exp(e[Oe]),I[l]=Math.exp(e[Qe])):(I[a]=.01,I[o]=.01,I[l]=.01),void 0!==e[je]?(I[p]=255*e[je],I[A]=255*e[Je],I[m]=255*e[Xe]):void 0!==e[Ze]?(I[p]=255*e[Ze],I[A]=255*e[$e],I[m]=255*e[et]):(I[p]=0,I[A]=0,I[m]=0),void 0!==e[Ye]&&(I[g]=1/(1+Math.exp(-e[Ye]))*255),I[p]=x(Math.floor(I[p]),0,255),I[A]=x(Math.floor(I[A]),0,255),I[m]=x(Math.floor(I[m]),0,255),I[g]=x(Math.floor(I[g]),0,255),v>=1&&void 0!==e[tt]){for(let t=0;t<9;t++)I[f[t]]=e[C.sphericalHarmonicsDegree1Fields[t]];if(v>=2)for(let t=0;t<15;t++)I[f[9+t]]=e[C.sphericalHarmonicsDegree2Fields[t]]}return s.set(e[ze],e[Ve],e[Ne],e[Ge]),s.normalize(),I[c]=s.x,I[h]=s.y,I[d]=s.z,I[u]=s.w,I[i]=e[We],I[n]=e[qe],I[r]=e[Ke],I}}();static readSplat(e,t,s,i,n){return Le.readVertex(e,t,s,i,t.fieldsToReadIndexes,n,!0)}parseToUncompressedSplatArray(e,t=0){const s=this.decodeHeaderFromBuffer(e),i=s.splatCount,n=this.findSplatData(e,s);return this.decodeSectionSplatData(n,i,s,t)}}class it{static parseToUncompressedSplatArray(e,t=0){return(new st).parseToUncompressedSplatArray(e,t)}}function nt(e,s,i,n,r,a,o,l){if(s){return Be.getStandardGenerator(i,n,r,a,o,l).generateFromUncompressedSplatArray(e)}return ve.generateFromUncompressedSplatArrays([e],i,0,new t.Vector3)}class rt{static loadFromURL(e,s,i,n,r,a,o=!0,l=0,c,h,d,u,A){let m=i?g.DirectToSplatBuffer:g.DirectToSplatArray;o&&(m=g.DirectToSplatArray);const S=p.ProgressiveLoadSectionSize,x=ve.HeaderSizeBytes+ve.SectionHeaderSizeBytes;let y,v,B,b=0,D=0,M=!1,w=!1;const E=T();let R,F=0,P=0,k=0,L="",U=null,_=[];const H=new TextDecoder,O=new st;return s&&s(0,"0%",f.Downloading),C(e,(e,i,r)=>{const a=e>=100;if(r&&(_.push({data:r,sizeBytes:r.byteLength,startBytes:k,endBytes:k+r.byteLength}),k+=r.byteLength),m===g.DownloadBeforeProcessing)a&&E.resolve(_);else{if(!M&&(L+=H.decode(r),Le.checkTextForEndHeader(L))){U=O.decodeHeaderText(L),b=U.splatCount,w=!0,l=Math.min(l,U.sphericalHarmonicsDegree);const e=ve.CompressionLevels[0].SphericalHarmonicsDegrees[l],s=x+e.BytesPerSplat*b;m===g.DirectToSplatBuffer?(v=new ArrayBuffer(s),ve.writeHeaderToBuffer({versionMajor:ve.CurrentMajorVersion,versionMinor:ve.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:b,splatCount:D,compressionLevel:0,sceneCenter:new t.Vector3},v)):R=new Ae(l),F=U.headerSizeBytes,P=U.headerSizeBytes,M=!0}if(M&&w){if(_.length>0){y=function(e,t){let s=0;for(let t of e)s+=t.sizeBytes;(!t||t.byteLength<s)&&(t=new ArrayBuffer(s));let i=0;for(let s of e)new Uint8Array(t,i,s.sizeBytes).set(s.data),i+=s.sizeBytes;return t}(_,y);if(k-F>S||a){const e=k-P,t=Math.floor(e/U.bytesPerSplat),s=t*U.bytesPerSplat,i=e-s,r=D+t,o=P-_[0].startBytes,c=new DataView(y,o,s),h=ve.CompressionLevels[0].SphericalHarmonicsDegrees[l],d=D*h.BytesPerSplat+x;if(m===g.DirectToSplatBuffer?O.parseToUncompressedSplatBufferSection(U,0,t-1,c,0,v,d,l):O.parseToUncompressedSplatArraySection(U,0,t-1,c,0,R,l),D=r,m===g.DirectToSplatBuffer&&(B||(ve.writeSectionHeaderToBuffer({maxSplatCount:b,splatCount:D,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:l},0,v,ve.HeaderSizeBytes),B=new ve(v,!1)),B.updateLoadedCounts(1,D),n&&n(B,a)),F+=S,P+=s,0===i)_=[];else{let e=[],t=0;for(let s=_.length-1;s>=0;s--){const n=_[s];if(t+=n.sizeBytes,e.unshift(n),t>=i)break}_=e}}}a&&(m===g.DirectToSplatBuffer?E.resolve(B):E.resolve(R))}}s&&s(e,i,f.Downloading)},!1,c).then(()=>(s&&s(0,"0%",f.Processing),E.promise.then(e=>{if(s&&s(100,"100%",f.Done),m===g.DownloadBeforeProcessing){const e=_.map(e=>e.data);return new Blob(e).arrayBuffer().then(e=>rt.loadFromFileData(e,r,a,o,l,h,d,u,A))}return m===g.DirectToSplatBuffer?e:I(()=>nt(e,o,r,a,h,d,u,A))})))}static loadFromFileData(e,t,s,i,n=0,r,a,o,l){return I(()=>it.parseToUncompressedSplatArray(e,n)).then(e=>nt(e,i,t,s,r,a,o,l))}}const at=new a.Vector3(1,0,0),ot=new a.Vector3(0,1,0),lt=new a.Vector3(0,0,1);class ct{constructor(e=new a.Vector3,t=new a.Vector3){this.origin=new a.Vector3,this.direction=new a.Vector3,this.setParameters(e,t)}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 e=new a.Vector3,t=[],s=[],i=[];return function(n,r){if(s[0]=this.origin.x,s[1]=this.origin.y,s[2]=this.origin.z,i[0]=this.direction.x,i[1]=this.direction.y,i[2]=this.direction.z,this.boxContainsPoint(n,this.origin,1e-4))return r&&(r.origin.copy(this.origin),r.normal.set(0,0,0),r.distance=-1),!0;for(let a=0;a<3;a++){if(0==i[a])continue;const o=0==a?at:1==a?ot:lt,l=i[a]<0?n.max:n.min;let c=-Math.sign(i[a]);t[0]=0==a?l.x:1==a?l.y:l.z;let h=t[0]-s[a];if(h*c<0){const l=(a+1)%3,d=(a+2)%3;if(t[2]=i[l]/i[a]*h+s[l],t[1]=i[d]/i[a]*h+s[d],e.set(t[a],t[d],t[l]),this.boxContainsPoint(n,e,1e-4))return r&&(r.origin.copy(e),r.normal.copy(o).multiplyScalar(c),r.distance=e.sub(this.origin).length()),!0}}return!1}}();intersectSphere=function(){const e=new a.Vector3;return function(t,s,i){e.copy(t).sub(this.origin);const n=e.dot(this.direction),r=n*n,a=e.dot(e)-r,o=s*s;if(a>o)return!1;const l=Math.sqrt(o-a),c=n-l,h=n+l;if(h<0)return!1;let d=c<0?h:c;return i&&(i.origin.copy(this.origin).addScaledVector(this.direction,d),i.normal.copy(i.origin).sub(t).normalize(),i.distance=d),!0}}()}class ht{constructor(){this.origin=new a.Vector3,this.normal=new a.Vector3,this.distance=0,this.splatIndex=0}set(e,t,s,i){this.origin.copy(e),this.normal.copy(t),this.distance=s,this.splatIndex=i}clone(){const e=new ht;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}class dt{constructor(e,t,s=!1){this.ray=new ct(e,t),this.raycastAgainstTrueSplatEllipsoid=s}setFromCameraAndScreenPosition=function(){const e=new a.Vector2;return function(t,s,i){if(e.x=s.x/i.x*2-1,e.y=(i.y-s.y)/i.y*2-1,t.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t;else{if(!t.isOrthographicCamera)throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type");this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t}}}();intersectSplatMesh=function(){const e=new a.Matrix4,t=new a.Matrix4,s=new a.Matrix4,i=new ct,n=new a.Vector3;return function(r,a=[]){const o=r.getSplatTree();if(o){for(let l=0;l<o.subTrees.length;l++){const c=o.subTrees[l];t.copy(r.matrixWorld),r.dynamicMode&&(r.getSceneTransform(l,s),t.multiply(s)),e.copy(t).invert(),i.origin.copy(this.ray.origin).applyMatrix4(e),i.direction.copy(this.ray.origin).add(this.ray.direction),i.direction.applyMatrix4(e).sub(i.origin).normalize();const h=[];c.rootNode&&this.castRayAtSplatTreeNode(i,o,c.rootNode,h),h.forEach(e=>{e.origin.applyMatrix4(t),e.normal.applyMatrix4(t).normalize(),e.distance=n.copy(e.origin).sub(this.ray.origin).length()}),a.push(...h)}return a.sort((e,t)=>e.distance>t.distance?1:-1),a}}}();castRayAtSplatTreeNode=function(){const e=new a.Vector4,t=new a.Vector3,s=new a.Vector3,i=new a.Quaternion,n=new ht,r=1e-7,o=new a.Vector3(0,0,0),l=new a.Matrix4,c=new a.Matrix4,h=new a.Matrix4,d=new a.Matrix4,p=new a.Matrix4,A=new ct;return function(a,m,g,f=[]){if(a.intersectBox(g.boundingBox)){if(g.data&&g.data.indexes&&g.data.indexes.length>0)for(let S=0;S<g.data.indexes.length;S++){const C=g.data.indexes[S],x=m.splatMesh.getSceneIndexForSplat(C);if(m.splatMesh.getScene(x).visible&&(m.splatMesh.getSplatColor(C,e),m.splatMesh.getSplatCenter(C,t),m.splatMesh.getSplatScaleAndRotation(C,s,i),!(s.x<=r||s.y<=r||m.splatMesh.splatRenderMode===u.ThreeD&&s.z<=r)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(s.x,s.y,s.z),h.makeRotationFromQuaternion(i);const r=2*Math.log10(e.w);if(l.makeScale(r,r,r),p.copy(l).multiply(h).multiply(c),d.copy(p).invert(),A.origin.copy(a.origin).sub(t).applyMatrix4(d),A.direction.copy(a.origin).add(a.direction).sub(t),A.direction.applyMatrix4(d).sub(A.origin).normalize(),A.intersectSphere(o,1,n)){const e=n.clone();e.splatIndex=C,e.origin.applyMatrix4(p).add(t),f.push(e)}}else{let e=s.x+s.y,i=2;if(m.splatMesh.splatRenderMode===u.ThreeD&&(e+=s.z,i=3),e/=i,a.intersectSphere(t,e,n)){const e=n.clone();e.splatIndex=C,f.push(e)}}}if(g.children&&g.children.length>0)for(let e of g.children)this.castRayAtSplatTreeNode(a,m,e,f);return f}}}()}const ut="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACEgEDZW52Bm1lbW9yeQIDAICABAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQqiDwICAAucDwMBfAd9Bn8gCyAKayEMAkACQCAOBEAgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQMgDCEFA0AgAyAFQQJ0IgFqIAIgACABaigCAEECdGooAgAiATYCACABIAogASAKSBshCiABIA0gASANShshDSAFQQFqIgUgC0cNAAsMAwsgDwRAIAsgDE0NAkF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiGmooAgBBAnQiG2ooAgAiDkcEQAJ/IAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRgCfyARIA8qAiyUIBIgDyoCKJQgEyAPKgIglCAUIA8qAiSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRkCfyARIA8qAhyUIBIgDyoCGJQgEyAPKgIQlCAUIA8qAhSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIRwCfyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSu0QAAAAAAECPQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIR0gDiEPCyADIBpqIAEgG0ECdGoiDigCBCAcbCAOKAIAIB1saiAOKAIIIBlsaiAOKAIMIBhsaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAii7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshAgJ/IAUqAhi7RAAAAAAAQI9AoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshByALIAxNAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEPQfj///8HIQpBiICAgHghDQ0CIAwhBQNAIAMgBUECdCIIaiABIAAgCGooAgBBBHRqIggoAgQgB2wgCCgCACAPbGogCCgCCCACbGoiCDYCACAIIAogCCAKSBshCiAIIA0gCCANShshDSAFQQFqIgUgC0cNAAsMAgsgDQRAQfj///8HIQpBiICAgHghDSALIAxNDQIgDCEFA0AgAyAFQQJ0IgFqAn8gAiAAIAFqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAVBAWoiBSALRw0ACwwCCyAPRQRAIAsgDE0NASAFKgIoIREgBSoCGCESIAUqAgghE0H4////ByEKQYiAgIB4IQ0gDCEFA0ACfyARIAEgACAFQQJ0IgdqKAIAQQR0aiICKgIIlCATIAIqAgCUIBIgAioCBJSSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOIAMgB2ogDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgCyAMTQ0AQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIYaigCAEECdCIZaigCACIORwRAIAUqAjgiESAIIA5BBnRqIg8qAjyUIAUqAigiEiAPKgI4lCAFKgIIIhMgDyoCMJQgBSoCGCIUIA8qAjSUkpKSIRUgESAPKgIslCASIA8qAiiUIBMgDyoCIJQgFCAPKgIklJKSkiEWIBEgDyoCHJQgEiAPKgIYlCATIA8qAhCUIBQgDyoCFJSSkpIhFyARIA8qAgyUIBIgDyoCCJQgEyAPKgIAlCAUIA8qAgSUkpKSIREgDiEPCyADIBhqAn8gFSABIBlBAnRqIg4qAgyUIBYgDioCCJQgESAOKgIAlCAXIA4qAgSUkpKSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIg42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gAkEBaiICIAtHDQALDAELQYiAgIB4IQ1B+P///wchCgsgCyAMSwRAIAlBAWuzIA2yIAqyk5UhESAMIQ0DQAJ/IBEgAyANQQJ0aiIBKAIAIAprspQiEotDAAAAT10EQCASqAwBC0GAgICAeAshDiABIA42AgAgBCAOQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhCgNAIAQgCkECdGoiASABKAIAIA1qIg02AgAgCkEBaiIKIAlHDQALCyAMQQBKBEAgDCEKA0AgBiAKQQFrIgFBAnQiAmogACACaigCADYCACAKQQFLIAEhCg0ACwsgCyAMSgRAIAshCgNAIAYgCyAEIAMgCkEBayIKQQJ0IgFqKAIAQQJ0aiICKAIAIgVrQQJ0aiAAIAFqKAIANgIAIAIgBUEBazYCACAKIAxKDQALCws=";function pt(e){let t,s,i,n,r,a,o,l,c,h,d,u,p,A,m,g,f,S,C,x;e.onmessage=y=>{if(y.data.centers){let e=y.data.centers,t=y.data.sceneIndexes;n?new Int32Array(s,A+y.data.range.from*x.BytesPerInt*4,4*y.data.range.count).set(new Int32Array(e)):new Float32Array(s,A+y.data.range.from*x.BytesPerFloat*4,4*y.data.range.count).set(new Float32Array(e)),r&&new Uint32Array(s,c+4*y.data.range.from,y.data.range.count).set(new Uint32Array(t)),C=y.data.range.from+y.data.range.count}else if(y.data.sort){const v=Math.min(y.data.sort.splatRenderCount||0,C),I=Math.min(y.data.sort.splatSortCount||0,C),B=y.data.sort.usePrecomputedDistances;let T,b,D;i||(T=y.data.sort.indexesToSort,D=y.data.sort.transforms,B&&(b=y.data.sort.precomputedDistances)),function(C,y,v,I,B,T,b){const D=performance.now();if(!i&&(new Uint32Array(s,o,B.byteLength/x.BytesPerInt).set(B),new Float32Array(s,h,b.byteLength/x.BytesPerFloat).set(b),I)){let e;e=n?new Int32Array(s,d,T.byteLength/x.BytesPerInt):new Float32Array(s,d,T.byteLength/x.BytesPerFloat),e.set(T)}g||(g=new Uint32Array(S)),new Float32Array(s,m,16).set(v),new Uint32Array(s,p,S).set(g),t.exports.sortIndexes(o,A,d,u,p,m,l,c,h,S,C,y,a,I,n,r);const M={sortDone:!0,splatSortCount:C,splatRenderCount:y,sortTime:0};if(!i){const e=new Uint32Array(s,l,y);(!f||f.length<y)&&(f=new Uint32Array(y)),f.set(e),M.sortedIndexes=f}const w=performance.now();M.sortTime=w-D,e.postMessage(M)}(I,v,y.data.sort.modelViewProj,B,T,b,D)}else if(y.data.init){x=y.data.init.Constants,a=y.data.init.splatCount,i=y.data.init.useSharedMemory,n=y.data.init.integerBasedSort,r=y.data.init.dynamicMode,S=y.data.init.distanceMapRange,C=0;const g=n?4*x.BytesPerInt:4*x.BytesPerFloat,f=new Uint8Array(y.data.init.sorterWasmBytes),v=16*x.BytesPerFloat,I=a*x.BytesPerInt,B=a*g,T=v,b=n?a*x.BytesPerInt:a*x.BytesPerFloat,D=a*x.BytesPerInt,M=a*x.BytesPerInt,w=n?S*x.BytesPerInt*2:S*x.BytesPerFloat*2,E=r?a*x.BytesPerInt:0,R=r?x.MaxScenes*v:0,F=32*x.MemoryPageSize,P=I+B+T+b+D+w+M+E+R+F,k=Math.floor(P/x.MemoryPageSize)+1,L={module:{},env:{memory:new WebAssembly.Memory({initial:k,maximum:k,shared:!0})}};WebAssembly.compile(f).then(e=>WebAssembly.instantiate(e,L)).then(n=>{t=n,o=0,A=o+I,m=A+B,d=m+T,u=d+b,p=u+D,l=p+w,c=l+M,h=c+E,s=L.env.memory.buffer,i?e.postMessage({sortSetupPhase1Complete:!0,indexesToSortBuffer:s,indexesToSortOffset:o,sortedIndexesBuffer:s,sortedIndexesOffset:l,precomputedDistancesBuffer:s,precomputedDistancesOffset:d,transformsBuffer:s,transformsOffset:h}):e.postMessage({sortSetupPhase1Complete:!0})})}}}class At{constructor(e,t){this.tasks=[]}show(){}hide(){}setContainer(e){}addTask(e){return this.tasks.push(e)}removeTask(e){}removeAllTasks(){this.tasks=[]}setMessageForTask(e,t){}}class mt{constructor(e){}show(){}hide(){}setContainer(e){}setProgress(e){}}class gt{constructor(e){this.scene=e,this.meshCursor=null,this.meshCursorVisible=!1,this.focusMarker=null,this.focusMarkerOpacity=0,this.controlPlane=null,this.controlPlaneVisible=!1}setupMeshCursor(){}setupFocusMarker(){}setupControlPlane(){}updateMeshCursor(e,t){}updateFocusMarker(e,t,s){}updateControlPlane(e,t){}setFocusMarkerVisibility(e){}setFocusMarkerOpacity(e){this.focusMarkerOpacity=e}getFocusMarkerOpacity(){return this.focusMarkerOpacity}positionAndOrientFocusMarker(e,t){}positionAndOrientMeshCursor(e,t){}setMeshCursorVisibility(e){this.meshCursorVisible=e}getMeschCursorVisibility(){return this.meshCursorVisible}setControlPlaneVisibility(e){this.controlPlaneVisible=e}positionAndOrientControlPlane(e,t,s){}updateForRenderMode(e,t){}dispose(){}}class ft{constructor(e={}){if(e.cameraUp||(e.cameraUp=[0,1,0]),this.cameraUp=(new t.Vector3).fromArray(e.cameraUp),e.initialCameraPosition||(e.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new t.Vector3).fromArray(e.initialCameraPosition),e.initialCameraRotation||(e.initialCameraRotation=[0,0,0]),this.initialCameraRotation=(new t.Vector3).fromArray(e.initialCameraRotation),this.backgroundColor=e.backgroundColor,e.initialCameraLookAt||(e.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new t.Vector3).fromArray(e.initialCameraLookAt),this.dropInMode=e.dropInMode||!1,void 0!==e.selfDrivenMode&&null!==e.selfDrivenMode||(e.selfDrivenMode=!0),this.selfDrivenMode=e.selfDrivenMode&&!this.dropInMode,this.selfDrivenUpdateFunc=this.selfDrivenUpdate.bind(this),void 0===e.useBuiltInControls&&(e.useBuiltInControls=!0),this.useBuiltInControls=e.useBuiltInControls,this.rootElement=e.rootElement,this.canvas=e.threejsCanvas,this.ignoreDevicePixelRatio=e.ignoreDevicePixelRatio||!1,this.devicePixelRatio=this.ignoreDevicePixelRatio?1:window.devicePixelRatio||1,this.halfPrecisionCovariancesOnGPU=e.halfPrecisionCovariancesOnGPU||!1,this.threeScene=e.threeScene,this.renderer=e.renderer,this.camera=e.camera,this.gpuAcceleratedSort=e.gpuAcceleratedSort||!1,void 0!==e.integerBasedSort&&null!==e.integerBasedSort||(e.integerBasedSort=!0),this.integerBasedSort=e.integerBasedSort,void 0!==e.sharedMemoryForWorkers&&null!==e.sharedMemoryForWorkers||(e.sharedMemoryForWorkers=!0),this.sharedMemoryForWorkers=!1,this.dynamicScene=!!e.dynamicScene,this.antialiased=e.antialiased||!1,this.kernel2DSize=void 0===e.kernel2DSize?.3:e.kernel2DSize,this.renderMode=e.renderMode||l.Always,this.sceneRevealMode=e.sceneRevealMode||d.Default,this.focalAdjustment=e.focalAdjustment||1,this.maxScreenSpaceSplatSize=e.maxScreenSpaceSplatSize||1024,this.logLevel=e.logLevel||o.None,this.sphericalHarmonicsDegree=e.sphericalHarmonicsDegree||0,this.enableOptionalEffects=e.enableOptionalEffects||!1,void 0!==e.enableSIMDInSort&&null!==e.enableSIMDInSort||(e.enableSIMDInSort=!0),this.enableSIMDInSort=e.enableSIMDInSort,void 0!==e.inMemoryCompressionLevel&&null!==e.inMemoryCompressionLevel||(e.inMemoryCompressionLevel=0),this.inMemoryCompressionLevel=e.inMemoryCompressionLevel,void 0!==e.optimizeSplatData&&null!==e.optimizeSplatData||(e.optimizeSplatData=!0),this.optimizeSplatData=e.optimizeSplatData,void 0!==e.freeIntermediateSplatData&&null!==e.freeIntermediateSplatData||(e.freeIntermediateSplatData=!1),this.freeIntermediateSplatData=e.freeIntermediateSplatData,M()){const e=w();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==e.splatRenderMode&&null!==e.splatRenderMode||(e.splatRenderMode=u.ThreeD),this.splatRenderMode=e.splatRenderMode,this.sceneFadeInRateMultiplier=e.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=e.splatSortDistanceMapPrecision||p.DefaultSplatSortDistanceMapPrecision;const s=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=x(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 dt,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new t.Vector3,this.nextCameraTarget=new t.Vector3,this.mousePosition=new t.Vector2,this.mouseDownPosition=new t.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.splatSceneDownloadControllers=[],this.splatSceneDownloadPromises={},this.splatSceneDownloadAndBuildPromise=null,this.splatSceneRemovalPromise=null,this.loadingSpinner=new At(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new mt(this.rootElement||document.body),this.loadingProgressBar.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.lastTime=0,this.gaussianSplatCount=0,this.totalFrames=0,this.flame_params=null,this.bone_tree=null,this.lbs_weight_80k=null,this.frame=0,this.useFlame=!0,this.bones=null,this.skeleton=null,this.avatarMesh=null,this.skinModel=null,this.boneRoot=null,this.baseMesh=null,this.setSkinAttibutes=!1,this.dropInMode||this.init()}createSplatMesh(){this.splatMesh=new ue(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.setupEventHandlers(),this.threeScene=this.threeScene||new t.Scene,this.sceneHelper=new gt(this.threeScene),this.sceneHelper.setupMeshCursor(),this.sceneHelper.setupFocusMarker(),this.sceneHelper.setupControlPlane(),this.loadingProgressBar.setContainer(this.rootElement),this.loadingSpinner.setContainer(this.rootElement),this.initialized=!0)}setupCamera(){if(!this.usingExternalCamera){const e=new t.Vector2;this.getRenderDimensions(e),this.perspectiveCamera=new t.PerspectiveCamera(50,e.x/e.y,.1,1e3),this.orthographicCamera=new t.OrthographicCamera(e.x/-2,e.x/2,e.y/2,e.y/-2,.1,1e3),this.camera=this.startInOrthographicMode?this.orthographicCamera:this.perspectiveCamera,this.camera.position.copy(this.initialCameraPosition),this.camera.rotateX(t.MathUtils.degToRad(this.initialCameraRotation.x)),this.camera.rotateY(t.MathUtils.degToRad(this.initialCameraRotation.y)),this.camera.rotateZ(t.MathUtils.degToRad(this.initialCameraRotation.z))}}setupRenderer(){if(!this.usingExternalRenderer){const e=new t.Vector2;this.getRenderDimensions(e),this.renderer=new t.WebGLRenderer({antialias:!1,precision:"highp",canvas:this.canvas}),this.renderer.setPixelRatio(this.devicePixelRatio),this.renderer.autoClear=!0,this.renderer.setClearColor(this.backgroundColor,1),this.renderer.setSize(e.x,e.y),this.resizeObserver=new ResizeObserver(()=>{this.getRenderDimensions(e),this.renderer.setSize(e.x,e.y),this.forceRenderNextFrame()}),this.resizeObserver.observe(this.rootElement),this.rootElement.appendChild(this.renderer.domElement)}}setupControls(){if(this.useBuiltInControls){this.usingExternalCamera?this.camera.isOrthographicCamera?this.orthographicControls=new n.OrbitControls(this.camera,this.renderer.domElement):this.perspectiveControls=new n.OrbitControls(this.camera,this.renderer.domElement):(this.perspectiveControls=new n.OrbitControls(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new n.OrbitControls(this.orthographicCamera,this.renderer.domElement));for(let e of[this.orthographicControls,this.perspectiveControls])e&&(e.listenToKeyEvents(window),e.rotateSpeed=.5,e.maxPolarAngle=.5*Math.PI,e.minPolarAngle=.5*Math.PI,e.minAzimuthAngle=-Math.PI/72,e.maxAzimuthAngle=Math.PI/72,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.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))}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}tempForward=new t.Vector3;tempMatrixLeft=new t.Matrix4;tempMatrixRight=new t.Matrix4;onKeyDown=e=>{switch(this.tempForward.set(0,0,-1),this.tempForward.transformDirection(this.camera.matrixWorld),this.tempMatrixLeft.makeRotationAxis(this.tempForward,Math.PI/128),this.tempMatrixRight.makeRotationAxis(this.tempForward,-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(this.tempMatrixLeft);break;case"ArrowRight":this.camera.up.transformDirection(this.tempMatrixRight);break;case"KeyC":this.showMeshCursor=!this.showMeshCursor;break;case"KeyU":this.showControlPlane=!this.showControlPlane;break;case"KeyI":this.showInfo=!this.showInfo,this.showInfo;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=y()}onMouseUp=function(){const e=new t.Vector2;return function(t){e.copy(this.mousePosition).sub(this.mouseDownPosition);y()-this.mouseDownTime<.5&&e.length()<2&&this.onMouseClick(t)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkPointRenderDimensions=new t.Vector2;checkPointToNewFocalPoint=new t.Vector3;checkPointOutHits=[];checkForFocalPointChange=()=>{if(!this.transitioningCameraTarget&&(this.getRenderDimensions(this.checkPointRenderDimensions),this.checkPointOutHits.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,this.checkPointRenderDimensions),this.raycaster.intersectSplatMesh(this.splatMesh,this.checkPointOutHits),this.checkPointOutHits.length>0)){const e=this.checkPointOutHits[0].origin;this.checkPointToNewFocalPoint.copy(e).sub(this.camera.position),this.checkPointToNewFocalPoint.length()>.5&&(this.previousCameraTarget.copy(this.controls.target),this.nextCameraTarget.copy(e),this.transitioningCameraTarget=!0,this.transitioningCameraTargetStartTime=y())}};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 i=e=>{e.saveState(),e.reset()},n=this.controls,r=e?this.orthographicControls:this.perspectiveControls;i(r),i(n),r.target.copy(n.target),e?ft.setCameraZoomFromPosition(s,t,n):ft.setCameraPositionFromZoom(s,t,r),this.controls=r,this.camera.lookAt(this.controls.target)}}static setCameraPositionFromZoom=function(){const e=new t.Vector3;return function(t,s,i){const n=1/(.001*s.zoom);e.copy(i.target).sub(t.position).normalize().multiplyScalar(n).negate(),t.position.copy(i.target).add(e)}}();static setCameraZoomFromPosition=function(){const e=new t.Vector3;return function(t,s,i){const n=e.copy(i.target).sub(s.position).length();t.zoom=1/(.001*n)}}();updateSplatMesh=function(){const e=new t.Vector2;return function(){if(!this.splatMesh)return;if(this.splatMesh.getSplatCount()>0){this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode),this.splatMesh.updateTransforms(),this.getRenderDimensions(e);const t=.5*this.camera.projectionMatrix.elements[0]*this.devicePixelRatio*e.x,s=.5*this.camera.projectionMatrix.elements[5]*this.devicePixelRatio*e.y,i=this.camera.isOrthographicCamera?1/this.devicePixelRatio:1,n=this.focalAdjustment*i,r=1/n;this.adjustForWebXRStereo(e),this.splatMesh.updateUniforms(e,t*n,s*n,this.camera.isOrthographicCamera,this.camera.zoom||1,r)}}}();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}addSplatSceneDownloadController(e){this.splatSceneDownloadControllers.push(e)}removeSplatSceneDownloadController(e){const t=this.splatSceneDownloadControllers.indexOf(e);t>-1&&this.splatSceneDownloadControllers.splice(t,1)}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:h(e),i=ft.isProgressivelyLoadable(s)&&t.progressiveLoad,n=void 0===t.showLoadingUI||null===t.showLoadingUI||t.showLoadingUI;let r=null;n&&(this.loadingSpinner.removeAllTasks(),r=this.loadingSpinner.addTask("Downloading..."));const a=(e,t,s)=>{if(n)if(s===f.Downloading)if(100==e)this.loadingSpinner.setMessageForTask(r,"Download complete!");else if(i)this.loadingSpinner.setMessageForTask(r,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(r,`Downloading${e}`)}else s===f.Processing&&(console.log("loaderStatus === LoaderStatus.Processing"),this.loadingSpinner.setMessageForTask(r,"Processing splats..."))};let o=!1,l=0;const c=(e,t)=>{n&&((e&&i||t&&!i)&&(this.loadingSpinner.removeTask(r),t||o||this.loadingProgressBar.show()),i&&(t?(o=!0,this.loadingProgressBar.hide()):this.loadingProgressBar.setProgress(l)))};return(i?this.downloadAndBuildSingleSplatSceneProgressiveLoad.bind(this):this.downloadAndBuildSingleSplatSceneStandardLoad.bind(this))(e,s,t.splatAlphaRemovalThreshold,((e,s,r)=>{!i&&t.onProgress&&t.onProgress(0,"0%",f.Processing);const a={rotation:t.rotation||t.orientation,position:t.position,scale:t.scale,splatAlphaRemovalThreshold:t.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[a],r,s&&n,n,i,i).then(()=>{!i&&t.onProgress&&t.onProgress(100,"100%",f.Processing),c(s,r)})}).bind(this),(e,s,i)=>{l=e,a(e,s,i),t.onProgress&&t.onProgress(e,s,i)},(()=>{this.loadingProgressBar.hide(),this.loadingSpinner.removeAllTasks()}).bind(this),t.headers)}downloadAndBuildSingleSplatSceneStandardLoad(e,t,s,i,n,r,a){const o=this.downloadSplatSceneToSplatBuffer(e,s,n,!1,void 0,t,a),l=b(o.abort?o.abort.bind(o):void 0);return o.then(e=>(this.removeSplatSceneDownloadPromise(o),i(e,!0,!0).then(()=>{l.resolve(),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(t=>{r&&r(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(o);const s=t instanceof S||"AbortError"===t.name?t:new Error(`Viewer::addSplatScene -> Could not load file ${e}`);l.reject(s)}),this.addSplatSceneDownloadPromise(o),this.setSplatSceneDownloadAndBuildPromise(l.promise),l.promise}downloadAndBuildSingleSplatSceneProgressiveLoad(e,t,s,i,n,r,a){let o=0,l=!1;const c=[],h=()=>{if(c.length>0&&!l&&!this.isDisposingOrDisposed()){l=!0;const e=c.shift();i(e.splatBuffer,e.firstBuild,e.finalBuild).then(()=>{l=!1,e.firstBuild?p.resolve():e.finalBuild&&(A.resolve(),this.clearSplatSceneDownloadAndBuildPromise()),c.length>0&&I(()=>h())})}},d=this.downloadSplatSceneToSplatBuffer(e,s,n,!0,(e,t)=>{this.isDisposingOrDisposed()||(t||0===c.length||e.getSplatCount()>c[0].splatBuffer.getSplatCount())&&(c.push({splatBuffer:e,firstBuild:0===o,finalBuild:t}),o++,h())},t,a),u=d.abort?d.abort.bind(d):void 0,p=b(u),A=b(u);return this.addSplatSceneDownloadPromise(d),this.setSplatSceneDownloadAndBuildPromise(A.promise),d.then(()=>{this.removeSplatSceneDownloadPromise(d)}).catch(e=>{console.error("Viewer::addSplatScene actual error:",e),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(d);const t=e instanceof S||"AbortError"===e.name?e:new Error(`Viewer::addSplatScene -> Could not load one or more scenes: ${e.message}`);p.reject(t),r&&r(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 i=e.length,n=[];let r;t&&(this.loadingSpinner.removeAllTasks(),r=this.loadingSpinner.addTask("Downloading..."));const a=(e,a,o,l)=>{n[e]=a;let c=0;for(let e=0;e<i;e++)c+=n[e]||0;c/=i,o=`${c.toFixed(2)}%`,t&&l===f.Downloading&&this.loadingSpinner.setMessageForTask(r,100==c?"Download complete!":`Downloading: ${o}`),s&&s(c,o,l)},o=new AbortController,l=o.signal;this.addSplatSceneDownloadController(o);const c=[];for(let t=0;t<e.length;t++){const s=e[t],i=void 0!==s.format&&null!==s.format?s.format:h(s.path),n=this.downloadSplatSceneToSplatBuffer(s.path,s.splatAlphaRemovalThreshold,a.bind(this,t),!1,void 0,i,s.headers,l);c.push(n)}const d=Promise.all(c).then(i=>(t&&this.loadingSpinner.removeTask(r),s&&s(0,"0%",f.Processing),this.addSplatBuffers(i,e,!0,t,t,!1,!1).then(()=>{s&&s(100,"100%",f.Processing),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(e=>{t&&this.loadingSpinner.removeTask(r),this.clearSplatSceneDownloadAndBuildPromise();throw"AbortError"===e.name?e:new Error("Viewer::addSplatScenes -> Could not load one or more splat scenes.")}).finally(()=>{this.removeSplatSceneDownloadController(o)});return this.setSplatSceneDownloadAndBuildPromise(d),d}downloadSplatSceneToSplatBuffer(e,t=1,s=void 0,i=!1,n=void 0,r,a){const o=!i&&this.optimizeSplatData;try{if(r===c.Ply)return rt.loadFromURL(e,s,i,n,t,this.inMemoryCompressionLevel,o,this.sphericalHarmonicsDegree,a)}catch(e){throw e instanceof pe?new Error("File type or server does not support progressive loading."):e}throw new Error(`Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ${e}`)}static isProgressivelyLoadable(e){return e===c.Ply}addSplatBuffers=(e,t=[],s=!0,i=!0,n=!0,r=!1,a=!1,o=!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=>{i&&(l=this.loadingSpinner.addTask("Processing splats...")),I(()=>{if(this.isDisposingOrDisposed())h();else{const i=this.addSplatBuffersToMesh(e,t,s,n,r,o),l=this.splatMesh.getMaxSplatCount();this.sortWorker&&this.sortWorker.maxSplatCount!==l&&this.disposeSortWorker(),this.gpuAcceleratedSort||this.preSortMessages.push({centers:i.centers.buffer,sceneIndexes:i.sceneIndexes.buffer,range:{from:i.from,to:i.to,count:i.count}});(!this.sortWorker&&l>0?this.setupSortWorker(this.splatMesh):Promise.resolve()).then(()=>{this.isDisposingOrDisposed()||this.runSplatSort(!0,!0).then(e=>{this.sortWorker&&e?(a?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,i=!0,n=!1,r=!1,a=!0){if(this.isDisposingOrDisposed())return;let o=[],l=[];r||(o=this.splatMesh.scenes.map(e=>e.splatBuffer)||[],l=this.splatMesh.sceneOptions?this.splatMesh.sceneOptions.map(e=>e):[]),o.push(...t),l.push(...s),this.renderer&&this.splatMesh.setRenderer(this.renderer);const c=this.splatMesh.build(o,l,!0,i,t=>{if(this.isDisposingOrDisposed())return;const s=this.splatMesh.getSplatCount();n&&s>=m&&(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)},a);return i&&this.freeIntermediateSplatData&&this.splatMesh.freeIntermediateSplatData(),c}}();async setupSortWorker(e){if(this.isDisposingOrDisposed())return;const t=this.integerBasedSort?Int32Array:Float32Array,s=e.getSplatCount(),i=e.getMaxSplatCount();return this.sortWorker=await function(e,t,s,i,n,r=p.DefaultSplatSortDistanceMapPrecision){const a=new Worker(URL.createObjectURL(new Blob(["(",pt.toString(),")(self)"],{type:"application/javascript"})));let o="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";const l=M()?w():null;s||t?s?t||l&&l.major<=16&&l.minor<4&&(o="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"):o=ut:(o=ut,l&&l.major<=16&&l.minor<4&&(o="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"));const c=atob(o),h=new Uint8Array(c.length);for(let e=0;e<c.length;e++)h[e]=c.charCodeAt(e);return a.postMessage({init:{sorterWasmBytes:h.buffer,splatCount:e,useSharedMemory:t,integerBasedSort:i,dynamicMode:n,distanceMapRange:1<<r,Constants:{BytesPerFloat:p.BytesPerFloat,BytesPerInt:p.BytesPerInt,MemoryPageSize:p.MemoryPageSize,MaxScenes:p.MaxScenes}}}),a}(i,this.sharedMemoryForWorkers,this.enableSIMDInSort,this.integerBasedSort,this.splatMesh.dynamicMode,this.splatSortDistanceMapPrecision),new Promise(e=>{this.sortWorker.onmessage=n=>{if(n.data.sortDone){if(this.sortRunning=!1,Array.from({length:this.gaussianSplatCount},(e,t)=>t),this.sharedMemoryForWorkers)this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes,n.data.splatRenderCount);else{const e=new Uint32Array(n.data.sortedIndexes.buffer,0,n.data.splatRenderCount);this.splatMesh.updateRenderIndexes(e,n.data.splatRenderCount)}this.lastSplatSortCount=this.splatSortCount,this.lastSortTime=n.data.sortTime,this.sortPromiseResolver(),this.sortPromiseResolver=null,this.forceRenderNextFrame(),this.runAfterNextSort.length>0&&(this.runAfterNextSort.forEach(e=>{e()}),this.runAfterNextSort.length=0)}else if(n.data.sortCanceled)this.sortRunning=!1;else if(n.data.sortSetupPhase1Complete){this.logLevel>=o.Info&&console.log("Sorting web worker WASM setup complete."),this.sharedMemoryForWorkers?(this.sortWorkerSortedIndexes=new Uint32Array(n.data.sortedIndexesBuffer,n.data.sortedIndexesOffset,i),this.sortWorkerIndexesToSort=new Uint32Array(n.data.indexesToSortBuffer,n.data.indexesToSortOffset,i),this.sortWorkerPrecomputedDistances=new t(n.data.precomputedDistancesBuffer,n.data.precomputedDistancesOffset,i),this.sortWorkerTransforms=new Float32Array(n.data.transformsBuffer,n.data.transformsOffset,16*p.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(i),this.sortWorkerPrecomputedDistances=new t(i),this.sortWorkerTransforms=new Float32Array(16*p.MaxScenes));for(let e=0;e<s;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=i,this.logLevel>=o.Info){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)}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((i,n)=>{let r;t&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),r=this.loadingSpinner.addTask("Removing splat scene..."));const a=()=>{t&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(r))},o=e=>{a(),this.splatSceneRemovalPromise=null,e?n(e):i()},l=()=>!!this.isDisposingOrDisposed()&&(o(),!0);s=this.sortPromise||Promise.resolve(),s.then(()=>{if(l())return;const t=[],i=[],n=[];for(let s=0;s<this.splatMesh.scenes.length;s++){let r=!1;for(let t of e)if(t===s){r=!0;break}if(!r){const e=this.splatMesh.scenes[s];t.push(e.splatBuffer),i.push(this.splatMesh.sceneOptions[s]),n.push({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})}}this.disposeSortWorker(),this.splatMesh.dispose(),this.sceneRevealMode=d.Instant,this.createSplatMesh(),this.addSplatBuffers(t,i,!0,!1,!0).then(()=>{l()||(a(),this.splatMesh.scenes.forEach((e,t)=>{e.position.copy(n[t].position),e.quaternion.copy(n[t].quaternion),e.scale.copy(n[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,o()}))}))}).catch(e=>{o(e)})})}),this.splatSceneRemovalPromise}start(){if(!this.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc),this.selfDrivenModeRunning=!0}stop(){this.selfDrivenMode&&this.selfDrivenModeRunning&&(cancelAnimationFrame(this.requestFrameId),this.selfDrivenModeRunning=!1)}async dispose(){if(this.isDisposingOrDisposed())return this.disposePromise;for(let e of this.splatSceneDownloadControllers)e.abort();let e=[];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.avatarMesh&&(v(this.avatarMesh),this.avatarMesh=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.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,this.sortWorkerSortedIndexes=null,this.sortWorkerIndexesToSort=null,this.sortWorkerPrecomputedDistances=null,this.sortWorkerTransforms=null,this.disposed=!0,this.disposing=!1,this.disposePromise=null}),this.disposePromise}vsyncNum=4;selfDrivenUpdate(){this.selfDrivenMode&&(this.requestFrameId=requestAnimationFrame(this.selfDrivenUpdateFunc)),this.vsyncCount++,this.vsyncCount<this.vsyncNum||(this.vsyncCount=0,this.update(),this.shouldRender()?(this.render(),this.consecutiveRenderFrames++):this.consecutiveRenderFrames=0,this.renderNextFrame=!1)}forceRenderNextFrame(){this.renderNextFrame=!0}shouldRender=function(){let e=0;const s=new t.Vector3,i=new t.Quaternion,n=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let t=!1,r=!1;if(this.camera){const e=this.camera.position,t=this.camera.quaternion;r=Math.abs(e.x-s.x)>n||Math.abs(e.y-s.y)>n||Math.abs(e.z-s.z)>n||Math.abs(t.x-i.x)>n||Math.abs(t.y-i.y)>n||Math.abs(t.z-i.z)>n||Math.abs(t.w-i.w)>n}return t=this.renderMode!==l.Never&&(0===e||this.splatMesh.visibleRegionChanging||r||this.renderMode===l.Always||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(s.copy(this.camera.position),i.copy(this.camera.quaternion)),e++,t}}();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){const s=document.getElementById("fps");s&&(s.textContent=`FPS: ${this.currentFPS}`),this.frame>=this.totalFrames&&(this.frame=0),this.dropInMode&&this.updateForDropInMode(e,t),this.initialized&&this.splatRenderReady&&!this.isDisposingOrDisposed()&&(this.controls&&(this.controls.update(),this.camera.isOrthographicCamera&&!this.usingExternalCamera&&ft.setCameraPositionFromZoom(this.camera,this.camera,this.controls)),this.runMorphUpdate(),this.runSplatSort(!0,!0),this.updateForRendererSizeChanges(),this.updateSplatMesh(),this.updateMeshCursor(),this.updateFPS(),this.timingSensitiveUpdates(),this.updateControlPlane())}sortedIndexes;updateForDropInMode(e,t){this.renderer=e,this.splatMesh&&this.splatMesh.setRenderer(this.renderer),this.camera=t,this.controls&&(this.controls.object=t),this.init()}lastCalcTime=y();fpsFrameCount=0;updateFPS=()=>{if(this.consecutiveRenderFrames>60){const e=y();e-this.lastCalcTime>=1?(this.currentFPS=this.fpsFrameCount,this.fpsFrameCount=0,this.lastCalcTime=e):this.fpsFrameCount++}else this.currentFPS=null};updateForRendererSizeChanges=function(){const e=new t.Vector2,s=new t.Vector2;let i;return function(){this.usingExternalCamera||(this.renderer.getSize(s),void 0!==i&&i===this.camera.isOrthographicCamera&&s.x===e.x&&s.y===e.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(),e.copy(s),i=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){const t=y();e||(e=t);const s=t-e;this.updateCameraTransition(t),this.updateFocusMarker(s),e=t}}();tempCameraTarget=new t.Vector3;toPreviousTarget=new t.Vector3;toNextTarget=new t.Vector3;updateCameraTransition=e=>{if(this.transitioningCameraTarget){this.toPreviousTarget.copy(this.previousCameraTarget).sub(this.camera.position).normalize(),this.toNextTarget.copy(this.nextCameraTarget).sub(this.camera.position).normalize();const t=Math.acos(this.toPreviousTarget.dot(this.toNextTarget)),s=(t/(Math.PI/3)*.65+.3)/t*(e-this.transitioningCameraTargetStartTime);this.tempCameraTarget.copy(this.previousCameraTarget).lerp(this.nextCameraTarget,s),this.camera.lookAt(this.tempCameraTarget),this.controls.target.copy(this.tempCameraTarget),s>=1&&(this.transitioningCameraTarget=!1)}};updateFocusMarker=function(){const e=new t.Vector2;let s=!1;return function(t){if(this.getRenderDimensions(e),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const i=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let n=Math.min(i+.4*t,1);this.sceneHelper.setFocusMarkerOpacity(n),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e),s=!0,this.forceRenderNextFrame()}else{let i;if(i=s?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),i>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e);let s=Math.max(i-.12*t,0);this.sceneHelper.setFocusMarkerOpacity(s),0===s&&this.sceneHelper.setFocusMarkerVisibility(!1)}i>0&&this.forceRenderNextFrame(),s=!1}}}();updateMeshCursor=function(){const e=[],s=new t.Vector2;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(s),e.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,s),this.raycaster.intersectSplatMesh(this.splatMesh,e),e.length>0?(this.sceneHelper.setMeshCursorVisibility(!0),this.sceneHelper.positionAndOrientMeshCursor(e[0].origin,this.camera)):this.sceneHelper.setMeshCursorVisibility(!1)):(this.sceneHelper.getMeschCursorVisibility()&&this.forceRenderNextFrame(),this.sceneHelper.setMeshCursorVisibility(!1))}}();updateInfoPanel=function(){const e=new t.Vector2;return function(){if(!this.showInfo)return;const t=this.splatMesh.getSplatCount();this.getRenderDimensions(e),this.controls&&this.controls.target,this.showMeshCursor&&this.sceneHelper.meshCursor.position,t>0&&this.splatRenderCount}}();updateControlPlane(){this.showControlPlane?(this.sceneHelper.setControlPlaneVisibility(!0),this.sceneHelper.positionAndOrientControlPlane(this.controls.target,this.camera.up)):this.sceneHelper.setControlPlaneVisibility(!1)}mvpMatrix=new t.Matrix4;cameraPositionArray=[];lastSortViewDir=new t.Vector3(0,0,-1);sortViewDir=new t.Vector3(0,0,-1);lastSortViewPos=new t.Vector3;sortViewOffset=new t.Vector3;queuedSorts=[];partialSorts=[{angleThreshold:.55,sortFractions:[.125,.33333,.75]},{angleThreshold:.65,sortFractions:[.33333,.66667]},{angleThreshold:.8,sortFractions:[.5]}];runSplatSort=(e=!1,t=!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 s=0,i=0,n=!1,r=!1;if(this.sortViewDir.set(0,0,-1).applyQuaternion(this.camera.quaternion),s=this.sortViewDir.dot(this.lastSortViewDir),i=this.sortViewOffset.copy(this.camera.position).sub(this.lastSortViewPos).length(),!(e||this.splatMesh.dynamicMode||0!==this.queuedSorts.length||(s<=.99&&(n=!0),i>=1&&(r=!0),n||r)))return Promise.resolve(!1);this.sortRunning=!0;let{splatRenderCount:a,shouldSortAll:o}=this.gatherSceneNodesForSort();o=o||t,this.splatRenderCount=a,this.mvpMatrix.copy(this.camera.matrixWorld).invert();const l=this.perspectiveCamera||this.camera;this.mvpMatrix.premultiply(l.projectionMatrix),this.splatMesh.dynamicMode||this.mvpMatrix.multiply(this.splatMesh.matrixWorld);let c=Promise.resolve(!0);return this.gpuAcceleratedSort&&(this.queuedSorts.length<=1||this.queuedSorts.length%2==0)&&(c=this.splatMesh.computeDistancesOnGPU(this.mvpMatrix,this.sortWorkerPrecomputedDistances)),c.then(()=>{if(0===this.queuedSorts.length)if(this.splatMesh.dynamicMode||o)this.queuedSorts.push(this.splatRenderCount);else{for(let e of this.partialSorts)if(s<e.angleThreshold){for(let t of e.sortFractions)this.queuedSorts.push(Math.floor(this.splatRenderCount*t));break}this.queuedSorts.push(this.splatRenderCount)}let e=Math.min(this.queuedSorts.shift(),this.splatRenderCount);this.splatSortCount=e,this.cameraPositionArray[0]=this.camera.position.x,this.cameraPositionArray[1]=this.camera.position.y,this.cameraPositionArray[2]=this.camera.position.z;const t={modelViewProj:this.mvpMatrix.elements,cameraPosition:this.cameraPositionArray,splatRenderCount:this.splatRenderCount,splatSortCount:e,usePrecomputedDistances:this.gpuAcceleratedSort};return this.splatMesh.dynamicMode&&this.splatMesh.fillTransformsArray(this.sortWorkerTransforms),this.sharedMemoryForWorkers||(t.indexesToSort=this.sortWorkerIndexesToSort,t.transforms=this.sortWorkerTransforms,this.gpuAcceleratedSort&&(t.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:t}),0===this.queuedSorts.length&&(this.lastSortViewPos.copy(this.camera.position),this.lastSortViewDir.copy(this.sortViewDir)),!0}),c};gatherSceneNodesForSort=function(){const e=[];let s=null;const i=new t.Vector3,n=new t.Vector3,r=new t.Vector3,a=new t.Matrix4,o=new t.Matrix4,l=new t.Matrix4,c=new t.Vector3,h=new t.Vector3(0,0,-1),d=new t.Vector3,u=e=>d.copy(e.max).sub(e.min).length();return function(d=!1){this.getRenderDimensions(c);const A=c.y/2/Math.tan(this.camera.fov/2*t.MathUtils.DEG2RAD),m=Math.atan(c.x/2/A),g=Math.atan(c.y/2/A),f=Math.cos(m),S=Math.cos(g),C=this.splatMesh.getSplatTree();if(C){o.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||o.multiply(this.splatMesh.matrixWorld);let t=0,s=0;for(let c=0;c<C.subTrees.length;c++){const p=C.subTrees[c];a.copy(o),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(c,l),a.multiply(l));const A=p.nodesWithIndexes.length;for(let o=0;o<A;o++){const l=p.nodesWithIndexes[o];if(!l.data||!l.data.indexes||0===l.data.indexes.length)continue;r.copy(l.center).applyMatrix4(a);const c=r.length();r.normalize(),i.copy(r).setX(0).normalize(),n.copy(r).setY(0).normalize();const A=h.dot(n),m=h.dot(i),g=u(l);!d&&(A<f-.6||m<S-.6)&&c>g||(s+=l.data.indexes.length,e[t]=l,l.data.distanceToNode=c,t++)}}e.length=t,e.sort((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1);let c=s*p.BytesPerInt;for(let s=0;s<t;s++){const t=e[s],i=t.data.indexes.length,n=i*p.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,c-n,i).set(t.data.indexes),c-=n}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")}createBonesFromJson(e){const s=[];function i(e,n=null){const r=new t.Bone;return r.name=e.name,n&&n.add(r),r.position.set(...e.position),s.push(r),e.children&&e.children.forEach(e=>i(e,r)),r}return e.forEach(e=>i(e)),s}updateMorphTarget(e){if(this.avatarMesh=e,this.splatMesh.flameModel=e,this.splatMesh.useFlameModel=this.useFlame,1==this.useFlame){this.bones=this.createBonesFromJson(this.bone_tree.bones);const e=[new t.Vector3(this.bones[0].position.x,this.bones[0].position.y,this.bones[0].position.z),new t.Vector3(this.bones[1].position.x,this.bones[1].position.y,this.bones[1].position.z),new t.Vector3(this.bones[2].position.x,this.bones[2].position.y,this.bones[2].position.z),new t.Vector3(this.bones[3].position.x,this.bones[3].position.y,this.bones[3].position.z),new t.Vector3(this.bones[4].position.x,this.bones[4].position.y,this.bones[4].position.z)];this.bones[1].position.copy(new t.Vector3(e[1].x-e[0].x,e[1].y-e[0].y,e[1].z-e[0].z)),this.bones[2].position.copy(new t.Vector3(e[2].x-e[1].x,e[2].y-e[1].y,e[2].z-e[1].z)),this.bones[3].position.copy(new t.Vector3(e[3].x-e[1].x,e[3].y-e[1].y,e[3].z-e[1].z)),this.bones[4].position.copy(new t.Vector3(e[4].x-e[1].x,e[4].y-e[1].y,e[4].z-e[1].z)),this.bones[0].updateMatrixWorld(!0);const s=[this.bones[0].matrixWorld.clone().invert(),this.bones[1].matrixWorld.clone().invert(),this.bones[2].matrixWorld.clone().invert(),this.bones[3].matrixWorld.clone().invert(),this.bones[4].matrixWorld.clone().invert()];this.skeleton=new t.Skeleton(this.bones,s)}this.runMorphUpdate(),this.splatMesh.gaussianSplatCount=this.gaussianSplatCount}updatedBoneMatrices(e){let t=[];for(let s=0;s<e;s++){let i;function n(e,t){let s=e.elements;for(let e=0;e<s.length;e++)t.push(s[e])}i=this.skeleton.bones[s].matrixWorld.clone().multiply(this.skeleton.boneInverses[s].clone()),n(i,t)}return new Float32Array(t)}runMorphUpdate(){this.gaussianSplatCount=this.avatarMesh.geometry.attributes.position.count;var e=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(this.splatMesh.bonesNum=5,0==this.useFlame){if(this.skinModel.skeleton.update(),this.boneRoot.updateMatrixWorld(!0),this.splatMesh.geometry.getAttribute("splatIndex")&&!1===this.setSkinAttibutes){this.setSkinAttibutes=!0;const e=this.splatMesh.geometry,s=this.skinModel.geometry.attributes.skinIndex,i=this.skinModel.geometry.attributes.skinWeight,n=new t.InstancedBufferAttribute(new s.array.constructor(s.array),4,s.normalized,1),r=new t.InstancedBufferAttribute(new i.array.constructor(i.array),4,i.normalized,1);n.setUsage(t.DynamicDrawUsage),r.setUsage(t.DynamicDrawUsage),e.setAttribute("skinIndex",n),e.setAttribute("skinWeight",r)}}else this.updateFlameBones();this.splatMesh.morphedMesh=e;let s=this.splatMesh.morphedMesh.length/3;null!=this.splatMesh.splatDataTextures.flameModel&&this.splatMesh.updateTetureAfterBSAndSkeleton(0,s-1,this.useFlame)}updateFlameBones(){function e(e,s,i=!1){let n;if(1==i)n=new t.Quaternion(s[0],s[1],s[2],s[3]);else{const e=new t.Vector3(s[0],s[1],s[2]),i=e.length(),r=e.normalize();n=(new t.Quaternion).setFromAxisAngle(r,i)}e.quaternion.copy(n),e.updateMatrixWorld(!0)}this.splatMesh.bsWeight=this.flame_params.expr[this.frame];let s=this.flame_params.rotation[this.frame];e(this.skeleton.bones[0],s),s=this.flame_params.neck_pose[this.frame],e(this.skeleton.bones[1],s),s=this.flame_params.jaw_pose[this.frame],e(this.skeleton.bones[2],s),s=this.flame_params.eyes_pose[this.frame],e(this.skeleton.bones[3],s),e(this.skeleton.bones[4],[s[3],s[4],s[5]]),this.skeleton.update();const i=this.updatedBoneMatrices(5);this.splatMesh.bonesMatrix=i,this.splatMesh.bonesNum=5,this.splatMesh.bonesWeight=this.lbs_weight_80k}}const St={x:0,y:1.8,z:1},Ct={x:-10,y:0,z:0},xt="ffffff",yt="false",vt={offset:{},scale:{}},It={hello:{size:2,isGroup:!1},idle:{size:1,isGroup:!1},listen:{size:0,isGroup:!1},speak:{size:6,isGroup:!1},think:{size:3,isGroup:!0},other:[]};class Bt{static _canvas="undefined"!=typeof document?document.createElement("canvas"):null;static instance=void 0;static async getInstance(e,s,n={}){if(void 0!==this.instance)return this.instance;try{const r=s,a=new URL(r,window.location.href),o=a.pathname.match(/\/([^/]+?)\.zip/);if(!(o&&o[1]))throw new Error("character model is not found");"undefined"!=typeof NProgress&&NProgress.start();const l=await fetch(r);if(!l.ok)throw new Error(`Failed to download: ${l.statusText}`);n.downloadProgress&&n.downloadProgress(1),n.loadProgress&&n.loadProgress(.1),"undefined"!=typeof NProgress&&NProgress.done();const h=await l.arrayBuffer(),d=await i.loadAsync(h);let u="";if(Object.values(d.files).forEach(e=>{e.dir&&(u=e.name?.slice(0,e.name?.length-1))}),!u)throw new Error("file folder is not found");const p=new Bt(e,d),A=new t.Vector3;A.x=St?.x||0,A.y=St?.y||0,A.z=St?.z||1;const m=new t.Vector3;m.x=Ct?.x||0,m.y=Ct?.y||0,m.z=Ct?.z||0;let g=16777215;xt&&(g=parseInt(xt,16)),n?.backgroundColor&&p.isHexColorStrict(n.backgroundColor)&&(g=parseInt(n.backgroundColor,16)),p.getChatState=n?.getChatState,p.getExpressionData=n?.getExpressionData,yt&&(p.useFlame="false"!==yt),p.viewer=new ft({rootElement:e,threejsCanvas:Bt._canvas,cameraUp:[0,1,0],initialCameraPosition:[A.x,A.y,A.z],initialCameraRotation:[m.x,m.y,m.z],sphericalHarmonicsDegree:0,backgroundColor:g}),p.viewer.useFlame=p.useFlame,!0===p.viewer.useFlame?await p.loadFlameModel(u,vt):await p.loadModel(u,It,vt),n.loadProgress&&n.loadProgress(.2);const f=await p.unpackFileAsBlob(u+"/offset.ply");return n.loadProgress&&n.loadProgress(.3),await p.viewer.addSplatScene(f,{progressiveLoad:!0,sharedMemoryForWorkers:!1,showLoadingUI:!1,format:c.Ply}),p.render(),n.loadProgress&&n.loadProgress(1),this.instance=p,p}catch(e){throw console.error("GaussianSplatRenderer.getInstance error:",e),e}}constructor(e,s){if(this.zipUrls={urls:new Map,zip:s},this.useFlame=!1,this.lastTime=0,this.startTime=0,this.expressionData={},this.chatState=z.Idle,Bt._canvas&&e){const{width:t,height:s}=e.getBoundingClientRect();Bt._canvas.style.visibility="visible",Bt._canvas.width=t,Bt._canvas.height=s,e.appendChild(Bt._canvas)}this.clock=new t.Clock,this.startTime=performance.now()/1e3,this.viewer=null,this.mixer=null,this.animManager=null,this.model=null,this.motioncfg=null,this.getChatState=null,this.getExpressionData=null}dispose(){Bt._canvas&&(Bt._canvas.style.visibility="hidden"),this.disposeModel(),this.zipUrls.urls.forEach(e=>{URL.revokeObjectURL(e)}),Bt.instance=void 0}disposeModel(){this.mixer&&(this.mixer.stopAllAction(),this.viewer?.avatarMesh&&this.mixer.uncacheRoot(this.viewer.avatarMesh),this.mixer=void 0,this.animManager?.dispose()),this.viewer?.dispose()}getCamera(){return this.viewer?.camera}updateBS(e){let t={browDownLeft:0,browDownRight:0,browInnerUp:0,browOuterUpLeft:0,browOuterUpRight:0,mouthCheekPuff:0,cheekSquintLeft:0,cheekSquintRight:0,eyeBlinkLeft:0,eyeBlinkRight:0,eyeLookDownLeft:0,eyeLookDownRight:0,eyeLookInLeft:0,eyeLookInRight:0,eyeLookOutLeft:0,eyeLookOutRight:0,eyeLookUpLeft:0,eyeLookUpRight:0,eyeSquintLeft:0,eyeSquintRight:0,eyeWideLeft:0,eyeWideRight:0,jawForward:0,jawLeft:0,jawOpen:0,jawRight:0,mouthClose:0,mouthDimpleLeft:0,mouthDimpleRight:0,mouthFrownLeft:0,mouthFrownRight:0,mouthFunnel:0,mouthLeft:0,mouthLowerDownLeft:0,mouthLowerDownRight:0,mouthPressLeft:0,mouthPressRight:0,mouthPucker:0,mouthRight:0,mouthRollLower:0,mouthRollUpper:0,mouthShrugLower:0,mouthShrugUpper:0,mouthSmileLeft:0,mouthSmileRight:0,mouthStretchLeft:0,mouthStretchRight:0,mouthUpperUpLeft:0,mouthUpperUpRight:0,noseSneerLeft:0,noseSneerRight:0,tongueOut:0};return null!=e&&(t=e),t}render(){if(!this.viewer||!this.viewer.selfDrivenMode)throw new Error("Cannot start viewer unless it is in self driven mode.");{this.viewer.requestFrameId=requestAnimationFrame(()=>this.render());const e=1/30,t=performance.now()/1e3,s=this.viewer.totalFrames||1,i=(t-this.startTime)%(s*e),n=Math.floor(i/e);if(this.viewer.frame=n,this.getChatState&&(this.chatState=this.getChatState(),this._lastLoggedState&&this._lastLoggedState===this.chatState||(console.log("[ANIM] Chat state changed to:",this.chatState,"animManager exists:",!!this.animManager),this._lastLoggedState=this.chatState),this.animManager?.update(this.chatState)),this.getExpressionData&&(this.expressionData=this.updateBS(this.getExpressionData())),!1===this.viewer.useFlame)if(this.mixer&&this.animManager){const e=this.clock.getDelta();if(this.mixer.update(e),this.motioncfg)for(const e in this.expressionData){const t=this.motioncfg.offset?.[e],s=this.motioncfg.scale?.[e];void 0!==t&&void 0!==s&&(this.expressionData[e]=this.expressionData[e]*s+t)}this.setExpression()}else this._warnedOnce||(console.warn("render: mixer or animManager not initialized, skipping animation update"),console.log("[ANIM] useFlame:",this.viewer.useFlame,"mixer:",!!this.mixer,"animManager:",!!this.animManager),this._warnedOnce=!0);this.viewer.update(this.viewer.renderer,this.viewer.camera);const r=this.viewer.shouldRender();this._renderLogCount<=3&&console.log("[GS-DEBUG] shouldRender:",r),r?(this.viewer.render(),this.viewer.consecutiveRenderFrames++):this.viewer.consecutiveRenderFrames=0,this.viewer.renderNextFrame=!1,this.viewer.selfDrivenModeRunning=!0}}isHexColorStrict(e){if("string"!=typeof e)return!1;return/^(#|0x)[0-9A-Fa-f]{6}$/i.test(e)}setExpression(){this.viewer?.splatMesh&&(this.viewer.splatMesh.bsWeight=this.expressionData),this.model&&this.model.traverse(e=>{if(e.isMesh||e.isSkinnedMesh){const t=e.geometry?.morphAttributes;if(t&&Object.keys(t).length>0){const t=e.morphTargetDictionary;for(const s in t){const i=t[s],n=this.expressionData[s];void 0!==n&&(e.morphTargetInfluences[i]=Math.max(0,Math.min(1,n)))}}}})}async loadFlameModel(e,s){const[i,n,r,a,o]=await Promise.all([this.unpackAndLoadGlb(e+"/skin.glb"),this.unpackAndLoadJson(e+"/lbs_weight_20k.json"),this.unpackAndLoadJson(e+"/flame_params.json"),this.unpackAndLoadJson(e+"/vertex_order.json"),this.unpackAndLoadJson(e+"/bone_tree.json")]);if(!this.viewer)throw new Error("render viewer is not initialized");let l,c;i.traverse(e=>{e.isSkinnedMesh&&(l=e),e instanceof t.Bone&&"hip"===e.name&&(c=e)}),this.viewer.sortedIndexes=a,this.viewer.flame_params=r,this.viewer.lbs_weight_80k=n,this.viewer.bone_tree=o,this.viewer.totalFrames=r.expr?.length||1,l&&(this.viewer.gaussianSplatCount=l.geometry.attributes.position.count),this.viewer.avatarMesh=i,this.viewer.skinModel=l,this.viewer.boneRoot=c,this.motioncfg=s,l&&this.viewer.updateMorphTarget(l),this.viewer.threeScene.add(i),i.visible=!1,l&&l.skeleton.computeBoneTexture()}async loadModel(e,s,i){const[n,r,a]=await Promise.all([this.unpackAndLoadGlb(e+"/skin.glb"),this.unpackAndLoadGlb(e+"/animation.glb"),this.unpackAndLoadJson(e+"/vertex_order.json")]);if(!this.viewer)throw new Error("render viewer is not initialized");let o,l;n.traverse(e=>{e.isSkinnedMesh&&(o=e),e instanceof t.Bone&&"hip"===e.name&&(l=e)}),this.viewer.sortedIndexes=a,o&&(this.viewer.gaussianSplatCount=o.geometry.attributes.position.count),this.viewer.avatarMesh=n,this.viewer.skinModel=o,this.viewer.boneRoot=l,this.mixer=new t.AnimationMixer(n),this.animManager=new Z(this.mixer,r,s),this.motioncfg=i,Array.isArray(r)&&r.length>0&&r[0].duration?this.viewer.totalFrames=Math.floor(30*r[0].duration):this.viewer.totalFrames=1,console.log("loadModel: totalFrames set to",this.viewer.totalFrames),o&&this.viewer.updateMorphTarget(o),this.viewer.threeScene.add(n),n.visible=!1,o&&o.skeleton.computeBoneTexture()}async unpackFileAsBlob(e){if(!this.zipUrls.urls.has(e)){const t=await(this.zipUrls.zip?.file(e)?.async("blob"));if(t){const s=URL.createObjectURL(t);this.zipUrls.urls.set(e,s)}}return this.zipUrls.urls.get(e)}async unpackAndLoadGlb(e){if(!this.zipUrls.urls.has(e)){const t=await(this.zipUrls.zip?.file(e)?.async("arraybuffer"));if(t){const s=new Blob([t],{type:"model/gltf-binary"}),i=URL.createObjectURL(s);this.zipUrls.urls.set(e,i)}}return this.LoadGLTF(this.zipUrls.urls.get(e))}async unpackAndLoadJson(e){const t=this.zipUrls.zip?.file(e);if(!t)throw new Error(`File not found in ZIP: ${e}`);const s=await t.async("string");if(!s)throw new Error(`Failed to read file from ZIP: ${e}`);return JSON.parse(s)}async LoadGLTF(e){return new Promise((t,i)=>{(new s.GLTFLoader).load(e,e=>{e.animations.length>0?t(e.animations):t(e.scene)},void 0,e=>{i(e)})})}}const Tt=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}();function bt(e,s,i){const n=new t.Vector2(4096,2048),r=e.geometry.attributes.position.array;let a=[];const o=r.length/3,l=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach(t=>{const s=e.morphTargetDictionary[t],i=e.geometry.morphAttributes.position[s];a=a.concat(Array.from(i.array))}),a=a.concat(Array.from(r));const c=new Float32Array(n.x*n.y*4),h=new Uint32Array(n.x*n.y*4);for(let e=0;e<o*(l+1);e++)c[4*e+0]=a[3*e+0],c[4*e+1]=a[3*e+1],c[4*e+2]=a[3*e+2],h[4*e+0]=Tt(c[4*e+0]),h[4*e+1]=Tt(c[4*e+1]),h[4*e+2]=Tt(c[4*e+2]);const d=new t.DataTexture(h,n.x,n.y,t.RGBAIntegerFormat,t.UnsignedIntType);return d.internalFormat="RGBA32UI",d.needsUpdate=!0,s.uniforms.flameModelTexture.value=d,s.uniforms.flameModelTextureSize.value.copy(n),s.uniforms.gaussianSplatCount.value=i,s.uniformsNeedUpdate=!0,{data:h,texture:d,size:n,baseData:{flameModelPos:c}}}function Dt(e,s,i,n,r,a,o){if(!i)return null;const l=new t.Vector2(4,32),c=new Float32Array(e),h=new Uint32Array(l.x*l.y*4);if(o){for(let e=0;e<16*s;e++)h[e]=Tt(c[e]);r&&r.skeleton&&(a.uniforms.boneTexture0.value=r.skeleton.boneTexture,a.uniforms.bindMatrix.value=r.bindMatrix,a.uniforms.bindMatrixInverse.value=r.bindMatrixInverse)}for(const e in i)if(Object.hasOwn(i,e)){const t=i[e];h[n[e]+16*s]=Tt(t)}const d=new t.DataTexture(h,l.x,l.y,t.RGBAIntegerFormat,t.UnsignedIntType);return d.internalFormat="RGBA32UI",d.needsUpdate=!0,a.uniforms.boneTexture.value=d,a.uniforms.boneTextureSize.value.copy(l),a.uniformsNeedUpdate=!0,{data:h,texture:d,size:l,baseData:{boneMatrix:h}}}function Mt(e,t,s,i,n,r,a,o=!1){if(i&&n){if(o){const i=new Float32Array(t);for(let t=0;t<16*s;t++)e.baseData.boneMatrix[t]=Tt(i[t])}for(const t in i)if(Object.hasOwn(i,t)){const r=i[t],a=n[t];e.baseData.boneMatrix[a+16*s]=Tt(r)}e.boneMatrix.texture.data=e.baseData.boneMatrix,e.boneMatrix.texture.needsUpdate=!0,a.uniforms.boneTexture.value=e.boneMatrix.texture,r.skeleton&&(a.uniforms.boneTexture0.value=r.skeleton.boneTexture,a.uniforms.bindMatrix.value=r.bindMatrix,a.uniforms.bindMatrixInverse.value=r.bindMatrixInverse),a.uniformsNeedUpdate=!0}}function wt(e,s,i){const n=e.geometry.attributes.position.array.length/3,r=new t.Vector2(512,512),a=new Float32Array(r.x*r.y*4),o=new Uint32Array(r.x*r.y*4);for(let e=0;e<n;e++)a[8*e+0]=s[e][0],a[8*e+1]=s[e][1],a[8*e+2]=s[e][2],a[8*e+3]=s[e][3],a[8*e+4]=s[e][4],o[8*e+0]=Tt(s[e][0]),o[8*e+1]=Tt(s[e][1]),o[8*e+2]=Tt(s[e][2]),o[8*e+3]=Tt(s[e][3]),o[8*e+4]=Tt(s[e][4]);const l=new t.DataTexture(o,r.x,r.y,t.RGBAIntegerFormat,t.UnsignedIntType);return l.internalFormat="RGBA32UI",l.needsUpdate=!0,i.uniforms.boneWeightTexture.value=l,i.uniforms.boneWeightTextureSize.value.copy(r),i.uniformsNeedUpdate=!0,{data:o,texture:l,size:r,baseData:{boneWeight:o}}}function Et(e,t){const s=[];for(let i=0;i<t;i++){const t=e.bones[i].matrixWorld.clone().multiply(e.boneInverses[i].clone()).elements;for(let e=0;e<t.length;e++)s.push(t[e])}return new Float32Array(s)}const Rt={buildModelTexture:bt,buildBoneMatrixTexture:Dt,updateBoneMatrixTexture:Mt,buildBoneWeightTexture:wt,getUpdatedBoneMatrices:Et};e.ARKIT_BLENDSHAPES_COUNT=G,e.ARKitBlendshapes=V,e.AbortedPromiseError=S,e.AnimationManager=Z,e.BASE_COMPONENT_COUNT=14,e.CENTER_COLORS_ELEMENTS_PER_SPLAT=4,e.CENTER_COLORS_ELEMENTS_PER_TEXEL=4,e.CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION=60,e.COVARIANCES_ELEMENTS_PER_SPLAT=6,e.COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED=4,e.COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED=8,e.COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED=6,e.COVARIANCES_ELEMENTS_PER_TEXEL_STORED=4,e.Constants=p,e.DefaultSphericalHarmonics8BitCompressionHalfRange=F,e.DefaultSphericalHarmonics8BitCompressionRange=A,e.DirectLoadError=pe,e.FLAME_BONES_COUNT=W,e.FOCUS_MARKER_FADE_IN_SPEED=.4,e.FOCUS_MARKER_FADE_OUT_SPEED=.12,e.FieldSize=ke,e.FieldSizeStringMap=Pe,e.FlameAnimator=class{constructor(){this.skeleton=null,this.bones=null,this.flameParams=null,this.lbsWeight=null,this.frame=0,this.totalFrames=0,this.useFlame=!0,this.avatarMesh=null,this.gaussianSplatCount=0}initialize(e,t,s,i){this.flameParams=e,this.lbsWeight=s,this.avatarMesh=i,e&&e.rotation&&(this.totalFrames=e.rotation.length),this.gaussianSplatCount=i.geometry.attributes.position.count,this.buildSkeleton(t)}buildSkeleton(e){if(!e)return;this.bones=[];const s=[],i=(e,n=null)=>{const r=new t.Bone;r.name=e.name||`bone_${this.bones.length}`,e.position&&r.position.fromArray(e.position),e.rotation&&r.rotation.fromArray(e.rotation),e.scale&&r.scale.fromArray(e.scale),n&&n.add(r),this.bones.push(r);const a=new t.Matrix4;e.inverseBindMatrix?a.fromArray(e.inverseBindMatrix):(r.updateMatrixWorld(!0),a.copy(r.matrixWorld).invert()),s.push(a),e.children&&e.children.forEach(e=>i(e,r))};Array.isArray(e)?(e.forEach((e,i)=>{const n=new t.Bone;n.name=e.name||`bone_${i}`,e.position&&n.position.fromArray(e.position),this.bones.push(n);const r=new t.Matrix4;e.inverseBindMatrix&&r.fromArray(e.inverseBindMatrix),s.push(r)}),this.bones.length>=5&&(this.bones[0].add(this.bones[1]),this.bones[1].add(this.bones[2]),this.bones[1].add(this.bones[3]),this.bones[1].add(this.bones[4]))):e.root&&i(e.root),this.skeleton=new t.Skeleton(this.bones,s)}setBoneRotation(e,s,i=!1){let n;if(i)n=new t.Quaternion(s[0],s[1],s[2],s[3]);else{const e=new t.Vector3(s[0],s[1],s[2]),i=e.length(),r=e.normalize();n=(new t.Quaternion).setFromAxisAngle(r,i)}e.quaternion.copy(n),e.updateMatrixWorld(!0)}updateFlameBones(){if(!this.flameParams||!this.skeleton)return{};const e=this.frame,t=this.flameParams.expr[e],s=this.flameParams.rotation[e];this.setBoneRotation(this.skeleton.bones[0],s);const i=this.flameParams.neck_pose[e];this.setBoneRotation(this.skeleton.bones[1],i);const n=this.flameParams.jaw_pose[e];this.setBoneRotation(this.skeleton.bones[2],n);const r=this.flameParams.eyes_pose[e];this.setBoneRotation(this.skeleton.bones[3],r),this.setBoneRotation(this.skeleton.bones[4],[r[3],r[4],r[5]]),this.skeleton.update();return{bsWeight:t,bonesMatrix:Rt.getUpdatedBoneMatrices(this.skeleton,5),bonesNum:5,bonesWeight:this.lbsWeight}}runMorphUpdate(e){const t=new Float32Array(this.avatarMesh.geometry.attributes.position.array);if(e.gaussianSplatCount=this.gaussianSplatCount,e.bonesNum=5,this.useFlame){const t=this.updateFlameBones();e.bsWeight=t.bsWeight,e.bonesMatrix=t.bonesMatrix,e.bonesNum=t.bonesNum,e.bonesWeight=t.bonesWeight}e.morphedMesh=t;const s=e.morphedMesh.length/3;e.splatDataTextures&&e.splatDataTextures.flameModel&&e.updateTextureAfterBSAndSkeleton(0,s-1,this.useFlame)}setFrame(e){this.frame=e%this.totalFrames}nextFrame(){this.frame=(this.frame+1)%this.totalFrames}getSkeleton(){return this.skeleton}getFrame(){return this.frame}getTotalFrames(){return this.totalFrames}},e.FlameBoneNames=N,e.FlameConstants={FlameBonesCount:5,DefaultBlendshapeCount:52,FlameModelTextureSize:{width:4096,height:2048},BoneTextureSize:{width:4,height:32},BoneWeightTextureSize:{width:512,height:512}},e.FlameTextureManager=Rt,e.GaussianSplatRenderer=Bt,e.Hello=K,e.Hit=ht,e.INRIAV1PlyParser=st,e.Idle=j,e.InternalLoadType=g,e.Listen=J,e.LoaderStatus=f,e.LoaderUtils=class{static decodeText(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0,i=e.length;s<i;s++)t+=String.fromCharCode(e[s]);try{return decodeURIComponent(escape(t))}catch(e){return t}}static extractUrlBase(e){const t=e.lastIndexOf("/");return-1===t?"./":e.slice(0,t+1)}static resolveURL(e,t){return"string"!=typeof e||""===e?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},e.LogLevel=o,e.MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT=.5,e.MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER=m,e.PlyFormat=Te,e.PlyLoader=rt,e.PlyParser=it,e.PlyParserUtils=Le,e.Ray=ct,e.Raycaster=dt,e.RenderMode=l,e.SCALES_ROTATIONS_ELEMENTS_PER_TEXEL=4,e.SCENE_FADEIN_RATE_FAST=.012,e.SCENE_FADEIN_RATE_GRADUAL=.003,e.SCENE_INDEXES_ELEMENTS_PER_TEXEL=1,e.SceneFormat=c,e.SceneRevealMode=d,e.Semver=D,e.Speak=Y,e.SplatBuffer=ve,e.SplatBufferGenerator=Be,e.SplatGeometry=ee,e.SplatMaterial=ie,e.SplatMaterial2D=re,e.SplatMaterial3D=ne,e.SplatMesh=ue,e.SplatPartitioner=Ie,e.SplatRenderMode=u,e.SplatScene=$,e.SplatTree=se,e.State=q,e.THREE_CAMERA_FOV=50,e.TYVoiceChatState=z,e.TextureConstants={CENTER_COLORS_ELEMENTS_PER_TEXEL:4,CENTER_COLORS_ELEMENTS_PER_SPLAT:4,COVARIANCES_ELEMENTS_PER_TEXEL_STORED:2,COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED:4,COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED:2,COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED:4,COVARIANCES_ELEMENTS_PER_SPLAT:6,SCALES_ROTATIONS_ELEMENTS_PER_TEXEL:4,SCENE_INDEXES_ELEMENTS_PER_TEXEL:1,MAX_TEXTURE_TEXELS:16777216},e.Think=X,e.UncompressedSplatArray=Ae,e.Viewer=ft,e.abortablePromiseWithExtractedComponents=b,e.buildBoneMatrixTexture=Dt,e.buildBoneWeightTexture=wt,e.buildModelTexture=bt,e.clamp=x,e.convertBetweenCompressionLevels=_,e.copyBetweenBuffers=(e,t,s,i,n=0)=>{const r=new Uint8Array(e,t),a=new Uint8Array(s,i);for(let e=0;e<n;e++)a[e]=r[e]},e.dataViewFloatForCompressionLevel=(e,t,s,i=!1)=>0===s?e.getFloat32(4*t,!0):1===s||2===s&&!i?e.getUint16(2*t,!0):e.getUint8(t,!0),e.delayedExecute=I,e.disposeAllMeshes=v,e.fetchWithProgress=C,e.floatToHalf=H,e.fromHalfFloat=R,e.fromHalfFloatToUint8=L,e.fromUint8=k,e.fromUint8ToHalfFloat=U,e.getCurrentTime=y,e.getIOSSemever=w,e.getSphericalHarmonicsComponentCountForDegree=B,e.getUpdatedBoneMatrices=Et,e.isIOS=M,e.nativePromiseWithExtractedComponents=T,e.rgbaArrayToInteger=Q,e.rgbaToInteger=function(e,t,s,i){return e+(t<<8)+(s<<16)+(i<<24)},e.sceneFormatFromPath=h,e.toHalfFloat=E,e.toUint8=P,e.toUncompressedFloat=(e,s,i=!1,n,r)=>0===s?e:1===s||2===s&&!i?t.DataUtils.fromHalfFloat(e):2===s?k(e,n,r):void 0,e.uintEncodedFloat=O,e.updateBoneMatrixTexture=Mt});
|
|
2
|
+
//# sourceMappingURL=gsplat-flame-avatar-renderer.umd.min.js.map
|