@myned-ai/gsplat-flame-avatar-renderer 1.0.2 → 1.0.5

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.
Files changed (66) hide show
  1. package/README.md +6 -36
  2. package/dist/gsplat-flame-avatar-renderer.cjs.js +12875 -0
  3. package/dist/{gsplat-flame-avatar-renderer.umd.js.map → gsplat-flame-avatar-renderer.cjs.js.map} +1 -1
  4. package/dist/gsplat-flame-avatar-renderer.esm.js +1 -1
  5. package/package.json +6 -11
  6. package/src/api/index.js +7 -0
  7. package/src/buffers/SplatBuffer.js +1394 -0
  8. package/src/buffers/SplatBufferGenerator.js +41 -0
  9. package/src/buffers/SplatPartitioner.js +110 -0
  10. package/src/buffers/UncompressedSplatArray.js +106 -0
  11. package/src/buffers/index.js +11 -0
  12. package/src/core/SplatGeometry.js +48 -0
  13. package/src/core/SplatMesh.js +2620 -0
  14. package/src/core/SplatScene.js +43 -0
  15. package/src/core/SplatTree.js +200 -0
  16. package/src/core/Viewer.js +2895 -0
  17. package/src/core/index.js +13 -0
  18. package/src/enums/EngineConstants.js +58 -0
  19. package/src/enums/LogLevel.js +13 -0
  20. package/src/enums/RenderMode.js +11 -0
  21. package/src/enums/SceneFormat.js +21 -0
  22. package/src/enums/SceneRevealMode.js +11 -0
  23. package/src/enums/SplatRenderMode.js +10 -0
  24. package/src/enums/index.js +13 -0
  25. package/src/flame/FlameAnimator.js +271 -0
  26. package/src/flame/FlameConstants.js +21 -0
  27. package/src/flame/FlameTextureManager.js +293 -0
  28. package/src/flame/index.js +22 -0
  29. package/src/flame/utils.js +50 -0
  30. package/src/index.js +39 -0
  31. package/src/loaders/DirectLoadError.js +14 -0
  32. package/src/loaders/INRIAV1PlyParser.js +223 -0
  33. package/src/loaders/PlyLoader.js +261 -0
  34. package/src/loaders/PlyParser.js +19 -0
  35. package/src/loaders/PlyParserUtils.js +311 -0
  36. package/src/loaders/index.js +13 -0
  37. package/src/materials/SplatMaterial.js +1065 -0
  38. package/src/materials/SplatMaterial2D.js +358 -0
  39. package/src/materials/SplatMaterial3D.js +278 -0
  40. package/src/materials/index.js +11 -0
  41. package/src/raycaster/Hit.js +37 -0
  42. package/src/raycaster/Ray.js +123 -0
  43. package/src/raycaster/Raycaster.js +175 -0
  44. package/src/raycaster/index.js +10 -0
  45. package/src/renderer/AnimationManager.js +574 -0
  46. package/src/renderer/AppConstants.js +101 -0
  47. package/src/renderer/GaussianSplatRenderer.js +695 -0
  48. package/src/renderer/index.js +24 -0
  49. package/src/utils/LoaderUtils.js +65 -0
  50. package/src/utils/Util.js +375 -0
  51. package/src/utils/index.js +9 -0
  52. package/src/worker/SortWorker.js +284 -0
  53. package/src/worker/index.js +8 -0
  54. package/dist/gsplat-flame-avatar-renderer.esm.min.js +0 -2
  55. package/dist/gsplat-flame-avatar-renderer.esm.min.js.map +0 -1
  56. package/dist/gsplat-flame-avatar-renderer.umd.js +0 -12876
  57. package/dist/gsplat-flame-avatar-renderer.umd.min.js +0 -2
  58. package/dist/gsplat-flame-avatar-renderer.umd.min.js.map +0 -1
  59. package/dist/gsplat-flame-avatar.esm.js +0 -12755
  60. package/dist/gsplat-flame-avatar.esm.js.map +0 -1
  61. package/dist/gsplat-flame-avatar.esm.min.js +0 -2
  62. package/dist/gsplat-flame-avatar.esm.min.js.map +0 -1
  63. package/dist/gsplat-flame-avatar.umd.js +0 -12876
  64. package/dist/gsplat-flame-avatar.umd.js.map +0 -1
  65. package/dist/gsplat-flame-avatar.umd.min.js +0 -2
  66. package/dist/gsplat-flame-avatar.umd.min.js.map +0 -1
@@ -1,2 +0,0 @@
1
- import*as e from"three";import{DataUtils as t,LoopOnce as s,LoopRepeat as i,Object3D as n,Vector3 as a,Quaternion as r,Matrix4 as o,BufferGeometry as l,BufferAttribute as c,InstancedBufferGeometry as h,InstancedBufferAttribute as d,DynamicDrawUsage as u,Vector2 as p,Color as A,ShaderMaterial as m,DoubleSide as g,NormalBlending as f,MeshBasicMaterial as S,Mesh as C,Box3 as x,Vector4 as y,DataTexture as v,RGBAIntegerFormat as I,UnsignedIntType as B,RGBAFormat as b,FloatType as T,RGFormat as w,UnsignedByteType as D,HalfFloatType as M,RedIntegerFormat as E,RedFormat as R,RGIntegerFormat as F,RGBIntegerFormat as P,Matrix3 as k,Scene as L,PerspectiveCamera as U,OrthographicCamera as H,MathUtils as _,WebGLRenderer as z,Skeleton as Q,Bone as O,Clock as N,AnimationMixer as V}from"three";import{GLTFLoader as W}from"three/examples/jsm/loaders/GLTFLoader.js";import G from"jszip";import{OrbitControls as q}from"three/examples/jsm/controls/OrbitControls.js";const K={None:0,Error:1,Warning:2,Info:3,Debug:4},j={Always:0,OnChange:1,Never:2},X={Ply:0},J=e=>e.endsWith(".ply")?X.Ply:null,Y={Default:0,Gradual:1,Instant:2},Z={ThreeD:0,TwoD:1};let $=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 ee=$.SphericalHarmonics8BitCompressionRange,te=6,se=4,ie=4,ne=4,ae=6,re=8,oe=4,le=4,ce=1,he=.012,de=.003,ue=50,pe=.5,Ae=60,me=15e5,ge=.4,fe=.12,Se={DirectToSplatBuffer:0,DirectToSplatArray:1,DownloadBeforeProcessing:2},Ce={Downloading:0,Processing:1,Done:2};class xe{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)}}class ye extends Error{constructor(e){super(e),this.name="AbortedPromiseError"}}const ve=function(e,t,s=!0,i){const n=new AbortController,a=n.signal;let r=!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:a};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 a=0,o=e.headers.get("Content-Length"),c=o?parseInt(o):void 0;const h=[];for(;!r;)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 r,o;a+=e.length,void 0!==c&&(r=a/c*100,o=`${r.toFixed(2)}%`),s&&h.push(e),l(r,o,e,c)}catch(e){return void n(e)}}).catch(e=>{"AbortError"===e.name?n(new ye("Fetch aborted")):n(new ye(e.message||e))})});return c.abort=e=>{r=!0,n.abort(e)},c.abortController=n,c},Ie=function(e,t,s){return Math.max(Math.min(e,s),t)},Be=function(){return performance.now()/1e3},be=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)be(t)},Te=(e,t)=>new Promise(s=>{window.setTimeout(()=>{s(e())},t?1:50)}),we=(e=0)=>{switch(e){case 1:return 9;case 2:return 24}return 0},De=()=>{let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}},Me=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 Ee{constructor(e,t,s){this.major=e,this.minor=t,this.patch=s}toString(){return`${this.major}_${this.minor}_${this.patch}`}}function Re(){const e=navigator.userAgent;return e.indexOf("iPhone")>0||e.indexOf("iPad")>0}function Fe(){if(Re()){const e=navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);return new Ee(parseInt(e[1]||0,10),parseInt(e[2]||0,10),parseInt(e[3]||0,10))}return null}const Pe=t.toHalfFloat.bind(t),ke=t.fromHalfFloat.bind(t),Le=ee/2,Ue=(e,s,i=!1,n,a)=>0===s?e:1===s||2===s&&!i?t.fromHalfFloat(e):2===s?_e(e,n,a):void 0,He=(e,t,s)=>{e=Ie(e,t,s);const i=s-t;return Ie(Math.floor((e-t)/i*255),0,255)},_e=(e,t,s)=>e/255*(s-t)+t,ze=(e,t,s)=>He(ke(e),t,s),Qe=(e,t,s)=>Pe(_e(e,t,s)),Oe=(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),Ne=function(){const e=e=>e;return function(t,s,i,n=!1){if(s===i)return t;let a=e;return 2===s&&n?1===i?a=Qe:0===i&&(a=_e):2===s||1===s?0===i?a=ke:2===i&&(a=n?ze:e):0===s&&(1===i?a=Pe:2===i&&(a=n?He:Pe)),a(t)}}(),Ve=(e,t,s,i,n=0)=>{const a=new Uint8Array(e,t),r=new Uint8Array(s,i);for(let e=0;e<n;e++)r[e]=a[e]},We=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,a=i>>12&2047;const r=i>>23&255;return r<103?n:r>142?(n|=31744,n|=(255==r?0:1)&&8388607&i,n):r<113?(a|=2048,n|=(a>>114-r)+(a>>113-r&1),n):(n|=r-112<<10|a>>1,n+=1&a,n)}}(),Ge=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),qe=function(e,t,s,i){return e+(t<<8)+(s<<16)+(i<<24)},Ke=function(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24)},je=14,Xe={Idle:"Idle",Listening:"Listening",Responding:"Responding",Thinking:"Thinking"},Je=["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"],Ye=["root","neck","jaw","leftEye","rightEye"],Ze=Je.length,$e=Ye.length;class et{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 tt extends et{constructor(e,t){super(e,t)}update(e){if(this.actions&&0!==this.actions.length&&(void 0===rt.CurPlaying&&e===Xe.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,rt.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=i,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==rt.LastAction&&rt.PrepareCrossFade(rt.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),rt.CurPlaying===Xe.Idle&&e===Xe.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,rt.SetWeight(this.actions[e],1),this.actions[e].loop=i,this.actions[e].play(),rt.PrepareCrossFade(this.actions[this.stage],this.actions[e],this.blendingTime),this.stage=e}}}class st extends et{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===rt.CurPlaying&&e===Xe.Idle&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,rt.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=i,this.actions[this.stage].clampWhenFinished=!1,this.actions[this.stage].paused=!1,this.actions[this.stage].play(),void 0!==rt.LastAction&&rt.PrepareCrossFade(rt.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),rt.CurPlaying===Xe.Idle&&e!==Xe.Idle&&!0===this.isPlaying&&0===this.stage&&(this.actions[this.stage].loop=s,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rt.LastAction=this.actions[this.stage]))}}class it extends et{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===rt.CurPlaying&&e===Xe.Listening&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),rt.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=this.isGroup?s:i,this.actions[this.stage].clampWhenFinished=!!this.isGroup,void 0!==rt.LastAction&&rt.PrepareCrossFade(rt.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(rt.CurPlaying===Xe.Listening&&e===Xe.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,rt.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=i,this.actions[this.stage+1].play(),rt.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),rt.CurPlaying!==Xe.Listening||e===Xe.Listening||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),rt.SetWeight(this.actions[2],1),this.actions[2].loop=s,rt.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),rt.CurPlaying===Xe.Listening&&e!==Xe.Listening&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=s,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rt.LastAction=this.actions[this.stage]))}}class nt extends et{constructor(e,t){super(e,t)}update(e){this.actions&&0!==this.actions.length&&(void 0===rt.CurPlaying&&e===Xe.Thinking&&!1===this.isPlaying&&(this.stage=0,this.actions[this.stage].time=0,this.actions[this.stage].play(),rt.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=s,void 0!==rt.LastAction&&rt.PrepareCrossFade(rt.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),this.isGroup&&(rt.CurPlaying===Xe.Thinking&&e===Xe.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,rt.SetWeight(this.actions[this.stage+1],1),this.actions[this.stage+1].loop=i,this.actions[this.stage+1].play(),rt.PrepareCrossFade(this.actions[this.stage],this.actions[this.stage+1],this.blendingTime),this.stage=1),rt.CurPlaying!==Xe.Thinking||e===Xe.Thinking||!0!==this.isPlaying||0!==this.stage&&1!==this.stage||(this.actions[2].time=0,this.actions[2].play(),rt.SetWeight(this.actions[2],1),this.actions[2].loop=s,rt.PrepareCrossFade(this.actions[this.stage],this.actions[2],this.blendingTime),this.stage=2)),rt.CurPlaying===Xe.Thinking&&e!==Xe.Thinking&&!0===this.isPlaying&&this.stage===(this.isGroup?this.actions.length-1:0)&&(this.actions[this.stage].loop=s,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rt.LastAction=this.actions[this.stage]))}}class at extends et{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===rt.CurPlaying&&e===Xe.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(),rt.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=s,this.actions[this.stage].clampWhenFinished=!0,void 0!==rt.LastAction&&rt.PrepareCrossFade(rt.LastAction,this.actions[this.stage],this.blendingTime),this.isPlaying=!0),rt.CurPlaying===Xe.Responding&&e===Xe.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(),rt.SetWeight(this.actions[this.stage],1),this.actions[this.stage].loop=s,this.actions[this.stage].clampWhenFinished=!0,rt.PrepareCrossFade(e,this.actions[this.stage],this.blendingTime)}rt.CurPlaying===Xe.Responding&&e!==Xe.Responding&&!0===this.isPlaying&&(this.actions[this.stage].loop=s,this.actions[this.stage].clampWhenFinished=!0,this.isPlaying=!1,rt.LastAction=this.actions[this.stage])}else this._warnedNoActions||(console.warn("[SPEAK] No actions available!"),this._warnedNoActions=!0)}}class rt{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;rt.UnPauseAllActions(),rt.ExecuteCrossFade(e,t,i),rt.IsBlending=!0,setTimeout(()=>{rt.IsBlending=!1},s+.1)}static PauseAllActions(){rt.actions.forEach(function(e){e.paused=!0})}static UnPauseAllActions(){rt.actions.forEach(function(e){e.paused=!1})}static ExecuteCrossFade(e,t,s){rt.SetWeight(t,1),t.time=0,e.crossFadeTo(t,s,!0)}constructor(e,t,s){const i=[],n=[],a=[],r=[],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&&a.push(e.clipAction(p.clone())),d===h&&r.push(e.clipAction(p.clone())),u===d&&o.push(e.clipAction(p.clone()))):s<h?a.push(A):s<d?r.push(A):s<u&&o.push(A),rt.actions.push(A),rt.SetWeight(A,0)}this.hello=new tt(i,s?.hello?.isGroup||!1),this.idle=new st(n,s?.idle?.isGroup||!1),this.listen=new it(a,s?.listen?.isGroup||!1),this.think=new nt(o,s?.think?.isGroup||!1),this.speak=new at(r,s?.speak?.isGroup||!1)}curPlaying(){return this.hello.isPlaying||this.idle.isPlaying?Xe.Idle:this.listen.isPlaying?Xe.Listening:this.think.isPlaying?Xe.Thinking:this.speak.isPlaying?Xe.Responding:void 0}dispose(){this.hello.dispose(),this.idle.dispose(),this.listen.dispose(),this.think.dispose(),this.speak.dispose(),rt.actions=[]}resetAllActions(e=!1){switch(this.curPlaying()){case Xe.Idle:rt.LastAction=this.hello.actions[this.hello.stage];break;case Xe.Listening:rt.LastAction=this.listen.actions[this.listen.stage];break;case Xe.Thinking:rt.LastAction=this.think.actions[this.think.stage];break;case Xe.Responding:rt.LastAction=this.speak.actions[this.speak.stage];break;default:rt.LastAction=void 0}rt.LastAction&&(rt.LastAction.loop=s,rt.LastAction.clampWhenFinished=!0,rt.SetWeight(rt.LastAction,1)),e&&(rt.PauseAllActions(),rt.actions.forEach(function(e){e.time=0,rt.SetWeight(e,0)}),rt.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(!rt.IsBlending)if(rt.CurPlaying=this.curPlaying(),void 0===rt.CurPlaying)switch(e){case Xe.Idle:this.idle.update(e);break;case Xe.Listening:this.listen.update(e);break;case Xe.Thinking:this.think.update(e);break;case Xe.Responding:this.speak.update(e);break;default:this.idle.update(e)}else switch(rt.CurPlaying){case Xe.Idle:this.idle.update(e);break;case Xe.Listening:this.listen.update(e);break;case Xe.Thinking:this.think.update(e);break;case Xe.Responding:this.speak.update(e);break;default:this.idle.update(e)}}}class ot extends n{constructor(e,t=new a,s=new r,i=new a(1,1,1),n=1,l=1,c=!0){super(),this.splatBuffer=e,this.position.copy(t),this.quaternion.copy(s),this.scale.copy(i),this.transform=new o,this.minimumAlpha=n,this.opacity=l,this.visible=c}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 lt{static build(e){const t=new l;t.setIndex([0,1,2,0,2,3]);const s=new Float32Array(12),i=new c(s,3);t.setAttribute("position",i),i.setXYZ(0,-1,-1,0),i.setXYZ(1,-1,1,0),i.setXYZ(2,1,1,0),i.setXYZ(3,1,-1,0),i.needsUpdate=!0;const n=(new h).copy(t),a=new Uint32Array(e),r=new d(a,1,!1);return r.setUsage(u),n.setAttribute("splatIndex",r),n.instanceCount=0,n}}class ct{constructor(){this.rootNode=null,this.splatMesh=null}static convertWorkerSubTree(e,t){const s=new ct;return s.rootNode=e.rootNode,s.splatMesh=t,s}}class ht{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,t=()=>!0,s,i)=>{this.splatTreeWorker||(this.splatTreeWorker=null),this.splatMesh=e,this.subTrees=[];const n=new a,r=(s,i)=>{const a=new Float32Array(4*i);let r=0;for(let o=0;o<i;o++){const i=o+s;if(t(i)){e.getSplatCenter(i,n);const t=4*r;a[t]=n.x,a[t+1]=n.y,a[t+2]=n.z,a[t+3]=i,r++}}return a};return new Promise(t=>{const n=()=>!!this.disposed&&(this.diposeSplatTreeWorker(),t(),!0);s&&s(!1),Te(()=>{if(n())return;const a=[];if(e.dynamicMode){let t=0;for(let s=0;s<e.scenes.length;s++){const i=e.getScene(s).splatBuffer.getSplatCount(),n=r(t,i);a.push(n),t+=i}}else{const t=r(0,e.getSplatCount());a.push(t)}this.splatTreeWorker.onmessage=s=>{n()||s.data.subTrees&&(i&&i(!1),Te(()=>{if(!n()){for(let t of s.data.subTrees){const s=ct.convertWorkerSubTree(t,e);this.subTrees.push(s)}this.diposeSplatTreeWorker(),i&&i(!0),Te(()=>{t()})}}))},Te(()=>{if(n())return;s&&s(!0);const e=a.map(e=>e.buffer);var t,i,r,o,l;t=this.splatTreeWorker,i=a,r=e,o=this.maxDepth,l=this.maxCentersPerNode,t&&t.postMessage({process:{centers:i,maxDepth:o,maxCentersPerNode:l}},r)})})})};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 dt{static buildVertexShaderBase(e=!1,t=!1,s=0,i="",n=!0){let a="";return a+=1==n?"#define USE_FLAME":"#define USE_SKINNING",a+="\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&&(a+=`\n uniform float sceneOpacity[${$.MaxScenes}];\n uniform int sceneVisibility[${$.MaxScenes}];\n `),e&&(a+=`\n uniform highp mat4 transforms[${$.MaxScenes}];\n `),a+=`\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[${$.MaxScenes}];\n uniform float sphericalHarmonics8BitCompressionRangeMax[${$.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&&(a+="\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 "),a+=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;",a+="\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&&(a+=" \n if (sphericalHarmonicsDegree >= 1) {\n ",a+=e?"\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(transform) * vec4(cameraPosition, 1.0)));\n ":"\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n ",a+="\n vec3 sh1;\n vec3 sh2;\n vec3 sh3;\n ",s>=2&&(a+="\n vec3 sh4;\n vec3 sh5;\n vec3 sh6;\n vec3 sh7;\n vec3 sh8;\n "),1===s?a+="\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&&(a+="\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 "),a+="\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&&(a+="\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&&(a+="\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 "),a+="\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 "),a+="\n\n vColor.rgb = clamp(vColor.rgb, vec3(0.), vec3(1.));\n\n }\n\n "),a}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,t=!1,s=0,i=1,n=!1){const r={sceneCenter:{type:"v3",value:new a},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 o},bindMatrixInverse:{type:"m4",value:new o},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 p},orthoZoom:{type:"f",value:1},inverseFocalAdjustment:{type:"f",value:1},viewport:{type:"v2",value:new p},basisViewport:{type:"v2",value:new p},debugColor:{type:"v3",value:new A},centersColorsTextureSize:{type:"v2",value:new p(1024,1024)},flameModelTextureSize:{type:"v2",value:new p(4096,2048)},boneTextureSize:{type:"v2",value:new p(4,32)},boneWeightTextureSize:{type:"v2",value:new p(512,512)},sphericalHarmonicsDegree:{type:"i",value:s},sphericalHarmonicsTextureSize:{type:"v2",value:new p(1024,1024)},sphericalHarmonics8BitMode:{type:"i",value:0},sphericalHarmonicsMultiTextureMode:{type:"i",value:0},splatScale:{type:"f",value:i},pointCloudModeEnabled:{type:"i",value:n?1:0},sceneIndexesTexture:{type:"t",value:null},sceneIndexesTextureSize:{type:"v2",value:new p(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<$.MaxScenes;e++)r.sphericalHarmonics8BitCompressionRangeMin.value.push(-$.SphericalHarmonics8BitCompressionRange/2),r.sphericalHarmonics8BitCompressionRangeMax.value.push($.SphericalHarmonics8BitCompressionRange/2);if(t){const e=[];for(let t=0;t<$.MaxScenes;t++)e.push(1);r.sceneOpacity={type:"f",value:e};const t=[];for(let e=0;e<$.MaxScenes;e++)t.push(1);r.sceneVisibility={type:"i",value:t}}if(e){const e=[];for(let t=0;t<$.MaxScenes;t++)e.push(new o);r.transforms={type:"mat4",value:e}}return r}}class ut{static build(e=!1,t=!1,s=!1,i=2048,n=1,a=!1,r=0,o=.3,l=!0){let c=dt.buildVertexShaderBase(e,t,r,"\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 ",l);c+=ut.buildVertexShaderProjection(s,t,i,o);const h=ut.buildFragmentShader(),d=dt.getUniforms(e,t,r,n,a);d.covariancesTextureSize={type:"v2",value:new p(1024,1024)},d.covariancesTexture={type:"t",value:null},d.covariancesTextureHalfFloat={type:"t",value:null},d.covariancesAreHalfFloat={type:"i",value:0};return new m({uniforms:d,vertexShader:c,fragmentShader:h,transparent:!0,alphaTest:1,blending:f,depthTest:!0,depthWrite:!1,side:g})}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+=dt.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 pt{static build(e=!1,t=!1,s=1,i=!1,n=0){let a=dt.buildVertexShaderBase(e,t,n,"\n uniform vec2 scaleRotationsTextureSize;\n uniform highp sampler2D scaleRotationsTexture;\n varying mat3 vT;\n varying vec2 vQuadCenter;\n varying vec2 vFragCoord;\n ");a+=pt.buildVertexShaderProjection();const r=pt.buildFragmentShader(),o=dt.getUniforms(e,t,n,s,i);o.scaleRotationsTexture={type:"t",value:null},o.scaleRotationsTextureSize={type:"v2",value:new p(1024,1024)};return new m({uniforms:o,vertexShader:a,fragmentShader:r,transparent:!0,alphaTest:1,blending:f,depthTest:!0,depthWrite:!1,side:g})}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+=dt.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 At=new l,mt=new S;function gt(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 ft(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 a="undefined"!=typeof WebGL2RenderingContext&&"WebGL2RenderingContext"===e.constructor.name;let r=void 0!==s.precision?s.precision:"highp";const o=n(r);o!==r&&(console.warn("THREE.WebGLRenderer:",r,"not supported, using",o,"instead."),r=o);const l=a||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=a||t.has("OES_texture_float");return{isWebGL2:a,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:r,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:a?e.getParameter(e.MAX_SAMPLES):0}}function St(e,t,s){const i=s.isWebGL2;return{convert:function(s,n){let a;if(s===D)return e.UNSIGNED_BYTE;if(1017===s)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===s)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===s)return e.BYTE;if(1011===s)return e.SHORT;if(1012===s)return e.UNSIGNED_SHORT;if(1013===s)return e.INT;if(1014===s)return e.UNSIGNED_INT;if(s===T)return e.FLOAT;if(s===M)return i?e.HALF_FLOAT:(a=t.get("OES_texture_half_float"),null!==a?a.HALF_FLOAT_OES:null);if(1021===s)return e.ALPHA;if(1022===s)return e.RGB;if(s===b)return e.RGBA;if(1024===s)return e.LUMINANCE;if(1025===s)return e.LUMINANCE_ALPHA;if(1026===s)return e.DEPTH_COMPONENT;if(1027===s)return e.DEPTH_STENCIL;if(s===R)return e.RED;if(s===E)return e.RED_INTEGER;if(s===w)return e.RG;if(s===F)return e.RG_INTEGER;if(s===P)return e.RGB_INTEGER;if(s===I)return e.RGBA_INTEGER;if(33776===s||33777===s||33778===s||33779===s){if(a=t.get("WEBGL_compressed_texture_s3tc"),null===a)return null;if(33776===s)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===s)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===s)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===s)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===s||35841===s||35842===s||35843===s){if(a=t.get("WEBGL_compressed_texture_pvrtc"),null===a)return null;if(35840===s)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===s)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===s)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===s)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===s)return a=t.get("WEBGL_compressed_texture_etc1"),null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null;if(s>=37808&&s<=37814||s>=37840&&s<=37846)return a=t.get("WEBGL_compressed_texture_astc"),null!==a?s:null;if(36492===s||36494===s||36495===s)return a=t.get("EXT_texture_compression_bptc"),null!==a?s:null;if(34042===s)return e.UNSIGNED_INT_24_8;if(i){if(6407===s)return e.RGB;if(6408===s)return e.RGBA}return void 0!==e[s]?e[s]:null}}}const Ct=16777216;class xt extends C{constructor(e=Z.ThreeD,t=!1,s=!1,i=!1,n=1,r=!0,o=!1,l=!1,c=1024,h=K.None,d=0,u=1,p=.3){super(At,mt),this.renderer=void 0,this.splatRenderMode=e,this.dynamicMode=t,this.enableOptionalEffects=s,this.halfPrecisionCovariancesOnGPU=i,this.devicePixelRatio=n,this.enableDistancesComputationOnGPU=r,this.integerBasedDistancesComputation=o,this.antialiased=l,this.kernel2DSize=p,this.maxScreenSpaceSplatSize=c,this.logLevel=h,this.sphericalHarmonicsDegree=d,this.minSphericalHarmonicsDegree=0,this.sceneFadeInRateMultiplier=u,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 x,this.calculatedSceneCenter=new a,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,t,s){const i=[];i.length=t.length;for(let n=0;n<t.length;n++){const o=t[n],l=s[n]||{};let c=l.position||[0,0,0],h=l.rotation||[0,0,0,1],d=l.scale||[1,1,1];const u=(new a).fromArray(c),p=(new r).fromArray(h),A=(new a).fromArray(d),m=xt.createScene(o,u,p,A,l.splatAlphaRemovalThreshold||1,l.opacity,l.visible);e.add(m),i[n]=m}return i}static createScene(e,t,s,i,n,a=1,r=!0){return new ot(e,t,s,i,n,a,r)}static buildSplatIndexMaps(e){const t=[],s=[];let i=0;for(let n=0;n<e.length;n++){const a=e[n].getMaxSplatCount();for(let e=0;e<a;e++)t[i]=e,s[i]=n,i++}return{localSplatIndexMap:t,sceneIndexMap:s}}buildSplatTree=(e=[],t,s)=>new Promise(i=>{this.disposeSplatTree(),this.baseSplatTree=new ht(8,1e3);const n=performance.now(),a=new y;this.baseSplatTree.processSplatMesh(this,t=>{this.getSplatColor(t,a);const s=this.getSceneIndexForSplat(t),i=e[s]||1;return a.w>=i},t,s).then(()=>{const e=performance.now()-n;if(this.logLevel>=K.Info&&console.log("SplatTree build: "+e+" ms"),this.disposed)i();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>=K.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()}`)),i()}})});build(e,t,s=!0,i=!1,n,a,r=!0){this.sceneOptions=t,this.finalBuild=i;const o=xt.getTotalMaxSplatCountForSplatBuffers(e),l=xt.buildScenes(this,e,t);if(s)for(let e=0;e<this.scenes.length&&e<l.length;e++){const t=l[e],s=this.getScene(e);t.copyTransformData(s)}this.scenes=l;let c=3;for(let t of e){const e=t.getMinSphericalHarmonicsDegree();e<c&&(c=e)}this.minSphericalHarmonicsDegree=Math.min(c,this.sphericalHarmonicsDegree);let h=!1;if(e.length!==this.lastBuildScenes.length)h=!0;else for(let t=0;t<e.length;t++){if(e[t]!==this.lastBuildScenes[t].splatBuffer){h=!0;break}}let d=!0;if((1!==this.scenes.length||this.lastBuildSceneCount!==this.scenes.length||this.lastBuildMaxSplatCount!==o||h)&&(d=!1),!d){this.boundingBox=new x,r||(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=lt.build(o),this.splatRenderMode===Z.ThreeD?this.material=ut.build(this.dynamicMode,this.enableOptionalEffects,this.antialiased,this.maxScreenSpaceSplatSize,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree,this.kernel2DSize,this.useFlameModel):this.material=pt.build(this.dynamicMode,this.enableOptionalEffects,this.splatScale,this.pointCloudModeEnabled,this.minSphericalHarmonicsDegree);const t=xt.buildSplatIndexMaps(e);this.globalSplatIndexToLocalSplatIndexMap=t.localSplatIndexMap,this.globalSplatIndexToSceneIndexMap=t.sceneIndexMap}const u=this.getSplatCount(!0);this.enableDistancesComputationOnGPU&&this.setupDistancesComputationTransformFeedback();const p=this.refreshGPUDataFromSplatBuffers(d);for(let e=0;e<this.scenes.length;e++)this.lastBuildScenes[e]=this.scenes[e];return this.lastBuildSplatCount=u,this.lastBuildMaxSplatCount=this.getMaxSplatCount(),this.lastBuildSceneCount=this.scenes.length,this.visible=this.scenes.length>0,p}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 x,this.calculatedSceneCenter=new a,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!==At&&(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(),t=this.getSplatCount(!0);this.disposeTextures();const s=(t,s)=>{const i=new p(4096,1024);for(;i.x*i.y*t<e*s;)i.y*=2;return i},i=e=>{const t=(e=>e>=1?6:4)(e);return{elementsPerTexelStored:t,texSize:s(t,6)}};let n=this.getTargetCovarianceCompressionLevel();const a=this.getTargetSphericalHarmonicsCompressionLevel();let r,o,l;if(this.splatRenderMode===Z.ThreeD){const t=i(n);t.texSize.x*t.texSize.y>Ct&&0===n&&(n=1),r=new Float32Array(6*e)}else o=new Float32Array(3*e),l=new Float32Array(4*e);const c=new Float32Array(3*e),h=new Uint8Array(4*e);let d=Float32Array;1===a?d=Uint16Array:2===a&&(d=Uint8Array);const u=we(this.minSphericalHarmonicsDegree),A=this.minSphericalHarmonicsDegree?new d(e*u):void 0,m=s(4,4),g=new Uint32Array(m.x*m.y*4);xt.updateCenterColorsPaddedData(0,t-1,c,h,g);const f=new v(g,m.x,m.y,I,B);if(f.internalFormat="RGBA32UI",f.needsUpdate=!0,this.material.uniforms.centersColorsTexture.value=f,this.material.uniforms.centersColorsTextureSize.value.copy(m),this.material.uniformsNeedUpdate=!0,this.splatDataTextures={baseData:{covariances:r,scales:o,rotations:l,centers:c,colors:h,sphericalHarmonics:A},centerColors:{data:g,texture:f,size:m}},this.splatRenderMode===Z.ThreeD){const e=i(n),t=e.elementsPerTexelStored,s=e.texSize;const a=n>=1?8:4,o=new(n>=1?Uint32Array:Float32Array)(s.x*s.y*a);let l;if(0===n?o.set(r):xt.updatePaddedCompressedCovariancesTextureData(r,o,0,0,r.length),n>=1)l=new v(o,s.x,s.y,I,B),l.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=l;else{l=new v(o,s.x,s.y,b,T),this.material.uniforms.covariancesTexture.value=l;const e=new v(new Uint32Array(32),2,2,I,B);e.internalFormat="RGBA32UI",this.material.uniforms.covariancesTextureHalfFloat.value=e,e.needsUpdate=!0}l.needsUpdate=!0,this.material.uniforms.covariancesAreHalfFloat.value=n>=1?1:0,this.material.uniforms.covariancesTextureSize.value.copy(s),this.splatDataTextures.covariances={data:o,texture:l,size:s,compressionLevel:n,elementsPerTexelStored:t,elementsPerTexelAllocated:a}}else{const e=s(4,6);let i=Float32Array,n=T;const a=new i(e.x*e.y*4);xt.updateScaleRotationsPaddedData(0,t-1,o,l,a);const r=new v(a,e.x,e.y,b,n);r.needsUpdate=!0,this.material.uniforms.scaleRotationsTexture.value=r,this.material.uniforms.scaleRotationsTextureSize.value.copy(e),this.splatDataTextures.scaleRotations={data:a,texture:r,size:e,compressionLevel:0}}if(A){const e=2===a?D:M;let i=u;i%2!=0&&i++;const n=2===this.minSphericalHarmonicsDegree?4:2,r=4===n?b:w;let o=s(n,i);if(o.x*o.y<=Ct){const s=new d(o.x*o.y*n);for(let e=0;e<t;e++){const t=u*e,n=i*e;for(let e=0;e<u;e++)s[n+e]=A[t+e]}const l=new v(s,o.x,o.y,r,e);l.needsUpdate=!0,this.material.uniforms.sphericalHarmonicsTexture.value=l,this.splatDataTextures.sphericalHarmonics={componentCount:u,paddedComponentCount:i,data:s,textureCount:1,texture:l,size:o,compressionLevel:a,elementsPerTexel:n}}else{const l=u/3;i=l,i%2!=0&&i++,o=s(n,i);const c=o.x*o.y*n,h=[this.material.uniforms.sphericalHarmonicsTextureR,this.material.uniforms.sphericalHarmonicsTextureG,this.material.uniforms.sphericalHarmonicsTextureB],p=[],m=[];for(let s=0;s<3;s++){const n=new d(c);p.push(n);for(let e=0;e<t;e++){const t=u*e,a=i*e;if(l>=3){for(let e=0;e<3;e++)n[a+e]=A[t+3*s+e];if(l>=8)for(let e=0;e<5;e++)n[a+3+e]=A[t+9+5*s+e]}}const a=new v(n,o.x,o.y,r,e);m.push(a),a.needsUpdate=!0,h[s].value=a}this.material.uniforms.sphericalHarmonicsMultiTextureMode.value=1,this.splatDataTextures.sphericalHarmonics={componentCount:u,componentCountPerChannel:l,paddedComponentCount:i,data:p,textureCount:3,textures:m,size:o,compressionLevel:a,elementsPerTexel:n}}this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(o),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 S=s(1,4),C=new Uint32Array(S.x*S.y*1);for(let e=0;e<t;e++)C[e]=this.globalSplatIndexToSceneIndexMap[e];const x=new v(C,S.x,S.y,E,B);x.internalFormat="R32UI",x.needsUpdate=!0,this.material.uniforms.sceneIndexesTexture.value=x,this.material.uniforms.sceneIndexesTextureSize.value.copy(S),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.sceneIndexes={data:C,texture:x,size:S},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 p(4,32);let t=new Float32Array(this.bonesMatrix),s=new Uint32Array(e.x*e.y*4);if(this.morphTargetDictionary=this.flameModel.morphTargetDictionary,this.useFlameModel){for(let e=0;e<16*this.bonesNum;e++)s[e]=Ge(t[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];s[this.morphTargetDictionary[e]+16*this.bonesNum]=Ge(t)}const i=new v(s,e.x,e.y,I,B);i.internalFormat="RGBA32UI",i.needsUpdate=!0,this.material.uniforms.boneTexture.value=i,this.material.uniforms.boneTextureSize.value.copy(e),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneMatrix={data:s,texture:i,size:e},this.splatDataTextures.baseData.boneMatrix=s}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]=Ge(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]=Ge(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 t=e.geometry.attributes.position.array.length/3;const s=new p(512,512);let i=new Float32Array(s.x*s.y*4),n=new Uint32Array(s.x*s.y*4);for(let e=0;e<t;e++)i[8*e+0]=this.bonesWeight[e][0],i[8*e+1]=this.bonesWeight[e][1],i[8*e+2]=this.bonesWeight[e][2],i[8*e+3]=this.bonesWeight[e][3],i[8*e+4]=this.bonesWeight[e][4],n[8*e+0]=Ge(this.bonesWeight[e][0]),n[8*e+1]=Ge(this.bonesWeight[e][1]),n[8*e+2]=Ge(this.bonesWeight[e][2]),n[8*e+3]=Ge(this.bonesWeight[e][3]),n[8*e+4]=Ge(this.bonesWeight[e][4]);const a=new v(n,s.x,s.y,I,B);a.internalFormat="RGBA32UI",a.needsUpdate=!0,this.material.uniforms.boneWeightTexture.value=a,this.material.uniforms.boneWeightTextureSize.value.copy(s),this.material.uniformsNeedUpdate=!0,this.splatDataTextures.boneWeight={data:n,texture:a,size:s},this.splatDataTextures.baseData.boneWeight=n}buildModelTexture(e){const t=new p(4096,2048);var s=e.geometry.attributes.position.array,i=[];let n=s.length/3,a=e.geometry.morphAttributes.position.length;Object.keys(e.morphTargetDictionary).forEach((t,s)=>{const n=e.morphTargetDictionary[t];var a=e.geometry.morphAttributes.position[n];i=i.concat(Array.from(a.array))}),i=i.concat(Array.from(s));let r=new Float32Array(t.x*t.y*4),o=new Uint32Array(t.x*t.y*4);for(let e=0;e<n*(a+1);e++)r[4*e+0]=i[3*e+0],r[4*e+1]=i[3*e+1],r[4*e+2]=i[3*e+2],o[4*e+0]=Ge(r[4*e+0]),o[4*e+1]=Ge(r[4*e+1]),o[4*e+2]=Ge(r[4*e+2]);const l=new v(o,t.x,t.y,I,B);l.internalFormat="RGBA32UI",l.needsUpdate=!0,this.material.uniforms.flameModelTexture.value=l,this.material.uniforms.flameModelTextureSize.value.copy(t),this.material.uniformsNeedUpdate=!0,this.material.uniforms.gaussianSplatCount.value=this.gaussianSplatCount,this.splatDataTextures.flameModel={data:o,texture:l,size:t},this.splatDataTextures.baseData.flameModelPos=r}updateTetureAfterBSAndSkeleton(e,t,s=!0){const i=new o;this.getSceneTransform(0,i),this.getScene(0).splatBuffer.fillSplatCenterArray(this.morphedMesh,this.splatDataTextures.baseData.centers,i,e,t,0);const n=this.splatDataTextures.centerColors,a=n.data,r=n.texture;xt.updateCenterColorsPaddedData(e,t,this.splatDataTextures.baseData.centers,this.splatDataTextures.baseData.colors,a);const l=this.renderer?this.renderer.properties.get(r):null;l&&l.__webglTexture?this.updateDataTexture(a,n.texture,n.size,l,4,4,4,e,t):r.needsUpdate=!0,this.updateBoneMatrixTexture(s)}updateBaseDataFromSplatBuffers(e,t){const s=this.splatDataTextures.covariances,i=s?s.compressionLevel:void 0,n=this.splatDataTextures.scaleRotations,a=n?n.compressionLevel:void 0,r=this.splatDataTextures.sphericalHarmonics,o=r?r.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,a,o,e,t,e)}updateDataTexturesFromBaseData(e,t){const s=this.splatDataTextures.covariances,i=s?s.compressionLevel:void 0,n=this.splatDataTextures.scaleRotations,a=n?n.compressionLevel:void 0,r=this.splatDataTextures.sphericalHarmonics,o=r?r.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;xt.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,a=6*e,r=6*t;if(0===i)for(let e=a;e<=r;e++){const t=this.splatDataTextures.baseData.covariances[e];s.data[e]=t}else xt.updatePaddedCompressedCovariancesTextureData(this.splatDataTextures.baseData.covariances,s.data,e*s.elementsPerTexelAllocated,a,r);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,r=6,o=0===a?4:2;xt.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,r,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,a,r,o)=>{const l=this.renderer?this.renderer.properties.get(i):null;l&&l.__webglTexture?this.updateDataTexture(r,i,n,l,a,o,s,e,t):i.needsUpdate=!0},n=r.componentCount,a=r.paddedComponentCount;if(1===r.textureCount){const s=r.data;for(let i=e;i<=t;i++){const e=n*i,t=a*i;for(let i=0;i<n;i++)s[t+i]=g[e+i]}i(r.texture,r.size,r.elementsPerTexel,s,a)}else{const s=r.componentCountPerChannel;for(let o=0;o<3;o++){const l=r.data[o];for(let i=e;i<=t;i++){const e=n*i,t=a*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(r.textures[o],r.size,r.elementsPerTexel,l,a)}}}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 a=n/i,r=e*a,o=Math.floor(r/s),l=o*s*i,c=t*a,h=Math.floor(c/s);return{dataStart:l,dataEnd:h*s*i+s*i,startRow:o,endRow:h}}updateDataTexture(e,t,s,i,n,a,r,o,l){const c=this.renderer.getContext(),h=xt.computeTextureUpdateRegion(o,l,s.x,n,a),d=h.dataEnd-h.dataStart,u=new e.constructor(e.buffer,h.dataStart*r,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 a=new DataView(t.buffer),r=s,o=0;for(let t=i;t<=n;t+=2)a.setUint16(2*r,e[t],!0),a.setUint16(2*r+2,e[t+1],!0),r+=2,o++,o>=3&&(r+=2,o=0)}static updateCenterColorsPaddedData(e,t,s,i,n){for(let a=e;a<=t;a++){const e=4*a,t=3*a,r=4*a;n[r]=Ke(i,e),n[r+1]=Ge(s[t]),n[r+2]=Ge(s[t+1]),n[r+3]=Ge(s[t+2])}}static updateScaleRotationsPaddedData(e,t,s,i,n){for(let a=e;a<=t;a++){const e=3*a,t=4*a,r=6*a;n[r]=s[e],n[r+1]=s[e+1],n[r+2]=s[e+2],n[r+3]=i[t],n[r+4]=i[t+1],n[r+5]=i[t+2]}}updateVisibleRegion(e){const t=this.getSplatCount(!0),s=new a;if(!e){const e=new a;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 i=e?this.lastBuildSplatCount:0;i<t;i++){this.getSplatCenter(this.morphedMesh,i,s,!0);const e=s.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=Y.Default){const t=.012*this.sceneFadeInRateMultiplier,s=.003*this.sceneFadeInRateMultiplier,i=this.finalBuild?t:s,n=e===Y.Default?i:s;this.visibleRegionFadeStartRadius=(this.visibleRegionRadius-this.visibleRegionFadeStartRadius)*n+this.visibleRegionFadeStartRadius;const a=(this.visibleRegionBufferRadius>0?this.visibleRegionFadeStartRadius/this.visibleRegionBufferRadius:0)>.99,r=a||e===Y.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=r,this.material.uniformsNeedUpdate=!0,this.visibleRegionChanging=!a}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 p;return function(t,s,i,n,a,r){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=a,this.material.uniforms.inverseFocalAdjustment.value=r,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]=Ie(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?xt.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 xt.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 gt(t),i=new ft(t,s,{});if(s.init(i),this.webGLUtils=new St(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(),a=(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 r;this.integerBasedDistancesComputation?(r="#version 300 es\n in ivec4 center;\n flat out int distance;",this.dynamicMode?r+=`\n in uint sceneIndex;\n uniform ivec4 transforms[${$.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 `:r+="\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n "):(r="#version 300 es\n in vec4 center;\n flat out float distance;",this.dynamicMode?r+=`\n in uint sceneIndex;\n uniform mat4 transforms[${$.MaxScenes}];\n void main(void) {\n vec4 transformedCenter = transforms[sceneIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n `:r+="\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=a(n,n.VERTEX_SHADER,r),s=a(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 a=this.integerBasedDistancesComputation?Uint32Array:Float32Array,r=16*s;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.centersBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,r,t);else{const e=new a(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 a=4*s;if(i.bindBuffer(i.ARRAY_BUFFER,this.distancesTransformFeedback.sceneIndexesBuffer),e)i.bufferSubData(i.ARRAY_BUFFER,a,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 o;return(t,s)=>{if(!this.renderer)return;const i=this.renderer.getContext(),n=i.getParameter(i.VERTEX_ARRAY_BINDING),a=i.getParameter(i.CURRENT_PROGRAM),r=!!a&&i.getProgramParameter(a,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=xt.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=xt.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,a=0;switch(i.clientWaitSync(o,a,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 a&&!0!==r&&i.useProgram(a),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,t,s,i,n,r,l,c,h=0,d=0,u=1,p,A,m=0,g){const f=new a;f.x=void 0,f.y=void 0,this.splatRenderMode===Z.ThreeD?f.z=void 0:f.z=1;const S=new o;let C=0,x=this.scenes.length-1;null!=g&&g>=0&&g<=this.scenes.length&&(C=g,x=g);for(let a=C;a<=x;a++){null==c&&(c=!this.dynamicMode);const o=this.getScene(a),l=o.splatBuffer;let g;if(c&&(this.getSceneTransform(a,S),g=S),e&&l.fillSplatCovarianceArray(e,g,p,A,m,h),t||s){if(!t||!s)throw new Error('SplatMesh::fillSplatDataArrays() -> "scales" and "rotations" must both be valid.');l.fillSplatScaleRotationArray(t,s,g,p,A,m,d,f)}i&&l.fillSplatCenterArray(this.morphedMesh,i,g,p,A,m),n&&l.fillSplatColorArray(n,o.minimumAlpha,p,A,m),r&&l.fillSphericalHarmonicsArray(r,this.minSphericalHarmonicsDegree,g,p,A,m,u),m+=l.getSplatCount()}}morphedMesh;getIntegerCenters(e,t,s=!1){const i=t-e+1,n=new Float32Array(3*i);let a;this.fillSplatDataArrays(null,null,null,n,null,null,void 0,void 0,void 0,void 0,e);let r=s?4:3;a=new Int32Array(i*r);for(let e=0;e<i;e++){for(let t=0;t<3;t++)a[e*r+t]=Math.round(1e3*n[3*e+t]);s&&(a[e*r+3]=1e3)}return a}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 a=new Float32Array(4*i);for(let e=0;e<i;e++){for(let t=0;t<3;t++)a[4*e+t]=n[3*e+t];a[4*e+3]=1}return a}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={},t=new a;return function(s,i,n,a){this.getLocalSplatParameters(s,e,a),t.x=void 0,t.y=void 0,t.z=void 0,this.splatRenderMode===Z.TwoD&&(t.z=0),e.splatBuffer.getSplatScaleAndRotation(e.localIndex,i,n,e.sceneTransform,t)}}();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,t){let s=this.getSplatCount();if(null!=t){if(t<0||t>=this.scenes.length)throw new Error("SplatMesh::computeBoundingBox() -> Invalid scene index.");s=this.scenes[t].splatBuffer.getSplatCount()}const i=new Float32Array(3*s);this.fillSplatDataArrays(null,null,null,i,null,null,e,void 0,void 0,void 0,void 0,t);const n=new a,r=new a;for(let e=0;e<s;e++){const t=3*e,s=i[t],a=i[t+1],o=i[t+2];(0===e||s<n.x)&&(n.x=s),(0===e||a<n.y)&&(n.y=a),(0===e||o<n.z)&&(n.z=o),(0===e||s>r.x)&&(r.x=s),(0===e||a>r.y)&&(r.y=a),(0===e||o>r.z)&&(r.z=o)}return new x(n,r)}}class yt extends Error{constructor(e){super(e),this.name="DirectLoadError"}}class vt{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=we(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=we(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=vt.createSplat(this.sphericalHarmonicsDegree);return this.addSplat(e),e}addSplatFromComonents(e,t,s,i,n,a,r,o,l,c,h,d,u,p,...A){const m=[e,t,s,i,n,a,r,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=vt.createSplat(this.sphericalHarmonicsDegree);for(let e=0;e<this.componentCount&&e<s.length;e++)i[e]=s[e];this.addSplat(i)}}const It=(e,t,s,i,n=0)=>{const a=new Uint8Array(e,t),r=new Uint8Array(s,i);for(let e=0;e<n;e++)r[e]=a[e]},Bt=t.toHalfFloat.bind(t),bt=t.fromHalfFloat.bind(t),Tt=(e,s,i=!1,n,a)=>0===s?e:1===s||2===s&&!i?t.fromHalfFloat(e):2===s?Dt(e,n,a):void 0,wt=(e,t,s)=>{e=Ie(e,t,s);const i=s-t;return Ie(Math.floor((e-t)/i*255),0,255)},Dt=(e,t,s)=>e/255*(s-t)+t,Mt=(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 Et{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 a=0;for(;n<e.splatCount;){let i=e.partiallyFilledBucketLengths[a];if(t>=n&&t<n+i)break;n+=i,s++,a++}}return s}getSplatCenter(e,t,s,i){const n=this.globalSplatIndexToSectionMap[t],a=this.sections[n],r=t-a.splatCountOffset,o=a.bytesPerSplat*r,l=new DataView(this.bufferData,a.dataBase+o),c=Mt(l,0,this.compressionLevel),h=Mt(l,1,this.compressionLevel),d=Mt(l,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(a,r)*Et.BucketStorageSizeFloats,t=a.compressionScaleFactor,i=a.compressionScaleRange;s.x=(c-i)*t+a.bucketArray[e],s.y=(h-i)*t+a.bucketArray[e+1],s.z=(d-i)*t+a.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 o,t=new o,s=new o,i=new a,n=new a,l=new r;return function(a,r,o,c,h){const d=this.globalSplatIndexToSectionMap[a],u=this.sections[d],p=a-u.splatCountOffset,A=u.bytesPerSplat*p+Et.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,m=new DataView(this.bufferData,u.dataBase+A);n.set(Tt(Mt(m,0,this.compressionLevel),this.compressionLevel),Tt(Mt(m,1,this.compressionLevel),this.compressionLevel),Tt(Mt(m,2,this.compressionLevel),this.compressionLevel)),h&&(void 0!==h.x&&(n.x=h.x),void 0!==h.y&&(n.y=h.y),void 0!==h.z&&(n.z=h.z)),l.set(Tt(Mt(m,4,this.compressionLevel),this.compressionLevel),Tt(Mt(m,5,this.compressionLevel),this.compressionLevel),Tt(Mt(m,6,this.compressionLevel),this.compressionLevel),Tt(Mt(m,3,this.compressionLevel),this.compressionLevel)),c?(e.makeScale(n.x,n.y,n.z),t.makeRotationFromQuaternion(l),s.copy(e).multiply(t).multiply(c),s.decompose(i,o,r)):(r.copy(n),o.copy(l))}}();getSplatColor(e,t){const s=this.globalSplatIndexToSectionMap[e],i=this.sections[s],n=e-i.splatCountOffset,a=i.bytesPerSplat*n+Et.CompressionLevels[this.compressionLevel].ColorOffsetBytes,r=new Uint8Array(this.bufferData,i.dataBase+a,4);t.set(r[0],r[1],r[2],r[3])}fillSplatCenterArray(e,t,s,i,n,r){const o=this.splatCount;i=i||0,n=n||o-1,void 0===r&&(r=i);const l=new a;for(let a=i;a<=n;a++){const n=this.globalSplatIndexToSectionMap[a],o=this.sections[n],c=a-o.splatCountOffset,h=(a-i+r)*Et.CenterComponentCount,d=o.bytesPerSplat*c,u=new DataView(this.bufferData,o.dataBase+d),p=Mt(u,0,this.compressionLevel),A=Mt(u,1,this.compressionLevel),m=Mt(u,2,this.compressionLevel);if(this.compressionLevel>=1){const e=this.getBucketIndex(o,c)*Et.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;s&&l.applyMatrix4(s),t[h]=l.x+e[3*a+0],t[h+1]=l.y+e[3*a+1],t[h+2]=l.z+e[3*a+2]}}fillSplatScaleRotationArray=function(){const e=new o,t=new o,s=new o,i=new a,n=new r,l=new a,c=e=>{const t=e.w<0?-1:1;e.x*=t,e.y*=t,e.z*=t,e.w*=t};return function(a,r,o,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)=>Ne(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+Et.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,C=(p-h+u)*Et.ScaleComponentCount,x=(p-h+u)*Et.RotationComponentCount,y=new DataView(this.bufferData,m.dataBase+S),v=A&&void 0!==A.x?A.x:Mt(y,0,this.compressionLevel),I=A&&void 0!==A.y?A.y:Mt(y,1,this.compressionLevel),B=A&&void 0!==A.z?A.z:Mt(y,2,this.compressionLevel),b=Mt(y,3,this.compressionLevel),T=Mt(y,4,this.compressionLevel),w=Mt(y,5,this.compressionLevel),D=Mt(y,6,this.compressionLevel);i.set(Tt(v,this.compressionLevel),Tt(I,this.compressionLevel),Tt(B,this.compressionLevel)),n.set(Tt(T,this.compressionLevel),Tt(w,this.compressionLevel),Tt(D,this.compressionLevel),Tt(b,this.compressionLevel)).normalize(),o&&(l.set(0,0,0),e.makeScale(i.x,i.y,i.z),t.makeRotationFromQuaternion(n),s.identity().premultiply(e).premultiply(t),s.premultiply(o),s.decompose(l,n,i),n.normalize()),c(n),a&&(a[C]=g(i.x,0),a[C+1]=g(i.y,0),a[C+2]=g(i.z,0)),r&&(r[x]=g(n.x,0),r[x+1]=g(n.y,0),r[x+2]=g(n.z,0),r[x+3]=g(n.w,0))}}}();static computeCovariance=function(){const e=new o,t=new k,s=new k,i=new k,n=new k,a=new k,r=new k;return function(o,l,c,h,d=0,u){e.makeScale(o.x,o.y,o.z),t.setFromMatrix4(e),e.makeRotationFromQuaternion(l),s.setFromMatrix4(e),i.copy(s).multiply(t),n.copy(i).transpose().premultiply(i),c&&(a.setFromMatrix4(c),r.copy(a).transpose(),n.multiply(r),n.premultiply(a)),u>=1?(h[d]=Bt(n.elements[0]),h[d+1]=Bt(n.elements[3]),h[d+2]=Bt(n.elements[6]),h[d+3]=Bt(n.elements[4]),h[d+4]=Bt(n.elements[7]),h[d+5]=Bt(n.elements[8])):(h[d]=n.elements[0],h[d+1]=n.elements[3],h[d+2]=n.elements[6],h[d+3]=n.elements[4],h[d+4]=n.elements[7],h[d+5]=n.elements[8])}}();fillSplatCovarianceArray(e,t,s,i,n,o){const l=this.splatCount,c=new a,h=new r;s=s||0,i=i||l-1,void 0===n&&(n=s);for(let a=s;a<=i;a++){const i=this.globalSplatIndexToSectionMap[a],r=this.sections[i],l=a-r.splatCountOffset,d=(a-s+n)*Et.CovarianceComponentCount,u=r.bytesPerSplat*l+Et.CompressionLevels[this.compressionLevel].ScaleOffsetBytes,p=new DataView(this.bufferData,r.dataBase+u);c.set(Tt(Mt(p,0,this.compressionLevel),this.compressionLevel),Tt(Mt(p,1,this.compressionLevel),this.compressionLevel),Tt(Mt(p,2,this.compressionLevel),this.compressionLevel)),h.set(Tt(Mt(p,4,this.compressionLevel),this.compressionLevel),Tt(Mt(p,5,this.compressionLevel),this.compressionLevel),Tt(Mt(p,6,this.compressionLevel),this.compressionLevel),Tt(Mt(p,3,this.compressionLevel),this.compressionLevel)),Et.computeCovariance(c,h,t,e,d,o)}}fillSplatColorArray(e,t,s,i,n){const a=this.splatCount;s=s||0,i=i||a-1,void 0===n&&(n=s);for(let a=s;a<=i;a++){const i=this.globalSplatIndexToSectionMap[a],r=this.sections[i],o=a-r.splatCountOffset,l=(a-s+n)*Et.ColorComponentCount,c=r.bytesPerSplat*o+Et.CompressionLevels[this.compressionLevel].ColorOffsetBytes,h=new Uint8Array(this.bufferData,r.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 a;const e=new k,t=new o,s=new a,i=new a,n=new r,l=[],c=[],h=[],d=[],u=[],p=[],A=[],m=[],g=[],f=[],S=[],C=[],x=[],y=[],v=[],I=[],B=[],b=[],T=e=>e,w=(e,t,s,i)=>{e[0]=t,e[1]=s,e[2]=i},D=(e,t,s,i,n)=>{e[0]=Mt(t,i,n,!0),e[1]=Mt(t,i+s,n,!0),e[2]=Mt(t,i+s+s,n,!0)},M=(e,t)=>{t[0]=e[0],t[1]=e[1],t[2]=e[2]},E=(e,t,s,i)=>{t[s]=i(e[0]),t[s+1]=i(e[1]),t[s+2]=i(e[2])},R=(e,t,s,i,n)=>(t[0]=Tt(e[0],s,!0,i,n),t[1]=Tt(e[1],s,!0,i,n),t[2]=Tt(e[2],s,!0,i,n),t);return function(a,r,o,F,P,k,L){const U=this.splatCount;F=F||0,P=P||U-1,void 0===k&&(k=F),o&&r>=1&&(t.copy(o),t.decompose(s,n,i),n.normalize(),t.makeRotationFromQuaternion(n),e.setFromMatrix4(t),w(l,e.elements[4],-e.elements[7],e.elements[1]),w(c,-e.elements[5],e.elements[8],-e.elements[2]),w(h,e.elements[3],-e.elements[6],e.elements[0]));const H=e=>((e,t,s)=>wt(bt(e),t,s))(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff),_=e=>wt(e,this.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff);for(let e=F;e<=P;e++){const t=this.globalSplatIndexToSectionMap[e],s=this.sections[t];r=Math.min(r,s.sphericalHarmonicsDegree);const i=we(r),n=e-s.splatCountOffset,w=s.bytesPerSplat*n+Et.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes,P=new DataView(this.bufferData,s.dataBase+w),U=(e-F+k)*i;let z=o?0:this.compressionLevel,Q=T;z!==L&&(1===z?0===L?Q=bt:2==L&&(Q=H):0===z&&(1===L?Q=Bt:2==L&&(Q=_)));const O=this.minSphericalHarmonicsCoeff,N=this.maxSphericalHarmonicsCoeff;r>=1&&(D(g,P,3,0,this.compressionLevel),D(f,P,3,1,this.compressionLevel),D(S,P,3,2,this.compressionLevel),o?(R(g,g,this.compressionLevel,O,N),R(f,f,this.compressionLevel,O,N),R(S,S,this.compressionLevel,O,N),Et.rotateSphericalHarmonics3(g,f,S,l,c,h,y,v,I)):(M(g,y),M(f,v),M(S,I)),E(y,a,U,Q),E(v,a,U+3,Q),E(I,a,U+6,Q),r>=2&&(D(g,P,5,9,this.compressionLevel),D(f,P,5,10,this.compressionLevel),D(S,P,5,11,this.compressionLevel),D(C,P,5,12,this.compressionLevel),D(x,P,5,13,this.compressionLevel),o?(R(g,g,this.compressionLevel,O,N),R(f,f,this.compressionLevel,O,N),R(S,S,this.compressionLevel,O,N),R(C,C,this.compressionLevel,O,N),R(x,x,this.compressionLevel,O,N),Et.rotateSphericalHarmonics5(g,f,S,C,x,l,c,h,d,u,p,A,m,y,v,I,B,b)):(M(g,y),M(f,v),M(S,I),M(C,B),M(x,b)),E(y,a,U+9,Q),E(v,a,U+12,Q),E(I,a,U+15,Q),E(B,a,U+18,Q),E(b,a,U+21,Q)))}}}();static dot3=(e,t,s,i,n)=>{n[0]=n[1]=n[2]=0;const a=i[0],r=i[1],o=i[2];Et.addInto3(e[0]*a,e[1]*a,e[2]*a,n),Et.addInto3(t[0]*r,t[1]*r,t[2]*r,n),Et.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,a,r)=>{r[0]=r[1]=r[2]=0;const o=a[0],l=a[1],c=a[2],h=a[3],d=a[4];Et.addInto3(e[0]*o,e[1]*o,e[2]*o,r),Et.addInto3(t[0]*l,t[1]*l,t[2]*l,r),Et.addInto3(s[0]*c,s[1]*c,s[2]*c,r),Et.addInto3(i[0]*h,i[1]*h,i[2]*h,r),Et.addInto3(n[0]*d,n[1]*d,n[2]*d,r)};static rotateSphericalHarmonics3=(e,t,s,i,n,a,r,o,l)=>{Et.dot3(e,t,s,i,r),Et.dot3(e,t,s,n,o),Et.dot3(e,t,s,a,l)};static rotateSphericalHarmonics5=(e,t,s,i,n,a,r,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]*a[0]+o[0]*a[2]+(a[2]*o[0]+a[0]*o[2])),l[1]=o[1]*a[0]+a[1]*o[0],l[2]=C*(o[1]*a[1]+a[1]*o[1]),l[3]=o[1]*a[2]+a[1]*o[2],l[4]=S*(o[2]*a[2]-o[0]*a[0]+(a[2]*o[2]-a[0]*o[0])),Et.dot5(e,t,s,i,n,l,p),c[0]=S*(r[2]*a[0]+r[0]*a[2]+(a[2]*r[0]+a[0]*r[2])),c[1]=r[1]*a[0]+a[1]*r[0],c[2]=C*(r[1]*a[1]+a[1]*r[1]),c[3]=r[1]*a[2]+a[1]*r[2],c[4]=S*(r[2]*a[2]-r[0]*a[0]+(a[2]*r[2]-a[0]*r[0])),Et.dot5(e,t,s,i,n,c,A),h[0]=x*(r[2]*r[0]+r[0]*r[2])+-v*(o[2]*o[0]+o[0]*o[2]+(a[2]*a[0]+a[0]*a[2])),h[1]=y*r[1]*r[0]+-x*(o[1]*o[0]+a[1]*a[0]),h[2]=r[1]*r[1]+-S*(o[1]*o[1]+a[1]*a[1]),h[3]=y*r[1]*r[2]+-x*(o[1]*o[2]+a[1]*a[2]),h[4]=x*(r[2]*r[2]-r[0]*r[0])+-v*(o[2]*o[2]-o[0]*o[0]+(a[2]*a[2]-a[0]*a[0])),Et.dot5(e,t,s,i,n,h,m),d[0]=S*(r[2]*o[0]+r[0]*o[2]+(o[2]*r[0]+o[0]*r[2])),d[1]=r[1]*o[0]+o[1]*r[0],d[2]=C*(r[1]*o[1]+o[1]*r[1]),d[3]=r[1]*o[2]+o[1]*r[2],d[4]=S*(r[2]*o[2]-r[0]*o[0]+(o[2]*r[2]-o[0]*r[0])),Et.dot5(e,t,s,i,n,d,g),u[0]=S*(o[2]*o[0]+o[0]*o[2]-(a[2]*a[0]+a[0]*a[2])),u[1]=o[1]*o[0]-a[1]*a[0],u[2]=C*(o[1]*o[1]-a[1]*a[1]),u[3]=o[1]*o[2]-a[1]*a[2],u[4]=S*(o[2]*o[2]-o[0]*o[0]-(a[2]*a[2]-a[0]*a[0])),Et.dot5(e,t,s,i,n,u,f)};static parseHeader(e){const t=new Uint8Array(e,0,Et.HeaderSizeBytes),s=new Uint16Array(e,0,Et.HeaderSizeBytes/2),i=new Uint32Array(e,0,Et.HeaderSizeBytes/4),n=new Float32Array(e,0,Et.HeaderSizeBytes/4);return{versionMajor:t[0],versionMinor:t[1],maxSectionCount:i[1],sectionCount:i[2],maxSplatCount:i[3],splatCount:i[4],compressionLevel:s[10],sceneCenter:new a(n[6],n[7],n[8]),minSphericalHarmonicsCoeff:n[9]||-Le,maxSphericalHarmonicsCoeff:n[10]||Le}}static writeHeaderCountsToBuffer(e,t,s){const i=new Uint32Array(s,0,Et.HeaderSizeBytes/4);i[2]=e,i[4]=t}static writeHeaderToBuffer(e,t){const s=new Uint8Array(t,0,Et.HeaderSizeBytes),i=new Uint16Array(t,0,Et.HeaderSizeBytes/2),n=new Uint32Array(t,0,Et.HeaderSizeBytes/4),a=new Float32Array(t,0,Et.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,a[6]=e.sceneCenter.x,a[7]=e.sceneCenter.y,a[8]=e.sceneCenter.z,a[9]=e.minSphericalHarmonicsCoeff||-Le,a[10]=e.maxSphericalHarmonicsCoeff||Le}static parseSectionHeaders(e,t,s=0,i){const n=e.compressionLevel,a=e.maxSectionCount,r=new Uint16Array(t,s,a*Et.SectionHeaderSizeBytes/2),o=new Uint32Array(t,s,a*Et.SectionHeaderSizeBytes/4),l=new Float32Array(t,s,a*Et.SectionHeaderSizeBytes/4),c=[];let h=0,d=h/2,u=h/4,p=Et.HeaderSizeBytes+e.maxSectionCount*Et.SectionHeaderSizeBytes,A=0;for(let e=0;e<a;e++){const t=o[u+1],s=o[u+2],a=o[u+3],m=l[u+4],g=m/2,f=r[d+10],S=o[u+6]||Et.CompressionLevels[n].ScaleRange,C=o[u+8],x=o[u+9],y=4*x,v=f*a+y,I=r[d+20],{bytesPerSplat:B}=Et.calculateComponentStorage(n,I),b=B*t,T=b+v,w={bytesPerSplat:B,splatCountOffset:A,splatCount:i?t:0,maxSplatCount:t,bucketSize:s,bucketCount:a,bucketBlockSize:m,halfBucketBlockSize:g,bucketStorageSizeBytes:f,bucketsStorageSizeBytes:v,splatDataStorageSizeBytes:b,storageSizeBytes:T,compressionScaleRange:S,compressionScaleFactor:g/S,base:p,bucketsBase:p+y,dataBase:p+v,fullBucketCount:C,partiallyFilledBucketCount:x,sphericalHarmonicsDegree:I};c[e]=w,p+=T,h+=Et.SectionHeaderSizeBytes,d=h/2,u=h/4,A+=t}return c}static writeSectionHeaderToBuffer(e,t,s,i=0){const n=new Uint16Array(s,i,Et.SectionHeaderSizeBytes/2),a=new Uint32Array(s,i,Et.SectionHeaderSizeBytes/4),r=new Float32Array(s,i,Et.SectionHeaderSizeBytes/4);a[0]=e.splatCount,a[1]=e.maxSplatCount,a[2]=t>=1?e.bucketSize:0,a[3]=t>=1?e.bucketCount:0,r[4]=t>=1?e.bucketBlockSize:0,n[10]=t>=1?Et.BucketStorageSizeBytes:0,a[6]=t>=1?e.compressionScaleRange:0,a[7]=e.storageSizeBytes,a[8]=t>=1?e.fullBucketCount:0,a[9]=t>=1?e.partiallyFilledBucketCount:0,n[20]=e.sphericalHarmonicsDegree}static writeSectionHeaderSplatCountToBuffer(e,t,s=0){new Uint32Array(t,s,Et.SectionHeaderSizeBytes/4)[0]=e}constructFromBuffer(e,t){this.bufferData=e,this.globalSplatIndexToLocalSplatIndexMap=[],this.globalSplatIndexToSectionMap=[];const s=Et.parseHeader(this.bufferData);this.versionMajor=s.versionMajor,this.versionMinor=s.versionMinor,this.maxSectionCount=s.maxSectionCount,this.sectionCount=t?s.maxSectionCount:0,this.maxSplatCount=s.maxSplatCount,this.splatCount=t?s.maxSplatCount:0,this.compressionLevel=s.compressionLevel,this.sceneCenter=(new a).copy(s.sceneCenter),this.minSphericalHarmonicsCoeff=s.minSphericalHarmonicsCoeff,this.maxSphericalHarmonicsCoeff=s.maxSphericalHarmonicsCoeff,this.sections=Et.parseSectionHeaders(s,this.bufferData,Et.HeaderSizeBytes,t),this.linkBufferArrays(),this.buildMaps()}static calculateComponentStorage(e,t){const s=Et.CompressionLevels[e].BytesPerCenter,i=Et.CompressionLevels[e].BytesPerScale,n=Et.CompressionLevels[e].BytesPerRotation,a=Et.CompressionLevels[e].BytesPerColor,r=we(t),o=Et.CompressionLevels[e].BytesPerSphericalHarmonicsComponent*r;return{bytesPerCenter:s,bytesPerScale:i,bytesPerRotation:n,bytesPerColor:a,sphericalHarmonicsComponentsPerSplat:r,sphericalHarmonicsBytesPerSplat:o,bytesPerSplat:s+i+n+a+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*Et.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){Et.writeHeaderCountsToBuffer(e,t,this.bufferData),this.sectionCount=e,this.splatCount=t}updateSectionLoadedCounts(e,t){const s=Et.HeaderSizeBytes+Et.SectionHeaderSizeBytes*e;Et.writeSectionHeaderSplatCountToBuffer(t,this.bufferData,s),this.sections[e].splatCount=t}static writeSplatDataToSectionBuffer=function(){const e=new ArrayBuffer(12),t=new ArrayBuffer(12),s=new ArrayBuffer(16),i=new ArrayBuffer(4),n=new ArrayBuffer(256),o=new r,l=new a,c=new a,{X:h,Y:d,Z:u,SCALE0:p,SCALE1:A,SCALE2:m,ROTATION0:g,ROTATION1:f,ROTATION2:S,ROTATION3:C,FDC0:x,FDC1:y,FDC2:v,OPACITY:I,FRC0:B,FRC9:b}=vt.OFFSET,T=(e,t,s)=>{const i=2*s+1;return e=Math.round(e*t)+s,Ie(e,0,i)};return function(a,r,w,D,M,E,R,F,P=-Le,k=Le){const L=we(M),U=w,H=U+Et.CompressionLevels[D].BytesPerCenter,_=H+Et.CompressionLevels[D].BytesPerScale,z=_+Et.CompressionLevels[D].BytesPerRotation,Q=z+Et.CompressionLevels[D].BytesPerColor;if(void 0!==a[g]?(o.set(a[g],a[f],a[S],a[C]),o.normalize()):o.set(1,0,0,0),void 0!==a[p]?l.set(a[p]||0,a[A]||0,a[m]||0):l.set(0,0,0),0===D){const e=new Float32Array(r,U,Et.CenterComponentCount),t=new Float32Array(r,_,Et.RotationComponentCount),s=new Float32Array(r,H,Et.ScaleComponentCount);if(t.set([o.x,o.y,o.z,o.w]),s.set([l.x,l.y,l.z]),e.set([a[h],a[d],a[u]]),M>0){const e=new Float32Array(r,Q,L);if(M>=1){for(let t=0;t<9;t++)e[t]=a[B+t]||0;if(M>=2)for(let t=0;t<15;t++)e[t+9]=a[b+t]||0}}}else{const i=new Uint16Array(e,0,Et.CenterComponentCount),p=new Uint16Array(s,0,Et.RotationComponentCount),A=new Uint16Array(t,0,Et.ScaleComponentCount);if(p.set([Bt(o.x),Bt(o.y),Bt(o.z),Bt(o.w)]),A.set([Bt(l.x),Bt(l.y),Bt(l.z)]),c.set(a[h],a[d],a[u]).sub(E),c.x=T(c.x,R,F),c.y=T(c.y,R,F),c.z=T(c.z,R,F),i.set([c.x,c.y,c.z]),M>0){const e=1===D?2:1,t=new(1===D?Uint16Array:Uint8Array)(n,0,L);if(M>=1){for(let e=0;e<9;e++){const s=a[B+e]||0;t[e]=1===D?Bt(s):wt(s,P,k)}const s=9*e;if(It(t.buffer,0,r,Q,s),M>=2){for(let e=0;e<15;e++){const s=a[b+e]||0;t[e+9]=1===D?Bt(s):wt(s,P,k)}It(t.buffer,s,r,Q+s,15*e)}}}It(i.buffer,0,r,U,6),It(A.buffer,0,r,H,6),It(p.buffer,0,r,_,8)}const O=new Uint8ClampedArray(i,0,4);O.set([a[x]||0,a[y]||0,a[v]||0]),O[3]=a[I]||0,It(O.buffer,0,r,z,4)}}();static generateFromUncompressedSplatArrays(e,t,s,i,n,r,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=vt.OFFSET.FRC0;e<vt.OFFSET.FRC23&&e<t.length;e++)(!l||t[e]<l)&&(l=t[e]),(!c||t[e]>c)&&(c=t[e])}}l=l||-Le,c=c||Le;const{bytesPerSplat:d}=Et.calculateComponentStorage(s,h),u=Et.CompressionLevels[s].ScaleRange,p=[],A=[];let m=0;for(let i=0;i<e.length;i++){const g=e[i],f=new vt(h);for(let e=0;e<g.splatCount;e++){const s=g.splats[e];(s[vt.OFFSET.OPACITY]||0)>=t&&f.addSplat(s)}const S=o[i]||{},C=(S.blockSizeFactor||1)*(n||Et.BucketBlockSize),x=Math.ceil((S.bucketSizeFactor||1)*(r||Et.BucketSize)),y=Et.computeBucketsForUncompressedSplatArray(f,C,x),v=y.fullBuckets.length,I=y.partiallyFullBuckets.map(e=>e.splats.length),B=I.length,b=[...y.fullBuckets,...y.partiallyFullBuckets],T=f.splats.length*d,w=4*B,D=s>=1?b.length*Et.BucketStorageSizeBytes+w:0,M=T+D,E=new ArrayBuffer(M),R=u/(.5*C),F=new a;let P=0;for(let e=0;e<b.length;e++){const t=b[e];F.fromArray(t.center);for(let e=0;e<t.splats.length;e++){let i=t.splats[e];const n=f.splats[i],a=D+P*d;Et.writeSplatDataToSectionBuffer(n,E,a,s,h,F,R,u,l,c),P++}}if(m+=P,s>=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,w,b.length*Et.BucketStorageSizeFloats);for(let e=0;e<b.length;e++){const s=b[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(Et.SectionHeaderSizeBytes);Et.writeSectionHeaderToBuffer({maxSplatCount:P,splatCount:P,bucketSize:x,bucketCount:b.length,bucketBlockSize:C,compressionScaleRange:u,storageSizeBytes:M,fullBucketCount:v,partiallyFilledBucketCount:B,sphericalHarmonicsDegree:h},s,k,0),A.push(k)}let g=0;for(let e of p)g+=e.byteLength;const f=Et.HeaderSizeBytes+Et.SectionHeaderSizeBytes*p.length+g,S=new ArrayBuffer(f);Et.writeHeaderToBuffer({versionMajor:0,versionMinor:1,maxSectionCount:p.length,sectionCount:p.length,maxSplatCount:m,splatCount:m,compressionLevel:s,sceneCenter:i,minSphericalHarmonicsCoeff:l,maxSphericalHarmonicsCoeff:c},S);let C=Et.HeaderSizeBytes;for(let e of A)new Uint8Array(S,C,Et.SectionHeaderSizeBytes).set(new Uint8Array(e)),C+=Et.SectionHeaderSizeBytes;for(let e of p)new Uint8Array(S,C,e.byteLength).set(new Uint8Array(e)),C+=e.byteLength;return new Et(S)}static computeBucketsForUncompressedSplatArray(e,t,s){let i=e.splatCount;const n=t/2,r=new a,o=new a;for(let t=0;t<i;t++){const s=e.splats[t],i=[s[vt.OFFSET.X],s[vt.OFFSET.Y],s[vt.OFFSET.Z]];(0===t||i[0]<r.x)&&(r.x=i[0]),(0===t||i[0]>o.x)&&(o.x=i[0]),(0===t||i[1]<r.y)&&(r.y=i[1]),(0===t||i[1]>o.y)&&(o.y=i[1]),(0===t||i[2]<r.z)&&(r.z=i[2]),(0===t||i[2]>o.z)&&(o.z=i[2])}const l=(new a).copy(o).sub(r),c=Math.ceil(l.y/t),h=Math.ceil(l.z/t),d=new a,u=[],p={};for(let a=0;a<i;a++){const i=e.splats[a],o=[i[vt.OFFSET.X],i[vt.OFFSET.Y],i[vt.OFFSET.Z]],l=Math.floor((o[0]-r.x)/t),A=Math.floor((o[1]-r.y)/t),m=Math.floor((o[2]-r.z)/t);d.x=l*t+r.x+n,d.y=A*t+r.y+n,d.z=m*t+r.z+n;const g=l*(c*h)+A*h+m;let f=p[g];f||(p[g]=f={splats:[],center:d.toArray()}),f.splats.push(a),f.splats.length>=s&&(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 Rt{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 vt(e.sphericalHarmonicsDegree),a=i[t];for(let t=0;t<e.splatCount;t++)a(t)&&s.addSplat(e.splats[t]);n.push(s)}return{splatArrays:n,parameters:t}}static getStandardPartitioner(e=0,t=new a,s=Et.BucketBlockSize,i=Et.BucketSize){return new Rt(void 0,void 0,void 0,n=>{const r=vt.OFFSET.X,o=vt.OFFSET.Y,l=vt.OFFSET.Z;e<=0&&(e=n.splatCount);const c=new a,h=.5;n.splats.forEach(e=>{var s;c.set(e[r],e[o],e[l]).sub(t),(s=c).x=Math.floor(s.x/h)*h,s.y=Math.floor(s.y/h)*h,s.z=Math.floor(s.z/h)*h,e.centerDist=c.lengthSq()}),n.splats.sort((e,t)=>e.centerDist>t.centerDist?1:-1);const d=[],u=[];e=Math.min(n.splatCount,e);const p=Math.ceil(n.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:s,bucketSize:i}),A+=e}return{sectionCount:d.length,sectionFilters:d,groupingParameters:u}})}}class Ft{constructor(e,t,s,i,n,r,o){this.splatPartitioner=e,this.alphaRemovalThreshold=t,this.compressionLevel=s,this.sectionSize=i,this.sceneCenter=n?(new a).copy(n):void 0,this.blockSize=r,this.bucketSize=o}generateFromUncompressedSplatArray(e){const t=this.splatPartitioner.partitionUncompressedSplatArray(e);return Et.generateFromUncompressedSplatArrays(t.splatArrays,this.alphaRemovalThreshold,this.compressionLevel,this.sceneCenter,this.blockSize,this.bucketSize,t.parameters)}static getStandardGenerator(e=1,t=1,s=0,i=new a,n=Et.BucketBlockSize,r=Et.BucketSize){const o=Rt.getStandardPartitioner(s,i,n,r);return new Ft(o,e,t,s,i,n,r)}}const Pt={INRIAV1:0},kt=0,Lt=1,Ut=2,Ht=3,_t=4,zt=5,Qt=6,Ot={double:0,int:1,uint:2,float:3,short:4,ushort:5,uchar:6},Nt={[kt]:8,[Lt]:4,[Ut]:4,[Ht]:4,[_t]:2,[zt]:2,[Qt]:1};class Vt{static HeaderEndToken="end_header";constructor(){}decodeSectionHeader(e,t,s=0){const i=[];let n=!1,a=-1,r=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){a--;break}{n=!0,s=p,a=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&&(r=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 a=Ot[s];void 0!==n&&(c.push(n),h[n]=a)}}if(A===Vt.HeaderEndToken){o=!0;break}n&&(i.push(A),a++)}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+=Nt[Ot[s]]}const m=this.decodeSphericalHarmonicsFromSectionHeader(d,t);return{headerLines:i,headerStartLine:s,headerEndLine:a,fieldTypes:h,fieldIds:c,fieldOffsets:p,bytesPerVertex:A,vertexCount:r,dataSizeBytes:A*r,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 a=[],r=[];for(let e=0;e<3;e++){if(n>=1)for(let s=0;s<3;s++)a.push(t["f_rest_"+(s+i*e)]);if(n>=2)for(let s=0;s<5;s++)r.push(t["f_rest_"+(s+i*e+3)])}return{degree:n,coefficientsPerChannel:i,degree1Fields:a,degree2Fields:r}}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(Vt.HeaderEndToken)}static checkBufferForEndHeader(e,t,s,i){const n=new Uint8Array(e,Math.max(0,t-s),s),a=i.decode(n);return Vt.checkTextForEndHeader(a)}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 a=new Uint8Array(e,s,n);if(i+=t.decode(a),s+=n,Vt.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 a=new Uint8Array(e,s,n);if(i+=t.decode(a),s+=n,Vt.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===Vt.HeaderEndToken)break}return s}static determineHeaderFormatFromHeaderText(e){return Pt.INRIAV1}static determineHeaderFormatFromPlyBuffer(e){const t=Vt.extractHeaderFromBufferToText(e);return Vt.determineHeaderFormatFromHeaderText(t)}static readVertex(e,t,s,i,n,a,r=!0){const o=s*t.bytesPerVertex+i,l=t.fieldOffsets,c=t.fieldTypes;for(let t of n){const s=c[t];3===s?a[t]=e.getFloat32(o+l[t],!0):4===s?a[t]=e.getInt16(o+l[t],!0):5===s?a[t]=e.getUint16(o+l[t],!0):1===s?a[t]=e.getInt32(o+l[t],!0):2===s?a[t]=e.getUint32(o+l[t],!0):6===s&&(a[t]=r?e.getUint8(o+l[t])/255:e.getUint8(o+l[t]))}}}const Wt=["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"],Gt=Wt.map((e,t)=>t),[qt,Kt,jt,Xt,Jt,Yt,Zt,$t,es,ts,ss,is,ns,as,rs,os,ls,cs]=Gt;class hs{constructor(){this.plyParserutils=new Vt}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=[...Wt,...i],a=n.map((e,t)=>t),r=a.reduce((e,t)=>(e[n[t]]=t,e),{}),o=this.plyParserutils.decodeSectionHeader(e,r,0);return o.splatCount=o.vertexCount,o.bytesPerSplat=o.bytesPerVertex,o.fieldsToReadIndexes=a,o}decodeHeaderText(e){const t=Vt.convertHeaderTextToLines(e),s=this.decodeHeaderLines(t);return s.headerText=e,s.headerSizeBytes=e.indexOf(Vt.HeaderEndToken)+Vt.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,a,r,o=0){o=Math.min(o,e.sphericalHarmonicsDegree);const l=Et.CompressionLevels[0].SphericalHarmonicsDegrees[o].BytesPerSplat;for(let c=t;c<=s;c++){const t=hs.parseToUncompressedSplat(i,c,e,n,o),s=c*l+r;Et.writeSplatDataToSectionBuffer(t,a,s,0,o)}}parseToUncompressedSplatArraySection(e,t,s,i,n,a,r=0){r=Math.min(r,e.sphericalHarmonicsDegree);for(let o=t;o<=s;o++){const t=hs.parseToUncompressedSplat(i,o,e,n,r);a.addSplat(t)}}decodeSectionSplatData(e,t,s,i){i=Math.min(i,s.sphericalHarmonicsDegree);const n=new vt(i);for(let a=0;a<t;a++){const t=hs.parseToUncompressedSplat(e,a,s,0,i);n.addSplat(t)}return n}static parseToUncompressedSplat=function(){let e=[];const t=new r,s=vt.OFFSET.X,i=vt.OFFSET.Y,n=vt.OFFSET.Z,a=vt.OFFSET.SCALE0,o=vt.OFFSET.SCALE1,l=vt.OFFSET.SCALE2,c=vt.OFFSET.ROTATION0,h=vt.OFFSET.ROTATION1,d=vt.OFFSET.ROTATION2,u=vt.OFFSET.ROTATION3,p=vt.OFFSET.FDC0,A=vt.OFFSET.FDC1,m=vt.OFFSET.FDC2,g=vt.OFFSET.OPACITY,f=[];for(let e=0;e<45;e++)f[e]=vt.OFFSET.FRC0+e;return function(r,S,C,x=0,y=0){y=Math.min(y,C.sphericalHarmonicsDegree),hs.readSplat(r,C,S,x,e);const v=vt.createSplat(y);if(void 0!==e[qt]?(v[a]=Math.exp(e[qt]),v[o]=Math.exp(e[Kt]),v[l]=Math.exp(e[jt])):(v[a]=.01,v[o]=.01,v[l]=.01),void 0!==e[ss]?(v[p]=255*e[ss],v[A]=255*e[is],v[m]=255*e[ns]):void 0!==e[rs]?(v[p]=255*e[rs],v[A]=255*e[os],v[m]=255*e[ls]):(v[p]=0,v[A]=0,v[m]=0),void 0!==e[as]&&(v[g]=1/(1+Math.exp(-e[as]))*255),v[p]=Ie(Math.floor(v[p]),0,255),v[A]=Ie(Math.floor(v[A]),0,255),v[m]=Ie(Math.floor(v[m]),0,255),v[g]=Ie(Math.floor(v[g]),0,255),y>=1&&void 0!==e[cs]){for(let t=0;t<9;t++)v[f[t]]=e[C.sphericalHarmonicsDegree1Fields[t]];if(y>=2)for(let t=0;t<15;t++)v[f[9+t]]=e[C.sphericalHarmonicsDegree2Fields[t]]}return t.set(e[Xt],e[Jt],e[Yt],e[Zt]),t.normalize(),v[c]=t.x,v[h]=t.y,v[d]=t.z,v[u]=t.w,v[s]=e[$t],v[i]=e[es],v[n]=e[ts],v}}();static readSplat(e,t,s,i,n){return Vt.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 ds{static parseToUncompressedSplatArray(e,t=0){return(new hs).parseToUncompressedSplatArray(e,t)}}function us(e,t,s,i,n,r,o,l){if(t){return Ft.getStandardGenerator(s,i,n,r,o,l).generateFromUncompressedSplatArray(e)}return Et.generateFromUncompressedSplatArrays([e],s,0,new a)}class ps{static loadFromURL(e,t,s,i,n,r,o=!0,l=0,c,h,d,u,p){let A=s?Se.DirectToSplatBuffer:Se.DirectToSplatArray;o&&(A=Se.DirectToSplatArray);const m=$.ProgressiveLoadSectionSize,g=Et.HeaderSizeBytes+Et.SectionHeaderSizeBytes;let f,S,C,x=0,y=0,v=!1,I=!1;const B=De();let b,T=0,w=0,D=0,M="",E=null,R=[];const F=new TextDecoder,P=new hs;return t&&t(0,"0%",Ce.Downloading),ve(e,(e,s,n)=>{const r=e>=100;if(n&&(R.push({data:n,sizeBytes:n.byteLength,startBytes:D,endBytes:D+n.byteLength}),D+=n.byteLength),A===Se.DownloadBeforeProcessing)r&&B.resolve(R);else{if(!v&&(M+=F.decode(n),Vt.checkTextForEndHeader(M))){E=P.decodeHeaderText(M),x=E.splatCount,I=!0,l=Math.min(l,E.sphericalHarmonicsDegree);const e=Et.CompressionLevels[0].SphericalHarmonicsDegrees[l],t=g+e.BytesPerSplat*x;A===Se.DirectToSplatBuffer?(S=new ArrayBuffer(t),Et.writeHeaderToBuffer({versionMajor:Et.CurrentMajorVersion,versionMinor:Et.CurrentMinorVersion,maxSectionCount:1,sectionCount:1,maxSplatCount:x,splatCount:y,compressionLevel:0,sceneCenter:new a},S)):b=new vt(l),T=E.headerSizeBytes,w=E.headerSizeBytes,v=!0}if(v&&I){if(R.length>0){f=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}(R,f);if(D-T>m||r){const e=D-w,t=Math.floor(e/E.bytesPerSplat),s=t*E.bytesPerSplat,n=e-s,a=y+t,o=w-R[0].startBytes,c=new DataView(f,o,s),h=Et.CompressionLevels[0].SphericalHarmonicsDegrees[l],d=y*h.BytesPerSplat+g;if(A===Se.DirectToSplatBuffer?P.parseToUncompressedSplatBufferSection(E,0,t-1,c,0,S,d,l):P.parseToUncompressedSplatArraySection(E,0,t-1,c,0,b,l),y=a,A===Se.DirectToSplatBuffer&&(C||(Et.writeSectionHeaderToBuffer({maxSplatCount:x,splatCount:y,bucketSize:0,bucketCount:0,bucketBlockSize:0,compressionScaleRange:0,storageSizeBytes:0,fullBucketCount:0,partiallyFilledBucketCount:0,sphericalHarmonicsDegree:l},0,S,Et.HeaderSizeBytes),C=new Et(S,!1)),C.updateLoadedCounts(1,y),i&&i(C,r)),T+=m,w+=s,0===n)R=[];else{let e=[],t=0;for(let s=R.length-1;s>=0;s--){const i=R[s];if(t+=i.sizeBytes,e.unshift(i),t>=n)break}R=e}}}r&&(A===Se.DirectToSplatBuffer?B.resolve(C):B.resolve(b))}}t&&t(e,s,Ce.Downloading)},!1,c).then(()=>(t&&t(0,"0%",Ce.Processing),B.promise.then(e=>{if(t&&t(100,"100%",Ce.Done),A===Se.DownloadBeforeProcessing){const e=R.map(e=>e.data);return new Blob(e).arrayBuffer().then(e=>ps.loadFromFileData(e,n,r,o,l,h,d,u,p))}return A===Se.DirectToSplatBuffer?e:Te(()=>us(e,o,n,r,h,d,u,p))})))}static loadFromFileData(e,t,s,i,n=0,a,r,o,l){return Te(()=>ds.parseToUncompressedSplatArray(e,n)).then(e=>us(e,i,t,s,a,r,o,l))}}const As=new e.Vector3(1,0,0),ms=new e.Vector3(0,1,0),gs=new e.Vector3(0,0,1);class fs{constructor(t=new e.Vector3,s=new e.Vector3){this.origin=new e.Vector3,this.direction=new e.Vector3,this.setParameters(t,s)}setParameters(e,t){this.origin.copy(e),this.direction.copy(t).normalize()}boxContainsPoint(e,t,s){return!(t.x<e.min.x-s||t.x>e.max.x+s||t.y<e.min.y-s||t.y>e.max.y+s||t.z<e.min.z-s||t.z>e.max.z+s)}intersectBox=function(){const t=new e.Vector3,s=[],i=[],n=[];return function(e,a){if(i[0]=this.origin.x,i[1]=this.origin.y,i[2]=this.origin.z,n[0]=this.direction.x,n[1]=this.direction.y,n[2]=this.direction.z,this.boxContainsPoint(e,this.origin,1e-4))return a&&(a.origin.copy(this.origin),a.normal.set(0,0,0),a.distance=-1),!0;for(let r=0;r<3;r++){if(0==n[r])continue;const o=0==r?As:1==r?ms:gs,l=n[r]<0?e.max:e.min;let c=-Math.sign(n[r]);s[0]=0==r?l.x:1==r?l.y:l.z;let h=s[0]-i[r];if(h*c<0){const l=(r+1)%3,d=(r+2)%3;if(s[2]=n[l]/n[r]*h+i[l],s[1]=n[d]/n[r]*h+i[d],t.set(s[r],s[d],s[l]),this.boxContainsPoint(e,t,1e-4))return a&&(a.origin.copy(t),a.normal.copy(o).multiplyScalar(c),a.distance=t.sub(this.origin).length()),!0}}return!1}}();intersectSphere=function(){const t=new e.Vector3;return function(e,s,i){t.copy(e).sub(this.origin);const n=t.dot(this.direction),a=n*n,r=t.dot(t)-a,o=s*s;if(r>o)return!1;const l=Math.sqrt(o-r),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(e).normalize(),i.distance=d),!0}}()}class Ss{constructor(){this.origin=new e.Vector3,this.normal=new e.Vector3,this.distance=0,this.splatIndex=0}set(e,t,s,i){this.origin.copy(e),this.normal.copy(t),this.distance=s,this.splatIndex=i}clone(){const e=new Ss;return e.origin.copy(this.origin),e.normal.copy(this.normal),e.distance=this.distance,e.splatIndex=this.splatIndex,e}}class Cs{constructor(e,t,s=!1){this.ray=new fs(e,t),this.raycastAgainstTrueSplatEllipsoid=s}setFromCameraAndScreenPosition=function(){const t=new e.Vector2;return function(e,s,i){if(t.x=s.x/i.x*2-1,t.y=(i.y-s.y)/i.y*2-1,e.isPerspectiveCamera)this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e;else{if(!e.isOrthographicCamera)throw new Error("Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type");this.ray.origin.set(t.x,t.y,(e.near+e.far)/(e.near-e.far)).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e}}}();intersectSplatMesh=function(){const t=new e.Matrix4,s=new e.Matrix4,i=new e.Matrix4,n=new fs,a=new e.Vector3;return function(e,r=[]){const o=e.getSplatTree();if(o){for(let l=0;l<o.subTrees.length;l++){const c=o.subTrees[l];s.copy(e.matrixWorld),e.dynamicMode&&(e.getSceneTransform(l,i),s.multiply(i)),t.copy(s).invert(),n.origin.copy(this.ray.origin).applyMatrix4(t),n.direction.copy(this.ray.origin).add(this.ray.direction),n.direction.applyMatrix4(t).sub(n.origin).normalize();const h=[];c.rootNode&&this.castRayAtSplatTreeNode(n,o,c.rootNode,h),h.forEach(e=>{e.origin.applyMatrix4(s),e.normal.applyMatrix4(s).normalize(),e.distance=a.copy(e.origin).sub(this.ray.origin).length()}),r.push(...h)}return r.sort((e,t)=>e.distance>t.distance?1:-1),r}}}();castRayAtSplatTreeNode=function(){const t=new e.Vector4,s=new e.Vector3,i=new e.Vector3,n=new e.Quaternion,a=new Ss,r=1e-7,o=new e.Vector3(0,0,0),l=new e.Matrix4,c=new e.Matrix4,h=new e.Matrix4,d=new e.Matrix4,u=new e.Matrix4,p=new fs;return function(e,A,m,g=[]){if(e.intersectBox(m.boundingBox)){if(m.data&&m.data.indexes&&m.data.indexes.length>0)for(let f=0;f<m.data.indexes.length;f++){const S=m.data.indexes[f],C=A.splatMesh.getSceneIndexForSplat(S);if(A.splatMesh.getScene(C).visible&&(A.splatMesh.getSplatColor(S,t),A.splatMesh.getSplatCenter(S,s),A.splatMesh.getSplatScaleAndRotation(S,i,n),!(i.x<=r||i.y<=r||A.splatMesh.splatRenderMode===Z.ThreeD&&i.z<=r)))if(this.raycastAgainstTrueSplatEllipsoid){c.makeScale(i.x,i.y,i.z),h.makeRotationFromQuaternion(n);const r=2*Math.log10(t.w);if(l.makeScale(r,r,r),u.copy(l).multiply(h).multiply(c),d.copy(u).invert(),p.origin.copy(e.origin).sub(s).applyMatrix4(d),p.direction.copy(e.origin).add(e.direction).sub(s),p.direction.applyMatrix4(d).sub(p.origin).normalize(),p.intersectSphere(o,1,a)){const e=a.clone();e.splatIndex=S,e.origin.applyMatrix4(u).add(s),g.push(e)}}else{let t=i.x+i.y,n=2;if(A.splatMesh.splatRenderMode===Z.ThreeD&&(t+=i.z,n=3),t/=n,e.intersectSphere(s,t,a)){const e=a.clone();e.splatIndex=S,g.push(e)}}}if(m.children&&m.children.length>0)for(let t of m.children)this.castRayAtSplatTreeNode(e,A,t,g);return g}}}()}const xs="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";function ys(e){let t,s,i,n,a,r,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)),a&&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 b,T,w;i||(b=y.data.sort.indexesToSort,w=y.data.sort.transforms,B&&(T=y.data.sort.precomputedDistances)),function(C,y,v,I,B,b,T){const w=performance.now();if(!i&&(new Uint32Array(s,o,B.byteLength/x.BytesPerInt).set(B),new Float32Array(s,h,T.byteLength/x.BytesPerFloat).set(T),I)){let e;e=n?new Int32Array(s,d,b.byteLength/x.BytesPerInt):new Float32Array(s,d,b.byteLength/x.BytesPerFloat),e.set(b)}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,r,I,n,a);const D={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),D.sortedIndexes=f}const M=performance.now();D.sortTime=M-w,e.postMessage(D)}(I,v,y.data.sort.modelViewProj,B,b,T,w)}else if(y.data.init){x=y.data.init.Constants,r=y.data.init.splatCount,i=y.data.init.useSharedMemory,n=y.data.init.integerBasedSort,a=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=r*x.BytesPerInt,B=r*g,b=v,T=n?r*x.BytesPerInt:r*x.BytesPerFloat,w=r*x.BytesPerInt,D=r*x.BytesPerInt,M=n?S*x.BytesPerInt*2:S*x.BytesPerFloat*2,E=a?r*x.BytesPerInt:0,R=a?x.MaxScenes*v:0,F=32*x.MemoryPageSize,P=I+B+b+T+w+M+D+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+b,u=d+T,p=u+w,l=p+M,c=l+D,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 vs{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 Is{constructor(e){}show(){}hide(){}setContainer(e){}setProgress(e){}}class Bs{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 bs{constructor(e={}){if(e.cameraUp||(e.cameraUp=[0,1,0]),this.cameraUp=(new a).fromArray(e.cameraUp),e.initialCameraPosition||(e.initialCameraPosition=[0,10,15]),this.initialCameraPosition=(new a).fromArray(e.initialCameraPosition),e.initialCameraRotation||(e.initialCameraRotation=[0,0,0]),this.initialCameraRotation=(new a).fromArray(e.initialCameraRotation),this.backgroundColor=e.backgroundColor,e.initialCameraLookAt||(e.initialCameraLookAt=[0,0,0]),this.initialCameraLookAt=(new a).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||j.Always,this.sceneRevealMode=e.sceneRevealMode||Y.Default,this.focalAdjustment=e.focalAdjustment||1,this.maxScreenSpaceSplatSize=e.maxScreenSpaceSplatSize||1024,this.logLevel=e.logLevel||K.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,Re()){const e=Fe();e.major<17&&(this.enableSIMDInSort=!1),e.major<16&&(this.sharedMemoryForWorkers=!1)}void 0!==e.splatRenderMode&&null!==e.splatRenderMode||(e.splatRenderMode=Z.ThreeD),this.splatRenderMode=e.splatRenderMode,this.sceneFadeInRateMultiplier=e.sceneFadeInRateMultiplier||1,this.splatSortDistanceMapPrecision=e.splatSortDistanceMapPrecision||$.DefaultSplatSortDistanceMapPrecision;const t=this.integerBasedSort?20:24;this.splatSortDistanceMapPrecision=Ie(this.splatSortDistanceMapPrecision,10,t),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 Cs,this.infoPanel=null,this.startInOrthographicMode=!1,this.currentFPS=0,this.lastSortTime=0,this.consecutiveRenderFrames=0,this.previousCameraTarget=new a,this.nextCameraTarget=new a,this.mousePosition=new p,this.mouseDownPosition=new p,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 vs(null,this.rootElement||document.body),this.loadingSpinner.hide(),this.loadingProgressBar=new Is(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 xt(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 L,this.sceneHelper=new Bs(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 p;this.getRenderDimensions(e),this.perspectiveCamera=new U(50,e.x/e.y,.1,1e3),this.orthographicCamera=new H(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(_.degToRad(this.initialCameraRotation.x)),this.camera.rotateY(_.degToRad(this.initialCameraRotation.y)),this.camera.rotateZ(_.degToRad(this.initialCameraRotation.z))}}setupRenderer(){if(!this.usingExternalRenderer){const e=new p;this.getRenderDimensions(e),this.renderer=new z({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 q(this.camera,this.renderer.domElement):this.perspectiveControls=new q(this.camera,this.renderer.domElement):(this.perspectiveControls=new q(this.perspectiveCamera,this.renderer.domElement),this.orthographicControls=new q(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 a;tempMatrixLeft=new o;tempMatrixRight=new o;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=Be()}onMouseUp=function(){const e=new p;return function(t){e.copy(this.mousePosition).sub(this.mouseDownPosition);Be()-this.mouseDownTime<.5&&e.length()<2&&this.onMouseClick(t)}}();onMouseClick(e){this.mousePosition.set(e.offsetX,e.offsetY),this.checkForFocalPointChange()}checkPointRenderDimensions=new p;checkPointToNewFocalPoint=new a;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=Be())}};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,a=e?this.orthographicControls:this.perspectiveControls;i(a),i(n),a.target.copy(n.target),e?bs.setCameraZoomFromPosition(s,t,n):bs.setCameraPositionFromZoom(s,t,a),this.controls=a,this.camera.lookAt(this.controls.target)}}static setCameraPositionFromZoom=function(){const e=new a;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 a;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 p;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,a=1/n;this.adjustForWebXRStereo(e),this.splatMesh.updateUniforms(e,t*n,s*n,this.camera.isOrthographicCamera,this.camera.zoom||1,a)}}}();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:J(e),i=bs.isProgressivelyLoadable(s)&&t.progressiveLoad,n=void 0===t.showLoadingUI||null===t.showLoadingUI||t.showLoadingUI;let a=null;n&&(this.loadingSpinner.removeAllTasks(),a=this.loadingSpinner.addTask("Downloading..."));const r=(e,t,s)=>{if(n)if(s===Ce.Downloading)if(100==e)this.loadingSpinner.setMessageForTask(a,"Download complete!");else if(i)this.loadingSpinner.setMessageForTask(a,"Downloading splats...");else{const e=t?`: ${t}`:"...";this.loadingSpinner.setMessageForTask(a,`Downloading${e}`)}else s===Ce.Processing&&(console.log("loaderStatus === LoaderStatus.Processing"),this.loadingSpinner.setMessageForTask(a,"Processing splats..."))};let o=!1,l=0;const c=(e,t)=>{n&&((e&&i||t&&!i)&&(this.loadingSpinner.removeTask(a),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,a)=>{!i&&t.onProgress&&t.onProgress(0,"0%",Ce.Processing);const r={rotation:t.rotation||t.orientation,position:t.position,scale:t.scale,splatAlphaRemovalThreshold:t.splatAlphaRemovalThreshold};return this.addSplatBuffers([e],[r],a,s&&n,n,i,i).then(()=>{!i&&t.onProgress&&t.onProgress(100,"100%",Ce.Processing),c(s,a)})}).bind(this),(e,s,i)=>{l=e,r(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,a,r){const o=this.downloadSplatSceneToSplatBuffer(e,s,n,!1,void 0,t,r),l=Me(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=>{a&&a(),this.clearSplatSceneDownloadAndBuildPromise(),this.removeSplatSceneDownloadPromise(o);const s=t instanceof ye||"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,a,r){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&&Te(()=>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,r),u=d.abort?d.abort.bind(d):void 0,p=Me(u),A=Me(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 ye||"AbortError"===e.name?e:new Error(`Viewer::addSplatScene -> Could not load one or more scenes: ${e.message}`);p.reject(t),a&&a(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 a;t&&(this.loadingSpinner.removeAllTasks(),a=this.loadingSpinner.addTask("Downloading..."));const r=(e,r,o,l)=>{n[e]=r;let c=0;for(let e=0;e<i;e++)c+=n[e]||0;c/=i,o=`${c.toFixed(2)}%`,t&&l===Ce.Downloading&&this.loadingSpinner.setMessageForTask(a,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:J(s.path),n=this.downloadSplatSceneToSplatBuffer(s.path,s.splatAlphaRemovalThreshold,r.bind(this,t),!1,void 0,i,s.headers,l);c.push(n)}const h=Promise.all(c).then(i=>(t&&this.loadingSpinner.removeTask(a),s&&s(0,"0%",Ce.Processing),this.addSplatBuffers(i,e,!0,t,t,!1,!1).then(()=>{s&&s(100,"100%",Ce.Processing),this.clearSplatSceneDownloadAndBuildPromise()}))).catch(e=>{t&&this.loadingSpinner.removeTask(a),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(h),h}downloadSplatSceneToSplatBuffer(e,t=1,s=void 0,i=!1,n=void 0,a,r){const o=!i&&this.optimizeSplatData;try{if(a===X.Ply)return ps.loadFromURL(e,s,i,n,t,this.inMemoryCompressionLevel,o,this.sphericalHarmonicsDegree,r)}catch(e){throw e instanceof yt?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===X.Ply}addSplatBuffers=(e,t=[],s=!0,i=!0,n=!0,a=!1,r=!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...")),Te(()=>{if(this.isDisposingOrDisposed())h();else{const i=this.addSplatBuffersToMesh(e,t,s,n,a,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?(r?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,a=!1,r=!0){if(this.isDisposingOrDisposed())return;let o=[],l=[];a||(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>=me&&(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)},r);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,a=$.DefaultSplatSortDistanceMapPrecision){const r=new Worker(URL.createObjectURL(new Blob(["(",ys.toString(),")(self)"],{type:"application/javascript"})));let o="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";const l=Re()?Fe():null;s||t?s?t||l&&l.major<=16&&l.minor<4&&(o="AGFzbQEAAAAADwhkeWxpbmsuMAEEAAAAAAEXAmAAAGAQf39/f39/f39/f39/f39/fwACDwEDZW52Bm1lbW9yeQIAAAMDAgABBz4DEV9fd2FzbV9jYWxsX2N0b3JzAAAYX193YXNtX2FwcGx5X2RhdGFfcmVsb2NzAAALc29ydEluZGV4ZXMAAQrrDwICAAvlDwQBfAN7B30DfyALIAprIQwCQAJAIA4EQCANBEBB+P///wchCkGIgICAeCENIAsgDE0NAyAMIQUDQCADIAVBAnQiAWogAiAAIAFqKAIAQQJ0aigCACIBNgIAIAEgCiABIApIGyEKIAEgDSABIA1KGyENIAVBAWoiBSALRw0ACwwDCyAPBEAgCyAMTQ0CQX8hD0H4////ByEKQYiAgIB4IQ0gDCECA0AgDyAHIAAgAkECdCIcaigCACIdQQJ0aigCACIbRwRAAn8gBf0JAjggCCAbQQZ0aiIO/QkCDCAOKgIc/SABIA4qAiz9IAIgDioCPP0gA/3mASAF/QkCKCAO/QkCCCAOKgIY/SABIA4qAij9IAIgDioCOP0gA/3mASAF/QkCCCAO/QkCACAOKgIQ/SABIA4qAiD9IAIgDioCMP0gA/3mASAF/QkCGCAO/QkCBCAOKgIU/SABIA4qAiT9IAIgDioCNP0gA/3mAf3kAf3kAf3kASIR/V/9DAAAAAAAQI9AAAAAAABAj0AiEv3yASIT/SEBIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEOAn8gE/0hACIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAv9ESAO/RwBAn8gESAR/Q0ICQoLDA0ODwABAgMAAQID/V8gEv3yASIR/SEAIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4C/0cAgJ/IBH9IQEiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgL/RwDIRIgGyEPCyADIBxqIAEgHUEEdGr9AAAAIBL9tQEiEf0bACAR/RsBaiAR/RsCaiAR/RsDaiIONgIAIA4gCiAKIA5KGyEKIA4gDSANIA5IGyENIAJBAWoiAiALRw0ACwwDCwJ/IAUqAgi7/RQgBSoCGLv9IgH9DAAAAAAAQI9AAAAAAABAj0D98gEiEf0hASIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDgJ/IBH9IQAiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQpBiICAgHghDSALIAxNDQL9ESAO/RwBIAX9HAIhEiAMIQUDQCADIAVBAnQiAmogASAAIAJqKAIAQQR0av0AAAAgEv21ASIR/RsAIBH9GwFqIBH9GwJqIgI2AgAgAiAKIAIgCkgbIQogAiANIAIgDUobIQ0gBUEBaiIFIAtHDQALDAILIA0EQEH4////ByEKQYiAgIB4IQ0gCyAMTQ0CIAwhBQNAIAMgBUECdCIBagJ/IAIgACABaigCAEECdGoqAgC7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAsiDjYCACAKIA4gCiAOSBshCiANIA4gDSAOShshDSAFQQFqIgUgC0cNAAsMAgsgD0UEQCALIAxNDQEgBSoCKCEUIAUqAhghFSAFKgIIIRZB+P///wchCkGIgICAeCENIAwhBQNAAn8gFCABIAAgBUECdCIHaigCAEEEdGoiAioCCJQgFiACKgIAlCAVIAIqAgSUkpK7RAAAAAAAALBAoiIQmUQAAAAAAADgQWMEQCAQqgwBC0GAgICAeAshDiADIAdqIA42AgAgCiAOIAogDkgbIQogDSAOIA0gDkobIQ0gBUEBaiIFIAtHDQALDAILIAsgDE0NAEF/IQ9B+P///wchCkGIgICAeCENIAwhAgNAIA8gByAAIAJBAnQiG2ooAgBBAnQiHGooAgAiDkcEQCAFKgI4IhQgCCAOQQZ0aiIPKgI8lCAFKgIoIhUgDyoCOJQgBSoCCCIWIA8qAjCUIAUqAhgiFyAPKgI0lJKSkiEYIBQgDyoCLJQgFSAPKgIolCAWIA8qAiCUIBcgDyoCJJSSkpIhGSAUIA8qAhyUIBUgDyoCGJQgFiAPKgIQlCAXIA8qAhSUkpKSIRogFCAPKgIMlCAVIA8qAgiUIBYgDyoCAJQgFyAPKgIElJKSkiEUIA4hDwsgAyAbagJ/IBggASAcQQJ0aiIOKgIMlCAZIA4qAgiUIBQgDioCAJQgGiAOKgIElJKSkrtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIONgIAIAogDiAKIA5IGyEKIA0gDiANIA5KGyENIAJBAWoiAiALRw0ACwwBC0GIgICAeCENQfj///8HIQoLIAsgDEsEQCAJQQFrsyANsiAKspOVIRQgDCENA0ACfyAUIAMgDUECdGoiASgCACAKa7KUIhWLQwAAAE9dBEAgFagMAQtBgICAgHgLIQ4gASAONgIAIAQgDkECdGoiASABKAIAQQFqNgIAIA1BAWoiDSALRw0ACwsgCUECTwRAIAQoAgAhDUEBIQoDQCAEIApBAnRqIgEgASgCACANaiINNgIAIApBAWoiCiAJRw0ACwsgDEEASgRAIAwhCgNAIAYgCkEBayIBQQJ0IgJqIAAgAmooAgA2AgAgCkEBSyABIQoNAAsLIAsgDEoEQCALIQoDQCAGIAsgBCADIApBAWsiCkECdCIBaigCAEECdGoiAigCACIFa0ECdGogACABaigCADYCACACIAVBAWs2AgAgCiAMSg0ACwsL"):o=xs:(o=xs,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 r.postMessage({init:{sorterWasmBytes:h.buffer,splatCount:e,useSharedMemory:t,integerBasedSort:i,dynamicMode:n,distanceMapRange:1<<a,Constants:{BytesPerFloat:$.BytesPerFloat,BytesPerInt:$.BytesPerInt,MemoryPageSize:$.MemoryPageSize,MaxScenes:$.MaxScenes}}}),r}(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>=K.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*$.MaxScenes)):(this.sortWorkerIndexesToSort=new Uint32Array(i),this.sortWorkerPrecomputedDistances=new t(i),this.sortWorkerTransforms=new Float32Array(16*$.MaxScenes));for(let e=0;e<s;e++)this.sortWorkerIndexesToSort[e]=e;if(this.sortWorker.maxSplatCount=i,this.logLevel>=K.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 a;t&&(this.loadingSpinner.removeAllTasks(),this.loadingSpinner.show(),a=this.loadingSpinner.addTask("Removing splat scene..."));const r=()=>{t&&(this.loadingSpinner.hide(),this.loadingSpinner.removeTask(a))},o=e=>{r(),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 a=!1;for(let t of e)if(t===s){a=!0;break}if(!a){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=Y.Instant,this.createSplatMesh(),this.addSplatBuffers(t,i,!0,!1,!0).then(()=>{l()||(r(),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&&(be(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 t=new a,s=new r,i=1e-4;return function(){if(!this.initialized||!this.splatRenderReady||this.isDisposingOrDisposed())return!1;let n=!1,a=!1;if(this.camera){const e=this.camera.position,n=this.camera.quaternion;a=Math.abs(e.x-t.x)>i||Math.abs(e.y-t.y)>i||Math.abs(e.z-t.z)>i||Math.abs(n.x-s.x)>i||Math.abs(n.y-s.y)>i||Math.abs(n.z-s.z)>i||Math.abs(n.w-s.w)>i}return n=this.renderMode!==j.Never&&(0===e||this.splatMesh.visibleRegionChanging||a||this.renderMode===j.Always||!0===this.dynamicMode||this.renderNextFrame),this.camera&&(t.copy(this.camera.position),s.copy(this.camera.quaternion)),e++,n}}();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&&bs.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=Be();fpsFrameCount=0;updateFPS=()=>{if(this.consecutiveRenderFrames>60){const e=Be();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 p,t=new p;let s;return function(){this.usingExternalCamera||(this.renderer.getSize(t),void 0!==s&&s===this.camera.isOrthographicCamera&&t.x===e.x&&t.y===e.y||(this.camera.isOrthographicCamera?(this.camera.left=-t.x/2,this.camera.right=t.x/2,this.camera.top=t.y/2,this.camera.bottom=-t.y/2):this.camera.aspect=t.x/t.y,this.camera.updateProjectionMatrix(),e.copy(t),s=this.camera.isOrthographicCamera))}}();timingSensitiveUpdates=function(){let e;return function(){const t=Be();e||(e=t);const s=t-e;this.updateCameraTransition(t),this.updateFocusMarker(s),e=t}}();tempCameraTarget=new a;toPreviousTarget=new a;toNextTarget=new a;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 p;let t=!1;return function(s){if(this.getRenderDimensions(e),this.transitioningCameraTarget){this.sceneHelper.setFocusMarkerVisibility(!0);const i=Math.max(this.sceneHelper.getFocusMarkerOpacity(),0);let n=Math.min(i+.4*s,1);this.sceneHelper.setFocusMarkerOpacity(n),this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e),t=!0,this.forceRenderNextFrame()}else{let i;if(i=t?1:Math.min(this.sceneHelper.getFocusMarkerOpacity(),1),i>0){this.sceneHelper.updateFocusMarker(this.nextCameraTarget,this.camera,e);let t=Math.max(i-.12*s,0);this.sceneHelper.setFocusMarkerOpacity(t),0===t&&this.sceneHelper.setFocusMarkerVisibility(!1)}i>0&&this.forceRenderNextFrame(),t=!1}}}();updateMeshCursor=function(){const e=[],t=new p;return function(){this.showMeshCursor?(this.forceRenderNextFrame(),this.getRenderDimensions(t),e.length=0,this.raycaster.setFromCameraAndScreenPosition(this.camera,this.mousePosition,t),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 p;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 o;cameraPositionArray=[];lastSortViewDir=new a(0,0,-1);sortViewDir=new a(0,0,-1);lastSortViewPos=new a;sortViewOffset=new a;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,a=!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&&(a=!0),n||a)))return Promise.resolve(!1);this.sortRunning=!0;let{splatRenderCount:r,shouldSortAll:o}=this.gatherSceneNodesForSort();o=o||t,this.splatRenderCount=r,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 t=null;const s=new a,i=new a,n=new a,r=new o,l=new o,c=new o,h=new a,d=new a(0,0,-1),u=new a,p=e=>u.copy(e.max).sub(e.min).length();return function(a=!1){this.getRenderDimensions(h);const o=h.y/2/Math.tan(this.camera.fov/2*_.DEG2RAD),u=Math.atan(h.x/2/o),A=Math.atan(h.y/2/o),m=Math.cos(u),g=Math.cos(A),f=this.splatMesh.getSplatTree();if(f){l.copy(this.camera.matrixWorld).invert(),this.splatMesh.dynamicMode||l.multiply(this.splatMesh.matrixWorld);let t=0,o=0;for(let h=0;h<f.subTrees.length;h++){const u=f.subTrees[h];r.copy(l),this.splatMesh.dynamicMode&&(this.splatMesh.getSceneTransform(h,c),r.multiply(c));const A=u.nodesWithIndexes.length;for(let l=0;l<A;l++){const c=u.nodesWithIndexes[l];if(!c.data||!c.data.indexes||0===c.data.indexes.length)continue;n.copy(c.center).applyMatrix4(r);const h=n.length();n.normalize(),s.copy(n).setX(0).normalize(),i.copy(n).setY(0).normalize();const A=d.dot(i),f=d.dot(s),S=p(c);!a&&(A<m-.6||f<g-.6)&&h>S||(o+=c.data.indexes.length,e[t]=c,c.data.distanceToNode=h,t++)}}e.length=t,e.sort((e,t)=>e.data.distanceToNode<t.data.distanceToNode?-1:1);let h=o*$.BytesPerInt;for(let s=0;s<t;s++){const t=e[s],i=t.data.indexes.length,n=i*$.BytesPerInt;new Uint32Array(this.sortWorkerIndexesToSort.buffer,h-n,i).set(t.data.indexes),h-=n}return{splatRenderCount:o,shouldSortAll:!1}}{const e=this.splatMesh.getSplatCount();if(!t||t.length!==e){t=new Uint32Array(e);for(let s=0;s<e;s++)t[s]=s}return this.sortWorkerIndexesToSort.set(t),{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 t=[];function s(e,i=null){const n=new O;return n.name=e.name,i&&i.add(n),n.position.set(...e.position),t.push(n),e.children&&e.children.forEach(e=>s(e,n)),n}return e.forEach(e=>s(e)),t}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 a(this.bones[0].position.x,this.bones[0].position.y,this.bones[0].position.z),new a(this.bones[1].position.x,this.bones[1].position.y,this.bones[1].position.z),new a(this.bones[2].position.x,this.bones[2].position.y,this.bones[2].position.z),new a(this.bones[3].position.x,this.bones[3].position.y,this.bones[3].position.z),new a(this.bones[4].position.x,this.bones[4].position.y,this.bones[4].position.z)];this.bones[1].position.copy(new a(e[1].x-e[0].x,e[1].y-e[0].y,e[1].z-e[0].z)),this.bones[2].position.copy(new a(e[2].x-e[1].x,e[2].y-e[1].y,e[2].z-e[1].z)),this.bones[3].position.copy(new a(e[3].x-e[1].x,e[3].y-e[1].y,e[3].z-e[1].z)),this.bones[4].position.copy(new a(e[4].x-e[1].x,e[4].y-e[1].y,e[4].z-e[1].z)),this.bones[0].updateMatrixWorld(!0);const t=[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 Q(this.bones,t)}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,t=this.skinModel.geometry.attributes.skinIndex,s=this.skinModel.geometry.attributes.skinWeight,i=new d(new t.array.constructor(t.array),4,t.normalized,1),n=new d(new s.array.constructor(s.array),4,s.normalized,1);i.setUsage(u),n.setUsage(u),e.setAttribute("skinIndex",i),e.setAttribute("skinWeight",n)}}else this.updateFlameBones();this.splatMesh.morphedMesh=e;let t=this.splatMesh.morphedMesh.length/3;null!=this.splatMesh.splatDataTextures.flameModel&&this.splatMesh.updateTetureAfterBSAndSkeleton(0,t-1,this.useFlame)}updateFlameBones(){function e(e,t,s=!1){let i;if(1==s)i=new r(t[0],t[1],t[2],t[3]);else{const e=new a(t[0],t[1],t[2]),s=e.length(),n=e.normalize();i=(new r).setFromAxisAngle(n,s)}e.quaternion.copy(i),e.updateMatrixWorld(!0)}this.splatMesh.bsWeight=this.flame_params.expr[this.frame];let t=this.flame_params.rotation[this.frame];e(this.skeleton.bones[0],t),t=this.flame_params.neck_pose[this.frame],e(this.skeleton.bones[1],t),t=this.flame_params.jaw_pose[this.frame],e(this.skeleton.bones[2],t),t=this.flame_params.eyes_pose[this.frame],e(this.skeleton.bones[3],t),e(this.skeleton.bones[4],[t[3],t[4],t[5]]),this.skeleton.update();const s=this.updatedBoneMatrices(5);this.splatMesh.bonesMatrix=s,this.splatMesh.bonesNum=5,this.splatMesh.bonesWeight=this.lbs_weight_80k}}const Ts={x:0,y:1.8,z:1},ws={x:-10,y:0,z:0},Ds="ffffff",Ms="false",Es={offset:{},scale:{}},Rs={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 Fs{static _canvas="undefined"!=typeof document?document.createElement("canvas"):null;static instance=void 0;static async getInstance(e,t,s={}){if(void 0!==this.instance)return this.instance;try{const i=t,n=new URL(i,window.location.href),r=n.pathname.match(/\/([^/]+?)\.zip/);if(!(r&&r[1]))throw new Error("character model is not found");"undefined"!=typeof NProgress&&NProgress.start();const o=await fetch(i);if(!o.ok)throw new Error(`Failed to download: ${o.statusText}`);s.downloadProgress&&s.downloadProgress(1),s.loadProgress&&s.loadProgress(.1),"undefined"!=typeof NProgress&&NProgress.done();const l=await o.arrayBuffer(),c=await G.loadAsync(l);let h="";if(Object.values(c.files).forEach(e=>{e.dir&&(h=e.name?.slice(0,e.name?.length-1))}),!h)throw new Error("file folder is not found");const d=new Fs(e,c),u=new a;u.x=Ts?.x||0,u.y=Ts?.y||0,u.z=Ts?.z||1;const p=new a;p.x=ws?.x||0,p.y=ws?.y||0,p.z=ws?.z||0;let A=16777215;Ds&&(A=parseInt(Ds,16)),s?.backgroundColor&&d.isHexColorStrict(s.backgroundColor)&&(A=parseInt(s.backgroundColor,16)),d.getChatState=s?.getChatState,d.getExpressionData=s?.getExpressionData,Ms&&(d.useFlame="false"!==Ms),d.viewer=new bs({rootElement:e,threejsCanvas:Fs._canvas,cameraUp:[0,1,0],initialCameraPosition:[u.x,u.y,u.z],initialCameraRotation:[p.x,p.y,p.z],sphericalHarmonicsDegree:0,backgroundColor:A}),d.viewer.useFlame=d.useFlame,!0===d.viewer.useFlame?await d.loadFlameModel(h,Es):await d.loadModel(h,Rs,Es),s.loadProgress&&s.loadProgress(.2);const m=await d.unpackFileAsBlob(h+"/offset.ply");return s.loadProgress&&s.loadProgress(.3),await d.viewer.addSplatScene(m,{progressiveLoad:!0,sharedMemoryForWorkers:!1,showLoadingUI:!1,format:X.Ply}),d.render(),s.loadProgress&&s.loadProgress(1),this.instance=d,d}catch(e){throw console.error("GaussianSplatRenderer.getInstance error:",e),e}}constructor(e,t){if(this.zipUrls={urls:new Map,zip:t},this.useFlame=!1,this.lastTime=0,this.startTime=0,this.expressionData={},this.chatState=Xe.Idle,Fs._canvas&&e){const{width:t,height:s}=e.getBoundingClientRect();Fs._canvas.style.visibility="visible",Fs._canvas.width=t,Fs._canvas.height=s,e.appendChild(Fs._canvas)}this.clock=new N,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(){Fs._canvas&&(Fs._canvas.style.visibility="hidden"),this.disposeModel(),this.zipUrls.urls.forEach(e=>{URL.revokeObjectURL(e)}),Fs.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 a=this.viewer.shouldRender();this._renderLogCount<=3&&console.log("[GS-DEBUG] shouldRender:",a),a?(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,t){const[s,i,n,a,r]=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 o,l;s.traverse(e=>{e.isSkinnedMesh&&(o=e),e instanceof O&&"hip"===e.name&&(l=e)}),this.viewer.sortedIndexes=a,this.viewer.flame_params=n,this.viewer.lbs_weight_80k=i,this.viewer.bone_tree=r,this.viewer.totalFrames=n.expr?.length||1,o&&(this.viewer.gaussianSplatCount=o.geometry.attributes.position.count),this.viewer.avatarMesh=s,this.viewer.skinModel=o,this.viewer.boneRoot=l,this.motioncfg=t,o&&this.viewer.updateMorphTarget(o),this.viewer.threeScene.add(s),s.visible=!1,o&&o.skeleton.computeBoneTexture()}async loadModel(e,t,s){const[i,n,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 r,o;i.traverse(e=>{e.isSkinnedMesh&&(r=e),e instanceof O&&"hip"===e.name&&(o=e)}),this.viewer.sortedIndexes=a,r&&(this.viewer.gaussianSplatCount=r.geometry.attributes.position.count),this.viewer.avatarMesh=i,this.viewer.skinModel=r,this.viewer.boneRoot=o,this.mixer=new V(i),this.animManager=new rt(this.mixer,n,t),this.motioncfg=s,Array.isArray(n)&&n.length>0&&n[0].duration?this.viewer.totalFrames=Math.floor(30*n[0].duration):this.viewer.totalFrames=1,console.log("loadModel: totalFrames set to",this.viewer.totalFrames),r&&this.viewer.updateMorphTarget(r),this.viewer.threeScene.add(i),i.visible=!1,r&&r.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,s)=>{(new W).load(e,e=>{e.animations.length>0?t(e.animations):t(e.scene)},void 0,e=>{s(e)})})}}const Ps={FlameBonesCount:5,DefaultBlendshapeCount:52,FlameModelTextureSize:{width:4096,height:2048},BoneTextureSize:{width:4,height:32},BoneWeightTextureSize:{width:512,height:512}},ks=function(){const e=new Float32Array(1),t=new Int32Array(e.buffer);return function(s){return e[0]=s,t[0]}}(),Ls={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};function Us(e,t,s){const i=new p(4096,2048),n=e.geometry.attributes.position.array;let a=[];const r=n.length/3,o=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(n));const l=new Float32Array(i.x*i.y*4),c=new Uint32Array(i.x*i.y*4);for(let e=0;e<r*(o+1);e++)l[4*e+0]=a[3*e+0],l[4*e+1]=a[3*e+1],l[4*e+2]=a[3*e+2],c[4*e+0]=ks(l[4*e+0]),c[4*e+1]=ks(l[4*e+1]),c[4*e+2]=ks(l[4*e+2]);const h=new v(c,i.x,i.y,I,B);return h.internalFormat="RGBA32UI",h.needsUpdate=!0,t.uniforms.flameModelTexture.value=h,t.uniforms.flameModelTextureSize.value.copy(i),t.uniforms.gaussianSplatCount.value=s,t.uniformsNeedUpdate=!0,{data:c,texture:h,size:i,baseData:{flameModelPos:l}}}function Hs(e,t,s,i,n,a,r){if(!s)return null;const o=new p(4,32),l=new Float32Array(e),c=new Uint32Array(o.x*o.y*4);if(r){for(let e=0;e<16*t;e++)c[e]=ks(l[e]);n&&n.skeleton&&(a.uniforms.boneTexture0.value=n.skeleton.boneTexture,a.uniforms.bindMatrix.value=n.bindMatrix,a.uniforms.bindMatrixInverse.value=n.bindMatrixInverse)}for(const e in s)if(Object.hasOwn(s,e)){const n=s[e];c[i[e]+16*t]=ks(n)}const h=new v(c,o.x,o.y,I,B);return h.internalFormat="RGBA32UI",h.needsUpdate=!0,a.uniforms.boneTexture.value=h,a.uniforms.boneTextureSize.value.copy(o),a.uniformsNeedUpdate=!0,{data:c,texture:h,size:o,baseData:{boneMatrix:c}}}function _s(e,t,s,i,n,a,r,o=!1){if(i&&n){if(o){const i=new Float32Array(t);for(let t=0;t<16*s;t++)e.baseData.boneMatrix[t]=ks(i[t])}for(const t in i)if(Object.hasOwn(i,t)){const a=i[t],r=n[t];e.baseData.boneMatrix[r+16*s]=ks(a)}e.boneMatrix.texture.data=e.baseData.boneMatrix,e.boneMatrix.texture.needsUpdate=!0,r.uniforms.boneTexture.value=e.boneMatrix.texture,a.skeleton&&(r.uniforms.boneTexture0.value=a.skeleton.boneTexture,r.uniforms.bindMatrix.value=a.bindMatrix,r.uniforms.bindMatrixInverse.value=a.bindMatrixInverse),r.uniformsNeedUpdate=!0}}function zs(e,t,s){const i=e.geometry.attributes.position.array.length/3,n=new p(512,512),a=new Float32Array(n.x*n.y*4),r=new Uint32Array(n.x*n.y*4);for(let e=0;e<i;e++)a[8*e+0]=t[e][0],a[8*e+1]=t[e][1],a[8*e+2]=t[e][2],a[8*e+3]=t[e][3],a[8*e+4]=t[e][4],r[8*e+0]=ks(t[e][0]),r[8*e+1]=ks(t[e][1]),r[8*e+2]=ks(t[e][2]),r[8*e+3]=ks(t[e][3]),r[8*e+4]=ks(t[e][4]);const o=new v(r,n.x,n.y,I,B);return o.internalFormat="RGBA32UI",o.needsUpdate=!0,s.uniforms.boneWeightTexture.value=o,s.uniforms.boneWeightTextureSize.value.copy(n),s.uniformsNeedUpdate=!0,{data:r,texture:o,size:n,baseData:{boneWeight:r}}}function Qs(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 Os={buildModelTexture:Us,buildBoneMatrixTexture:Hs,updateBoneMatrixTexture:_s,buildBoneWeightTexture:zs,getUpdatedBoneMatrices:Qs};class Ns{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 t=[],s=(e,i=null)=>{const n=new O;n.name=e.name||`bone_${this.bones.length}`,e.position&&n.position.fromArray(e.position),e.rotation&&n.rotation.fromArray(e.rotation),e.scale&&n.scale.fromArray(e.scale),i&&i.add(n),this.bones.push(n);const a=new o;e.inverseBindMatrix?a.fromArray(e.inverseBindMatrix):(n.updateMatrixWorld(!0),a.copy(n.matrixWorld).invert()),t.push(a),e.children&&e.children.forEach(e=>s(e,n))};Array.isArray(e)?(e.forEach((e,s)=>{const i=new O;i.name=e.name||`bone_${s}`,e.position&&i.position.fromArray(e.position),this.bones.push(i);const n=new o;e.inverseBindMatrix&&n.fromArray(e.inverseBindMatrix),t.push(n)}),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&&s(e.root),this.skeleton=new Q(this.bones,t)}setBoneRotation(e,t,s=!1){let i;if(s)i=new r(t[0],t[1],t[2],t[3]);else{const e=new a(t[0],t[1],t[2]),s=e.length(),n=e.normalize();i=(new r).setFromAxisAngle(n,s)}e.quaternion.copy(i),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 a=this.flameParams.eyes_pose[e];this.setBoneRotation(this.skeleton.bones[3],a),this.setBoneRotation(this.skeleton.bones[4],[a[3],a[4],a[5]]),this.skeleton.update();return{bsWeight:t,bonesMatrix:Os.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}}export{Ze as ARKIT_BLENDSHAPES_COUNT,Je as ARKitBlendshapes,ye as AbortedPromiseError,rt as AnimationManager,je as BASE_COMPONENT_COUNT,se as CENTER_COLORS_ELEMENTS_PER_SPLAT,le as CENTER_COLORS_ELEMENTS_PER_TEXEL,Ae as CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION,te as COVARIANCES_ELEMENTS_PER_SPLAT,ne as COVARIANCES_ELEMENTS_PER_TEXEL_ALLOCATED,re as COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_ALLOCATED,ae as COVARIANCES_ELEMENTS_PER_TEXEL_COMPRESSED_STORED,ie as COVARIANCES_ELEMENTS_PER_TEXEL_STORED,$ as Constants,Le as DefaultSphericalHarmonics8BitCompressionHalfRange,ee as DefaultSphericalHarmonics8BitCompressionRange,yt as DirectLoadError,$e as FLAME_BONES_COUNT,ge as FOCUS_MARKER_FADE_IN_SPEED,fe as FOCUS_MARKER_FADE_OUT_SPEED,Nt as FieldSize,Ot as FieldSizeStringMap,Ns as FlameAnimator,Ye as FlameBoneNames,Ps as FlameConstants,Os as FlameTextureManager,Fs as GaussianSplatRenderer,tt as Hello,Ss as Hit,hs as INRIAV1PlyParser,st as Idle,Se as InternalLoadType,it as Listen,Ce as LoaderStatus,xe as LoaderUtils,K as LogLevel,pe as MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT,me as MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER,Pt as PlyFormat,ps as PlyLoader,ds as PlyParser,Vt as PlyParserUtils,fs as Ray,Cs as Raycaster,j as RenderMode,oe as SCALES_ROTATIONS_ELEMENTS_PER_TEXEL,he as SCENE_FADEIN_RATE_FAST,de as SCENE_FADEIN_RATE_GRADUAL,ce as SCENE_INDEXES_ELEMENTS_PER_TEXEL,X as SceneFormat,Y as SceneRevealMode,Ee as Semver,at as Speak,Et as SplatBuffer,Ft as SplatBufferGenerator,lt as SplatGeometry,dt as SplatMaterial,pt as SplatMaterial2D,ut as SplatMaterial3D,xt as SplatMesh,Rt as SplatPartitioner,Z as SplatRenderMode,ot as SplatScene,ht as SplatTree,et as State,ue as THREE_CAMERA_FOV,Xe as TYVoiceChatState,Ls as TextureConstants,nt as Think,vt as UncompressedSplatArray,bs as Viewer,Me as abortablePromiseWithExtractedComponents,Hs as buildBoneMatrixTexture,zs as buildBoneWeightTexture,Us as buildModelTexture,Ie as clamp,Ne as convertBetweenCompressionLevels,Ve as copyBetweenBuffers,Oe as dataViewFloatForCompressionLevel,Te as delayedExecute,be as disposeAllMeshes,ve as fetchWithProgress,We as floatToHalf,ke as fromHalfFloat,ze as fromHalfFloatToUint8,_e as fromUint8,Qe as fromUint8ToHalfFloat,Be as getCurrentTime,Fe as getIOSSemever,we as getSphericalHarmonicsComponentCountForDegree,Qs as getUpdatedBoneMatrices,Re as isIOS,De as nativePromiseWithExtractedComponents,Ke as rgbaArrayToInteger,qe as rgbaToInteger,J as sceneFormatFromPath,Pe as toHalfFloat,He as toUint8,Ue as toUncompressedFloat,Ge as uintEncodedFloat,_s as updateBoneMatrixTexture};
2
- //# sourceMappingURL=gsplat-flame-avatar.esm.min.js.map