@margoengine/splats 0.0.0-stage → 1.0.0

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 (58) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +546 -2
  4. package/dist/animate.d.ts +138 -0
  5. package/dist/animate.js +31 -0
  6. package/dist/brush.d.ts +148 -0
  7. package/dist/brush.js +36 -0
  8. package/dist/compat-CDoDsXE8.js +19 -0
  9. package/dist/compat.d.ts +7 -0
  10. package/dist/compressed-Bfvhv63J.js +1 -0
  11. package/dist/compressed.d.ts +40 -0
  12. package/dist/data-BDt3mxGg.js +2 -0
  13. package/dist/data.d.ts +28 -0
  14. package/dist/data.js +1 -0
  15. package/dist/depth.d.ts +42 -0
  16. package/dist/depth.js +14 -0
  17. package/dist/edit.d.ts +48 -0
  18. package/dist/encode-BfG7xkVn.js +1 -0
  19. package/dist/encode.d.ts +40 -0
  20. package/dist/formats.d.ts +24 -0
  21. package/dist/formats.js +5 -0
  22. package/dist/index.d.ts +182 -0
  23. package/dist/index.js +1 -0
  24. package/dist/lighting.d.ts +89 -0
  25. package/dist/lighting.js +48 -0
  26. package/dist/lod-sog.d.ts +44 -0
  27. package/dist/lod-sog.js +1 -0
  28. package/dist/lod.d.ts +129 -0
  29. package/dist/lod.js +4 -0
  30. package/dist/modify.d.ts +83 -0
  31. package/dist/modify.js +24 -0
  32. package/dist/pick.d.ts +75 -0
  33. package/dist/pick.js +14 -0
  34. package/dist/ply.d.ts +62 -0
  35. package/dist/progressive.d.ts +37 -0
  36. package/dist/progressive.js +5 -0
  37. package/dist/scene-scope-C5HWuOIb.js +4 -0
  38. package/dist/session.d.ts +127 -0
  39. package/dist/session.js +1 -0
  40. package/dist/set.d.ts +59 -0
  41. package/dist/set.js +4 -0
  42. package/dist/shader-B7zZyYz-.js +64 -0
  43. package/dist/shader.d.ts +17 -0
  44. package/dist/shared/fog.d.ts +33 -0
  45. package/dist/shared/pass.d.ts +53 -0
  46. package/dist/sog-TlM17j4y.js +1 -0
  47. package/dist/sog.d.ts +20 -0
  48. package/dist/sort.d.ts +4 -0
  49. package/dist/spz-ivoWSN9h.js +1 -0
  50. package/dist/spz.d.ts +23 -0
  51. package/dist/src-BxooDRB9.js +48 -0
  52. package/dist/view-DyJeX8rJ.js +1 -0
  53. package/dist/view-rect-G-t2gTqO.js +1 -0
  54. package/dist/webp.d.ts +11 -0
  55. package/dist/zip-Cgj7EvkG.js +1 -0
  56. package/dist/zip.d.ts +7 -0
  57. package/dist/zstd-BPbUkXlY.js +1 -0
  58. package/package.json +105 -4
package/dist/edit.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { type SplatData } from './data.js';
2
+ /** A region of {@link cropSplats}: an axis-aligned box or a sphere, world units. */
3
+ export type SplatRegion = {
4
+ box: {
5
+ min: readonly [number, number, number];
6
+ max: readonly [number, number, number];
7
+ };
8
+ } | {
9
+ sphere: {
10
+ center: readonly [number, number, number];
11
+ radius: number;
12
+ };
13
+ };
14
+ /**
15
+ * The splats for which `keep(index, data)` returns true, as a new cloud (SH included).
16
+ * @throws RangeError when nothing is kept or `data` is invalid.
17
+ */
18
+ export declare function filterSplats(data: SplatData, keep: (index: number, data: SplatData) => boolean): SplatData;
19
+ /**
20
+ * The splats whose centres lie inside `region` (or outside it, with `invert`): crop a capture to its subject or cut
21
+ * away a floater. Returns a new cloud.
22
+ * @throws RangeError for an invalid region or when no splat is left.
23
+ */
24
+ export declare function cropSplats(data: SplatData, region: SplatRegion, options?: {
25
+ invert?: boolean;
26
+ }): SplatData;
27
+ /**
28
+ * The cloud moved by a 4x4 affine `matrix` (column-major, as Margo's math and glTF use): positions by the matrix,
29
+ * covariances by its linear part (A Σ Aᵀ, so scale and shear stretch the splats), and spherical harmonics turned by
30
+ * the matrix's rotation (from its polar decomposition), so view-dependent colour follows the turn. Returns a new cloud.
31
+ * @throws RangeError for a matrix that is not 16 finite numbers with an invertible linear part.
32
+ */
33
+ export declare function transformSplats(data: SplatData, matrix: ArrayLike<number>): SplatData;
34
+ /**
35
+ * One cloud from several (a scan in parts, a prop placed in a capture). The clouds must all have spherical harmonics
36
+ * of the same degree or none.
37
+ * @throws RangeError for an empty list, mixed SH degrees, or more than 3,000,000 splats in all.
38
+ */
39
+ export declare function mergeSplats(...clouds: SplatData[]): SplatData;
40
+ /**
41
+ * A coarser level of detail: the splats of each `cellSize` grid cell merge into one Gaussian with the same weighted
42
+ * mean and second moment (covariance of the mixture), weighted by opacity times volume. Colour, opacity and SH are
43
+ * the weighted means. Use it for distant views or a quick preview; `cellSize` sets the detail kept.
44
+ * @throws RangeError for a cellSize that is not a positive finite number.
45
+ */
46
+ export declare function decimateSplats(data: SplatData, options: {
47
+ cellSize: number;
48
+ }): SplatData;
@@ -0,0 +1 @@
1
+ import{c as e}from"./data-BDt3mxGg.js";import{MargoError as t}from"@margoengine/math/errors";var n;function r(){n=/* @__PURE__ */ new Int32Array(2048);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;n[e]=t}for(let e=0;e<256;e++)for(let t=1;t<8;t++){let r=n[(t-1)*256+e];n[t*256+e]=r>>>8^n[r&255]}return n}function i(e,t=0){let i=n??r(),a=e.length,o=a-(a&7),s=~t,c=0;for(;c<o;c+=8)s^=e[c]|e[c+1]<<8|e[c+2]<<16|e[c+3]<<24,s=i[1792+(s&255)]^i[1536+(s>>>8&255)]^i[1280+(s>>>16&255)]^i[1024+(s>>>24)]^i[768+e[c+4]]^i[512+e[c+5]]^i[256+e[c+6]]^i[e[c+7]];for(;c<a;c++)s=i[(s^e[c])&255]^s>>>8;return~s>>>0}var a=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],o=class{constructor(){this.bytes=/* @__PURE__ */ new Uint8Array(65536),this.at=0,this.acc=0,this.have=0}write(e,t){for(this.acc|=(e&(1<<t)-1)<<this.have,this.have+=t;this.have>=8;){if(this.at===this.bytes.length){let e=new Uint8Array(this.bytes.length*2);e.set(this.bytes),this.bytes=e}this.bytes[this.at++]=this.acc&255,this.acc>>>=8,this.have-=8}}finish(){return this.have&&this.write(0,8-this.have),this.bytes.subarray(0,this.at)}};function s(e,t){let n=e.length,r=new Uint8Array(n),i=Array.from(e,e=>e);for(;;){let e=[];for(let t=0;t<n;t++)i[t]>0&&e.push(t);if(r.fill(0),e.length<2){for(let t of e)r[t]=1;return r}let a=e.slice().sort((e,t)=>i[e]-i[t]||e-t),o=a.length,s=new Float64Array(o*2),c=new Int32Array(o*2);a.forEach((e,t)=>s[t]=i[e]);let l=o,u=0,d=o,f=()=>u<o&&(d>=l||s[u]<=s[d])?u++:d++;for(;l<o*2-1;){let e=f(),t=f();s[l]=s[e]+s[t],c[e]=c[t]=l++}let p=0,m=new Uint8Array(o*2);for(let e=o*2-3;e>=0;e--)m[e]=m[c[e]]+1;if(a.forEach((e,t)=>{r[e]=m[t],p=Math.max(p,m[t])}),p<=t)return r;for(let t of e)i[t]=Math.max(1,i[t]>>1)}}function c(e){let t=/* @__PURE__ */ new Uint32Array(16),n=/* @__PURE__ */ new Uint32Array(16),r=new Uint32Array(e.length);for(let n of e)n&&t[n]++;for(let e=1,r=0;e<16;e++)n[e]=r,r=r+t[e]<<1;for(let t=0;t<e.length;t++){let i=e[t];if(!i)continue;let a=n[i]++,o=0;for(let e=0;e<i;e++)o=o<<1|a&1,a>>=1;r[t]=o}return r}function l(e,t){let n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);if(n.length||n.push(0),n.length<=2&&n[n.length-1]<256){e.write(1,1),e.write(n.length-1,1);let r=n[0]>1;e.write(+r,1),e.write(n[0],r?8:1),n.length===2&&e.write(n[1],8);let i=new Uint8Array(t.length);return n.length===2&&(i[n[0]]=i[n[1]]=1),{lengths:i,codes:c(i)}}let r=s(t,15),i=/* @__PURE__ */ new Uint32Array(19);for(let e of r)i[e]++;i.filter(e=>e).length<2&&i[+!!i[0]]++;let o=s(i,7),l=c(o),u=19;for(;u>4&&!o[a[u-1]];)u--;e.write(0,1),e.write(u-4,4);for(let t=0;t<u;t++)e.write(o[a[t]],3);e.write(0,1);for(let t of r)e.write(l[t],o[t]);return{lengths:r,codes:c(r)}}function u(e,t,n){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1||t>16384||n>16384)throw RangeError(`A lossless WebP must be 1 to 16,384 pixels on each side; split the texture`);if(e.length!==t*n*4)throw RangeError(`A lossless WebP needs 4 bytes per pixel; pass width x height x 4`);let r=[/* @__PURE__ */ new Uint32Array(280),/* @__PURE__ */ new Uint32Array(256),/* @__PURE__ */ new Uint32Array(256),/* @__PURE__ */ new Uint32Array(256)],i=!0;for(let t=0;t<e.length;t+=4)r[0][e[t+1]]++,r[1][e[t]]++,r[2][e[t+2]]++,r[3][e[t+3]]++,e[t+3]!==255&&(i=!1);let a=new o;a.write(47,8),a.write(t-1,14),a.write(n-1,14),a.write(+!i,1),a.write(0,3),a.write(0,1),a.write(0,1),a.write(0,1);let[s,c,u,d]=r.map(e=>l(a,e));l(a,/* @__PURE__ */ new Uint32Array(40));for(let t=0;t<e.length;t+=4)a.write(s.codes[e[t+1]],s.lengths[e[t+1]]),a.write(c.codes[e[t]],c.lengths[e[t]]),a.write(u.codes[e[t+2]],u.lengths[e[t+2]]),a.write(d.codes[e[t+3]],d.lengths[e[t+3]]);let f=a.finish(),p=f.length+(f.length&1),m=new Uint8Array(20+p),h=new DataView(m.buffer);return m.set([82,73,70,70],0),h.setUint32(4,12+p,!0),m.set([87,69,66,80,86,80,56,76],8),h.setUint32(16,f.length,!0),m.set(f,20),m}var d={0:0,3:1,8:2,15:3};async function f(t,n={}){let r=e(t),i=r.count,a=r.rest?r.rest.length/i:0;if(a>45||r.alphas.some(e=>e>1))throw RangeError(`SPZ v3 stores SH through degree 3 and opacity through 1; use SOG for this cloud`);let o=0;for(let e of r.positions)o=Math.max(o,Math.abs(e));let s=2**23-1,c=n.fractionalBits??Math.max(0,Math.min(16,Math.floor(Math.log2(s/Math.max(o,1e-30)))));if(!Number.isInteger(c)||c<0||c>23)throw RangeError(`SPZ fractionalBits must be an integer from 0 to 23; pass a smaller value`);if(Math.round(o*2**c)>s)throw RangeError(`A coordinate of ${o} does not fit SPZ positions at ${c} fractional bits; use fewer bits`);let l=new Uint8Array(16+i*(20+a)),u=new DataView(l.buffer),f=e=>Math.min(255,Math.max(0,Math.round(e)));u.setUint32(0,1347635022,!0),u.setUint32(4,3,!0),u.setUint32(8,i,!0),l[12]=d[a/3],l[13]=c,l[14]=+!!n.antialiased;let h=16+i*9,g=h+i,_=g+i*3,v=_+i*3,y=v+i*4;for(let e=0;e<i;e++){for(let t=0;t<3;t++){let n=Math.round(r.positions[e*3+t]*2**c)&16777215,i=16+e*9+t*3;l[i]=n&255,l[i+1]=n>>8&255,l[i+2]=n>>16,l[g+e*3+t]=f((r.dc[e*3+t]*.15+.5)*255),l[_+e*3+t]=f((r.logScales[e*3+t]+10)*16)}l[h+e]=f(r.alphas[e]*255),u.setUint32(v+e*4,p(r.rotations,e),!0);for(let t=0;t<a;t++)l[y+e*a+t]=f(r.rest[e*a+t]*128+128)}return m(l)}function p(e,t){let[n,r,i,a]=e.subarray(t*4,t*4+4),o=Math.hypot(n,r,i,a),s=[r/o,i/o,a/o,n/o],c=0;for(let e=1;e<4;e++)Math.abs(s[e])>Math.abs(s[c])&&(c=e);let l=s[c]<0?-1:1,u=0;for(let e=0;e<4;e++){if(e===c)continue;let t=s[e]*l,n=Math.min(511,Math.round(Math.abs(t)/Math.SQRT1_2*511));u=u<<10|(t<0)<<9|n}return(c<<30|u)>>>0}async function m(e){if(typeof CompressionStream>`u`)throw new t(`unsupported`,`This runtime has no CompressionStream; use a current browser or Node 18+.`);let n=new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`));return new Uint8Array(await new Response(n).arrayBuffer())}function h(e){let t=Float32Array.from(e).sort(),n=t.length,r=[];for(let e=0,i=0;e<n;e++)if(e===n-1||t[e+1]-t[i]>1e-6*Math.max(Math.abs(t[i]),.001)){if(r.length>256)break;let n=0;for(let r=i;r<=e;r++)n+=t[r];r.push(n/(e-i+1)),i=e+1}let i=r.length<=256,a=i?Array.from({length:256},(e,t)=>r[Math.min(t,r.length-1)]):Array.from({length:256},(e,r)=>t[Math.min(n-1,Math.floor((r+.5)*n/256))]);for(let e=0;e<(i?0:8);e++){let e=/* @__PURE__ */ new Float64Array(256),r=/* @__PURE__ */ new Uint32Array(256);for(let i=0,o=0;i<n;i++){for(;o<255&&t[i]-a[o]>a[o+1]-t[i];)o++;e[o]+=t[i],r[o]++}for(let t=0;t<256;t++)r[t]&&(a[t]=e[t]/r[t]);a.sort((e,t)=>e-t)}let o=new Uint8Array(e.length);for(let t=0;t<e.length;t++){let n=e[t],r=0,i=255;for(;r<i;){let e=r+i+1>>1;a[e]<=n?r=e:i=e-1}o[t]=r<255&&a[r+1]-n<n-a[r]?r+1:r}return{book:a.map(e=>Math.fround(e)),index:o}}async function g(t){let n=e(t),r=n.count,i=(n.rest?.length??0)/r===72||n.alphas.some(e=>e>1),a=Math.ceil(Math.sqrt(r)),o=Math.ceil(r/a),s=()=>new Uint8Array(a*o*4).fill(255),c=s(),l=s(),f=s(),p=s(),m=s(),g=[1/0,1/0,1/0],y=[-1/0,-1/0,-1/0],b=n.positions.map(e=>Math.sign(e)*Math.log(Math.abs(e)+1));for(let e=0;e<r*3;e++)g[e%3]=Math.min(g[e%3],b[e]),y[e%3]=Math.max(y[e%3],b[e]);let x=h(n.logScales),S=h(n.dc);for(let e=0;e<r;e++){let t=e*4;for(let n=0;n<3;n++){let r=y[n]-g[n],i=r>0?Math.round((b[e*3+n]-g[n])/r*65535):0;c[t+n]=i&255,l[t+n]=i>>8,f[t+n]=x.index[e*3+n],m[t+n]=S.index[e*3+n]}m[t+3]=Math.round(i?204*Math.sqrt(n.alphas[e]):n.alphas[e]*255);let r=n.rotations.subarray(e*4,e*4+4),a=Math.hypot(r[0],r[1],r[2],r[3]);if(i){let e=r[0]<0?-1:1,n=Math.hypot(r[1],r[2],r[3]),i=n>1e-10?2/Math.PI*Math.atan2(n,r[0]*e)/n*e:0;c[t+3]=Math.round(r[1]*i*127+128),l[t+3]=Math.round(r[2]*i*127+128),f[t+3]=Math.round(r[3]*i*127+128);continue}let o=0;for(let e=1;e<4;e++)Math.abs(r[e])>Math.abs(r[o])&&(o=e);let s=r[o]<0?-1:1;for(let e=0,n=0;e<4;e++)e!==o&&(p[t+n++]=Math.round((r[e]*s/a/Math.SQRT1_2+1)*127.5));p[t+3]=252+o}let C={version:i?3:2,count:r,means:{mins:g,maxs:y,files:[`means_l.webp`,`means_u.webp`]},scales:{codebook:x.book,files:[`scales.webp`]},...i?{}:{quats:{files:[`quats.webp`]}},...i?{opacity:{max:n.alphas.reduce((e,t)=>Math.max(e,t),0)}}:{},sh0:{codebook:S.book,files:[`sh0.webp`]}},w=[[`means_l.webp`,u(c,a,o)],[`means_u.webp`,u(l,a,o)],[`scales.webp`,u(f,a,o)],[`sh0.webp`,u(m,a,o)]];if(i||w.push([`quats.webp`,u(p,a,o)]),n.rest){let e=n.rest.length/r/3,{centroids:t,labels:i,count:c}=_(n.rest,r,e*3),l=h(t),f=Math.ceil(c/64),p=new Uint8Array(64*e*f*4).fill(255),m=s();for(let t=0;t<c;t++)for(let n=0;n<e;n++)for(let r=0;r<3;r++)p[((t>>6)*64*e+(t&63)*e+n)*4+r]=l.index[(t*e+n)*3+r];for(let e=0;e<r;e++)m[e*4]=i[e]&255,m[e*4+1]=i[e]>>8,m[e*4+2]=0;C.shN={count:c,bands:e===24?4:d[e],codebook:l.book,files:[`shN_centroids.webp`,`shN_labels.webp`]},w.push([`shN_centroids.webp`,u(p,64*e,f)]),w.push([`shN_labels.webp`,u(m,a,o)])}return w.unshift([`meta.json`,new TextEncoder().encode(JSON.stringify(C))]),v(w)}function _(e,t,n){let r=new Uint16Array(t);if(t<=65536){for(let e=0;e<t;e++)r[e]=e;return{centroids:e,labels:r,count:t}}let i=new Float64Array(n);for(let r=0;r<t;r++)for(let a=0;a<n;a++)i[a]+=e[r*n+a]/t;let a=new Float64Array(n).fill(1/Math.sqrt(n));for(let r=0;r<8;r++){let r=new Float64Array(n);for(let o=0;o<t;o++){let t=0;for(let r=0;r<n;r++)t+=(e[o*n+r]-i[r])*a[r];for(let a=0;a<n;a++)r[a]+=t*(e[o*n+a]-i[a])}let o=Math.hypot(...r)||1;a=r.map(e=>e/o)}let o=new Float32Array(t);for(let r=0;r<t;r++)for(let t=0;t<n;t++)o[r]+=e[r*n+t]*a[t];let s=Uint32Array.from({length:t},(e,t)=>t).sort((e,t)=>o[e]-o[t]),c=65536,l=new Float32Array(c*n),u=new Uint32Array(c);for(let i=0;i<t;i++){let a=s[i],o=Math.floor(i*c/t);r[a]=o,u[o]++;for(let t=0;t<n;t++)l[o*n+t]+=e[a*n+t]}for(let e=0;e<c;e++)for(let t=0;t<n;t++)l[e*n+t]/=u[e]||1;return{centroids:l,labels:r,count:c}}function v(e){let t=new TextEncoder,n=e.map(([e])=>t.encode(e)),r=e.reduce((e,[,t],r)=>e+30+n[r].length+t.length+46+n[r].length,22),a=new Uint8Array(r),o=new DataView(a.buffer),s=[],c=[],l=0;e.forEach(([,e],t)=>{c.push(i(e)),s.push(l),o.setUint32(l,67324752,!0),o.setUint16(l+4,20,!0),o.setUint32(l+14,c[t],!0),o.setUint32(l+18,e.length,!0),o.setUint32(l+22,e.length,!0),o.setUint16(l+26,n[t].length,!0),a.set(n[t],l+30),a.set(e,l+30+n[t].length),l+=30+n[t].length+e.length});let u=l;return e.forEach(([,e],t)=>{o.setUint32(l,33639248,!0),o.setUint16(l+4,20,!0),o.setUint16(l+6,20,!0),o.setUint32(l+16,c[t],!0),o.setUint32(l+20,e.length,!0),o.setUint32(l+24,e.length,!0),o.setUint16(l+28,n[t].length,!0),o.setUint32(l+42,s[t],!0),a.set(n[t],l+46),l+=46+n[t].length}),o.setUint32(l,101010256,!0),o.setUint16(l+8,e.length,!0),o.setUint16(l+10,e.length,!0),o.setUint32(l+12,l-u,!0),o.setUint32(l+16,u,!0),a}export{g as encodeSog,f as encodeSpz};
@@ -0,0 +1,40 @@
1
+ import type { SplatData } from './data.js';
2
+ /** Options for {@link encodeSpz}. */
3
+ export interface EncodeSpzOptions {
4
+ /**
5
+ * Fractional bits of the 24-bit fixed-point positions (the step is 2^-bits). Default: the most that fit the cloud's
6
+ * largest coordinate, up to 16 (12, the format's usual value, holds coordinates to 2,048).
7
+ */
8
+ fractionalBits?: number;
9
+ /** Sets the header's antialiased flag (bit 0 of byte 14), for clouds trained with an anti-aliasing filter. */
10
+ antialiased?: boolean;
11
+ }
12
+ /**
13
+ * Encodes a cloud as an SPZ file (version 3: a gzip stream of a 16-byte header and the attributes), which `parseSpz`
14
+ * and SPZ version 3 readers decode. Positions are 24-bit fixed point, opacity, colour and log scale one byte each,
15
+ * rotations the smallest-three 10-bit packing and spherical harmonics one signed byte per coefficient.
16
+ * @throws RangeError when `data` fails `validateSplats`, a coordinate does not fit 24-bit fixed point at the chosen
17
+ * fractional bits, or `fractionalBits` is not 0 to 23; MargoError `'unsupported'` without `CompressionStream`.
18
+ * @example
19
+ * const bytes = await encodeSpz(await cloud.read());
20
+ */
21
+ export declare function encodeSpz(data: SplatData, options?: EncodeSpzOptions): Promise<Uint8Array<ArrayBuffer>>;
22
+ /**
23
+ * A 256-entry codebook for `values` and the nearest entry of each value: each distinct value (up to float rounding)
24
+ * its own entry when there are at most 256, else 1D k-means started at the quantiles. Entries are increasing.
25
+ */
26
+ export declare function codebook(values: Float32Array): {
27
+ book: number[];
28
+ index: Uint8Array;
29
+ };
30
+ /**
31
+ * Encodes a cloud as a bundled SOG scene (a ZIP of `meta.json` and lossless WebP textures), which
32
+ * `parseSog` decodes. Version 3 is selected for degree 4 or opacity above 1; otherwise version 2. Positions are 16-bit after a log transform within the cloud's bounds;
33
+ * log scales and base colours are 256-entry codebooks; rotations are the smallest-three in bytes; opacity is a byte;
34
+ * spherical harmonic bands are a palette of up to 65,536 entries (each splat's own when the cloud has at most that
35
+ * many, else groups along the bands' principal axis) quantised with a 256-entry codebook.
36
+ * @throws RangeError when `data` fails `validateSplats`.
37
+ * @example
38
+ * const bytes = await encodeSog(await cloud.read());
39
+ */
40
+ export declare function encodeSog(data: SplatData): Promise<Uint8Array<ArrayBuffer>>;
@@ -0,0 +1,24 @@
1
+ import { type SplatData } from './data.js';
2
+ /**
3
+ * Reads complete KSplat version 0.1 captures, compression 0 (float32), 1 (half) and 2 (half plus byte SH).
4
+ * Supports multiple sections, full and partial spatial buckets, section capacities and SH degrees 0 to 2.
5
+ * A mixed-degree file is promoted to its largest degree with zero missing higher bands.
6
+ * @throws RangeError for incomplete or inconsistent headers, counts, bucket tables or attributes.
7
+ */
8
+ export declare function parseKsplat(input: ArrayBuffer | ArrayBufferView): SplatData;
9
+ /**
10
+ * Reads SuperSplat compressed PLY: 256-splat chunks, packed position/rotation/scale/colour, optional colour ranges
11
+ * and channel-major uchar SH through degree 3. Returns ordinary linear-colour SplatData for every renderer entry.
12
+ */
13
+ export declare function parseCompressedPly(input: ArrayBuffer | ArrayBufferView): SplatData;
14
+ /** Options for encodePly. */
15
+ export interface EncodePlyOptions {
16
+ /** Standard PLY encoding. Default binary_little_endian. */
17
+ format?: 'binary_little_endian' | 'ascii';
18
+ }
19
+ /**
20
+ * Writes standard Gaussian PLY including full SH, log scales, wxyz rotation and logit opacity.
21
+ * Values retain float32 precision in binary or decimal round-trip precision in ASCII. Opacity endpoints use
22
+ * IEEE infinity logits, preserving exact 0 and 1 when read. No splats are dropped or reordered.
23
+ */
24
+ export declare function encodePly(data: SplatData, options?: EncodePlyOptions): Uint8Array<ArrayBuffer>;
@@ -0,0 +1,5 @@
1
+ import{c as e,n as t,p as n}from"./data-BDt3mxGg.js";import{MargoError as r}from"@margoengine/math/errors";var i=.2820947918;function a(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw TypeError(`Pass an ArrayBuffer or typed array containing the complete splat file`)}function o(e,t=0){if(!Number.isInteger(e)||e<1||e>3e6)throw RangeError(`Use a capture with 1 to 3,000,000 splats`);return{count:e,positions:new Float32Array(e*3),logScales:new Float32Array(e*3),rotations:new Float32Array(e*4),dc:new Float32Array(e*3),alphas:new Float32Array(e),...t?{rest:new Float32Array(e*((t+1)**2-1)*3)}:{}}}function s(e){let t=e&32768?-1:1,n=e>>>10&31,r=e&1023;return t*(n===0?r*2**-24:n===31?r?NaN:1/0:(1+r/1024)*2**(n-15))}function c(e){let t=a(e),r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<4096||t[0]!==0||t[1]!==1)throw RangeError(`Expected a complete KSplat version 0.1 file; re-export this capture`);let c=r.getUint32(4,!0),l=r.getUint32(8,!0),u=r.getUint32(16,!0),d=r.getUint16(20,!0);if(c<l||l<1||4096+c*1024>t.length||d>2||r.getUint32(12,!0)<u)throw RangeError(`KSplat section table or compression level is invalid; check the complete file`);let f=[],p=0,m=0;for(let e=0;e<l;e++){let t=4096+e*1024,n=r.getUint32(t,!0),i=r.getUint32(t+4,!0),a=r.getUint16(t+40,!0);if(n>i||i>3e6||a>2)throw RangeError(`Invalid KSplat section capacity or SH degree; re-export the capture`);p=Math.max(p,a),m+=n;let o=(d?24:44)+((a+1)**2-1)*3*(d===0?4:d===1?2:1);f.push({header:t,count:n,capacity:i,degree:a,stride:o,size:r.getUint32(t+28,!0),bucketSize:r.getUint32(t+8,!0),buckets:r.getUint32(t+12,!0),full:r.getUint32(t+32,!0),partial:r.getUint32(t+36,!0),block:r.getFloat32(t+16,!0),range:r.getUint32(t+24,!0)||32767,bucketBytes:r.getUint16(t+20,!0)})}if(m!==u)throw RangeError(`KSplat section counts disagree with its header; download the complete capture`);let h=o(u,p),g=(p+1)**2-1,_=r.getFloat32(36,!0),v=r.getFloat32(40,!0);if(d===2&&(!Number.isFinite(_)||!Number.isFinite(v)||_>v))throw RangeError(`KSplat SH range is invalid; re-export the capture`);let y=4096+c*1024,b=0;for(let e of f){let n=e.partial*4,a=y+n,o=a+e.buckets*e.bucketBytes;if(y+e.size>t.length||o+e.capacity*e.stride>y+e.size||e.size<1)throw RangeError(`KSplat section runs outside the file; download the complete capture`);let c=[];if(d){if(e.full+e.partial!==e.buckets||e.bucketSize<1||e.bucketBytes<12||!(e.block>0)||!Number.isFinite(e.block)||e.range<1)throw RangeError(`Invalid KSplat spatial bucket table; re-export this capture`);for(let t=0;t<e.buckets;t++){let n=t<e.full?e.bucketSize:r.getUint32(y+(t-e.full)*4,!0);if(n<1||n>e.bucketSize)throw RangeError(`KSplat partial bucket length is invalid; re-export this capture`);c.push(n)}if(c.reduce((e,t)=>e+t,0)!==e.capacity)throw RangeError(`KSplat bucket lengths disagree with its capacity; check the file`)}let l=0,u=c[0]??e.capacity,f=e.block/(2*e.range);for(let n=0;n<e.count;n++,b++){for(;n>=u;)u+=c[++l];let p=o+n*e.stride;for(let n=0;n<3;n++){h.positions[b*3+n]=d?r.getFloat32(a+l*e.bucketBytes+n*4,!0)+(r.getUint16(p+n*2,!0)-e.range)*f:r.getFloat32(p+n*4,!0);let o=d?s(r.getUint16(p+6+n*2,!0)):r.getFloat32(p+12+n*4,!0);if(!(o>0)||!Number.isFinite(o))throw RangeError(`KSplat axis scale must be finite and positive; re-export this capture`);h.logScales[b*3+n]=Math.log(o),h.dc[b*3+n]=(t[p+(d?20:40)+n]/255-.5)/i}h.alphas[b]=t[p+(d?23:43)]/255;for(let e=0;e<4;e++)h.rotations[b*4+e]=d?s(r.getUint16(p+12+e*2,!0)):r.getFloat32(p+24+e*4,!0);if(h.rest){let n=p+(d?24:44),i=d===0?4:d===1?2:1;for(let a=1;a<=e.degree;a++)for(let e=0;e<3;e++)for(let o=0;o<2*a+1;o++){let c=n+((a*a-1)*3+e*(2*a+1)+o)*i;h.rest[(b*g+a*a-1+o)*3+e]=d===0?r.getFloat32(c,!0):d===1?s(r.getUint16(c,!0)):_+t[c]/255*(v-_)}}}y+=e.size}if(y!==t.length)throw RangeError(`KSplat has trailing or missing sections; check the complete file`);return n(h)}var l={float:4,float32:4,uint:4,uint32:4,uchar:1,uint8:1};function u(e){let t=new TextDecoder(`latin1`).decode(e.subarray(0,65536)),n=/^end_header\r?\n/m.exec(t);if(!t.startsWith(`ply
2
+ `)&&!t.startsWith(`ply\r
3
+ `)||!n)throw RangeError(`Expected a complete PLY header under 64 KiB; check the file`);let i=n.index+n[0].length,a=t.slice(0,i);if(!/^format binary_little_endian 1\.0\r?$/m.test(a))throw new r(`unsupported`,`Compressed PLY requires binary_little_endian 1.0; re-export this capture`);let o=/* @__PURE__ */ new Map,s;for(let e of a.split(/\r?\n/)){let t=e.trim().split(/\s+/);if(t[0]===`element`){if(o.has(t[1]))throw RangeError(`PLY elements must have unique names; fix the header`);let e=Number(t[2]);if(!Number.isInteger(e)||e<0||e>3e6)throw RangeError(`PLY element count must be between 0 and 3,000,000; check the header`);s={name:t[1],count:e,stride:0,offset:0,properties:/* @__PURE__ */ new Map},o.set(t[1],s)}else if(t[0]===`property`&&s){if(!l[t[1]]||s.properties.has(t[2]))throw RangeError(`Compressed PLY needs unique scalar float, uint and uchar properties; fix the header`);s.properties.set(t[2],{offset:s.stride,type:t[1]}),s.stride+=l[t[1]]}}let c=i;for(let e of o.values())e.offset=c,c+=e.count*e.stride;if(c!==e.length)throw RangeError(`Compressed PLY byte length disagrees with its header; download the complete file`);return o}function d(e){let t=a(e),r=u(t),s=r.get(`chunk`),c=r.get(`vertex`),l=r.get(`sh`);if(!s||!c||s.count!==Math.ceil(c.count/256))throw RangeError(`Compressed PLY needs one chunk per 256 vertices; check the header`);let d=new DataView(t.buffer,t.byteOffset,t.byteLength),f=(e,n,r,i)=>{let a=e.properties.get(r);if(!a||!{float:[`float`,`float32`],uint:[`uint`,`uint32`],uchar:[`uchar`,`uint8`]}[i].includes(a.type))throw RangeError(`Compressed PLY property ${r} is missing or has the wrong type; re-export this capture`);let o=e.offset+n*e.stride+a.offset;return i===`float`?d.getFloat32(o,!0):i===`uint`?d.getUint32(o,!0):t[o]},p=l?l.properties.size/3:0,m=Math.sqrt(p+1)-1;if(![0,1,2,3].includes(m)||l&&l.count!==c.count)throw RangeError(`Compressed PLY SH needs 9, 24 or 45 bytes per vertex; check the sh element`);let h=o(c.count,m),g=s.properties.has(`min_r`),_=(e,t)=>t===0?(e>>>21)/2047:t===1?(e>>>11&1023)/1023:(e&2047)/2047,v=(e,t,n)=>e+(t-e)*n;for(let e=0;e<c.count;e++){let t=Math.floor(e/256),n=f(c,e,`packed_position`,`uint`),r=f(c,e,`packed_scale`,`uint`),a=f(c,e,`packed_rotation`,`uint`),o=f(c,e,`packed_color`,`uint`);for(let a=0;a<3;a++){let c=[`x`,`y`,`z`][a],l=f(s,t,`min_${c}`,`float`),u=f(s,t,`max_${c}`,`float`),d=f(s,t,`min_scale_${c}`,`float`),p=f(s,t,`max_scale_${c}`,`float`);if(![l,u,d,p].every(Number.isFinite)||u<l||p<d)throw RangeError(`Compressed PLY bounds are invalid; re-export the capture`);h.positions[e*3+a]=v(l,u,_(n,a)),h.logScales[e*3+a]=v(d,p,_(r,a));let m=[`r`,`g`,`b`][a],y=g?f(s,t,`min_${m}`,`float`):0,b=g?f(s,t,`max_${m}`,`float`):1;if(!Number.isFinite(y)||!Number.isFinite(b)||y>b)throw RangeError(`Compressed PLY colour bounds are invalid; re-export the capture`);h.dc[e*3+a]=(v(y,b,(o>>>24-a*8&255)/255)-.5)/i}h.alphas[e]=(o&255)/255;let u=a>>>30,d=[0,0,0,0],m=0,y=0;for(let e=0;e<4;e++)if(e!==u){let t=((a>>>20-y++*10&1023)/1023-.5)*Math.SQRT2;d[e]=t,m+=t*t}if(d[u]=Math.sqrt(Math.max(0,1-m)),h.rotations.set(d,e*4),l&&h.rest)for(let t=0;t<3;t++)for(let n=0;n<p;n++){let r=f(l,e,`f_rest_${t*p+n}`,`uchar`);h.rest[(e*p+n)*3+t]=r===0?-4:r===255?4:((r+.5)/256-.5)*8}}return n(h)}function f(n,r={}){let i=t(n),a=r.format??`binary_little_endian`;if(a!==`binary_little_endian`&&a!==`ascii`)throw RangeError(`Choose binary_little_endian or ascii as the PLY format`);if(n.colors.some((e,t)=>t%4==3&&e>1))throw RangeError(`Gaussian PLY logit opacity cannot exceed 1; use SOG for this cloud`);let o=e(n),s=(o.rest?.length??0)/i/3,c=[`x`,`y`,`z`,`nx`,`ny`,`nz`,`f_dc_0`,`f_dc_1`,`f_dc_2`,...Array.from({length:s*3},(e,t)=>`f_rest_${t}`),`opacity`,`scale_0`,`scale_1`,`scale_2`,`rot_0`,`rot_1`,`rot_2`,`rot_3`],l=new TextEncoder().encode(`ply\nformat ${a} 1.0\nelement vertex ${i}\n${c.map(e=>`property float ${e}\n`).join(``)}end_header\n`),u=a===`binary_little_endian`?new Uint8Array(l.length+i*c.length*4):void 0,d=u?new DataView(u.buffer):void 0,f=[];u?.set(l);for(let e=0;e<i;e++){let t=[...o.positions.subarray(e*3,e*3+3),0,0,0,...o.dc.subarray(e*3,e*3+3)];if(o.rest)for(let n=0;n<3;n++)for(let r=0;r<s;r++)t.push(o.rest[(e*s+r)*3+n]);let n=o.alphas[e];if(t.push(Math.log(n/(1-n)),...o.logScales.subarray(e*3,e*3+3),...o.rotations.subarray(e*4,e*4+4)),d)for(let n=0;n<t.length;n++)d.setFloat32(l.length+(e*c.length+n)*4,t[n],!0);else f.push(t.map(e=>String(Math.fround(e))).join(` `))}if(u)return u;let p=new TextEncoder().encode(f.join(`
4
+ `)+`
5
+ `),m=new Uint8Array(l.length+p.length);return m.set(l),m.set(p,l.length),m}export{f as encodePly,d as parseCompressedPly,c as parseKsplat};
@@ -0,0 +1,182 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
3
+ import { type SplatData } from './data.js';
4
+ import { type FogLike } from './shared/fog.js';
5
+ export type { FogLike } from './shared/fog.js';
6
+ import { type SurfaceTransparency } from './shared/pass.js';
7
+ export { parseSplat, validateSplats, type SplatData } from './data.js';
8
+ export { parsePly, encodeSplat, decomposeCovariance, splatsFromAttributes, attributesFromSplats, type GaussianAttributes, } from './ply.js';
9
+ export { parseSpz, parseSog, encodeSpz, encodeSog, type ParseSpzOptions, type ParseSogOptions, type SogFiles, type EncodeSpzOptions, } from './compressed.js';
10
+ export { cropSplats, filterSplats, transformSplats, mergeSplats, decimateSplats, type SplatRegion } from './edit.js';
11
+ type Context = Extract<PassContext, {
12
+ backend: 'webgpu';
13
+ }>;
14
+ /**
15
+ * A Gaussian splat cloud: GPU projection to screen ellipses, an 8-pass radix depth sort and far-to-near blending
16
+ * against the scene depth, every frame with no CPU sorting. `Splats.attach(engine, data)`; WebGPU only.
17
+ * @throws TypeError / RangeError from the constructor when `data` is invalid (see `validateSplats`); RangeError when
18
+ * attaching a cloud that exceeds the adapter's compute or storage limits.
19
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` from `gpuState`
20
+ * before the cloud is attached.
21
+ */
22
+ export declare class Splats implements EnginePlugin {
23
+ readonly name: string;
24
+ readonly count: number;
25
+ private readonly positions;
26
+ private readonly covariances;
27
+ private readonly colors;
28
+ private readonly sh;
29
+ private engine?;
30
+ private device?;
31
+ private buffers;
32
+ private inputs;
33
+ private uniform?;
34
+ private fadeData?;
35
+ private fadeBuffer?;
36
+ private index?;
37
+ private projected?;
38
+ private evaluated?;
39
+ private keys;
40
+ private projection?;
41
+ private projectionGroup?;
42
+ private projectionBuffers;
43
+ private fogSource;
44
+ private fogged?;
45
+ private readonly fogData;
46
+ private sortPipelines;
47
+ private sortGroups;
48
+ private compatSort?;
49
+ private routeReady;
50
+ private renders;
51
+ private disposed;
52
+ private mip;
53
+ private writes;
54
+ private readonly transparency;
55
+ private readonly attachment;
56
+ private readonly plainDepth;
57
+ private readonly stencilDepth;
58
+ private readonly presentation;
59
+ private record?;
60
+ private recordSamples?;
61
+ private recordFormat?;
62
+ private recordDepth?;
63
+ private readonly values;
64
+ private readonly integers;
65
+ private readonly view;
66
+ constructor(data: SplatData);
67
+ /**
68
+ * A cloud of `count` hidden splats (opacity 0) with `coefficients` SH coefficients per channel (0, 4, 9, 16 or 25), to
69
+ * fill later with `write`: a pool for streamed or edited splats. Hidden splats are culled before the sort.
70
+ * @throws RangeError for a count outside 1 to 3,000,000 or another coefficient count.
71
+ */
72
+ static reserve(count: number, coefficients?: number): Splats;
73
+ /** SH coefficients per channel: 0, 4, 9, 16 or 25. */
74
+ get coefficients(): number;
75
+ /**
76
+ * Replaces splats `first` to `first + n - 1` with the `n` splats of `data` (same SH coefficient count as the cloud),
77
+ * in the copy kept for device restoration and, when attached, on the GPU before the next frame.
78
+ * @throws RangeError when `data` is invalid, has another SH coefficient count or does not fit; MargoError
79
+ * `'disposed'` after `dispose()`.
80
+ */
81
+ write(first: number, data: SplatData): this;
82
+ /**
83
+ * Hides splats `first` to `first + count - 1` (opacity 0), as `write` would.
84
+ * @throws RangeError when the range does not fit; MargoError `'disposed'` after `dispose()`.
85
+ */
86
+ clear(first: number, count: number): this;
87
+ /**
88
+ * Sets the opacity of splats `first` to `first + alphas.length - 1` to `alphas[i] * scale`, uploading only their
89
+ * positions and colours (32 of the 128 bytes a splat takes), not covariances or SH: a cheap fade or hide of a range
90
+ * whose own opacities you keep. `scale` 0 hides them (culled before the sort).
91
+ * @throws RangeError when the range does not fit or `scale` is outside 0 to 1; MargoError `'disposed'` after `dispose()`.
92
+ */
93
+ setOpacities(first: number, alphas: Float32Array, scale?: number): this;
94
+ private range;
95
+ private upload;
96
+ /** GPU bytes of the optional per-splat screen-door intervals; zero until enabled. */
97
+ get ditherFadeBytes(): number;
98
+ /** Sets coverage [lower,upper] for an original-order content range. Default full coverage; no opacity or sort edits. */
99
+ setDitherFade(first: number, count: number, lower?: number, upper?: number): this;
100
+ private prepareFade;
101
+ /**
102
+ * The cloud as data, after any edits or poses made on the GPU (`./edit`, `./animate`): when attached, centres,
103
+ * covariances, opacities, colours and SH are read back into the copy kept for device restoration first. For export
104
+ * (`encodeSplat`, `encodeSpz`, `encodeSog`) and to keep GPU edits through a device loss.
105
+ * @throws MargoError `'disposed'` after `dispose()`; the GPU's error when the device is lost during the read.
106
+ */
107
+ read(): Promise<SplatData>;
108
+ /**
109
+ * Anti-aliasing (Mip-Splatting's 2D filter): when true, each splat's opacity is scaled by
110
+ * sqrt(det(S) / det(S + 0.3 I)) of its screen covariance S, so a splat smaller than a pixel fades with its true
111
+ * coverage instead of drawing as a 0.3 px^2 blob at full opacity, and distant or small captures stop shimmering.
112
+ * Default false (the look trained 3DGS files were made with). Live: read each frame, no recompile.
113
+ */
114
+ get antialias(): boolean;
115
+ set antialias(on: boolean);
116
+ /** The fog the splats are drawn in (see `setFog`), or null. */
117
+ get fog(): FogLike | null;
118
+ /**
119
+ * Fogs the cloud: `fog` is `@margoengine/environment`'s `Fog` or any object with its fields, read every frame, with
120
+ * Fog's maths (linear near/far, exp2 density, height falloff). Each splat's colour fades toward the fog colour by the
121
+ * fog at its centre, in the projection pass (so `gpuState.colors` holds fogged colours); its opacity is unchanged.
122
+ * `null` (the default) draws exactly as without fog. The first fogged frame compiles a second projection shader;
123
+ * changing the fog or its `enabled` flag never does.
124
+ * @throws TypeError when `fog` is neither an object nor null; RangeError or TypeError for an invalid field.
125
+ */
126
+ setFog(fog: FogLike | null): this;
127
+ static attach(instance: EngineKernel, data: SplatData): Splats;
128
+ setup(engine: Engine): void;
129
+ /**
130
+ * Settles once every frame orders the splats as it will from then on. On the WebGL2 compatibility layer Splats loads
131
+ * its sort route (a dynamic import) when it attaches; until it has loaded the WebGPU radix sort runs on the layer's
132
+ * CPU tier, which orders splats of equal depth its own way. Resolved at once on WebGPU. Read it after attaching, and
133
+ * await it before a frame that must be exact: a film frame, a pixel comparison (KB-COMPAT-READY1).
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const cloud = Splats.attach(engine, data);
138
+ * await cloud.ready;
139
+ * engine.render();
140
+ * ```
141
+ */
142
+ get ready(): Promise<void>;
143
+ registerPasses(graph: FrameGraph): void;
144
+ private sort;
145
+ /** The fog uniform and the fogged projection pipeline and group, made on the first fogged frame. */
146
+ private fogResources;
147
+ private dispatch;
148
+ /** Pipeline and group 0 for this target, and for `hook` when given. */
149
+ private fadeShader;
150
+ private pipeline;
151
+ private draw;
152
+ /**
153
+ * Leaves the frame's draw (order 3) and the depth sort to an order-independent pass, which calls `drawTransparent`. Use
154
+ * `addEffect` from `@margoengine/oit/vfx`. `gpuState.sorted` then holds the keys unsorted. Returns a remover; `released`
155
+ * runs if this cloud is disposed first.
156
+ */
157
+ setTransparency(hook: SurfaceTransparency, released?: () => void): () => void;
158
+ /** Draws the cloud into `hook`'s pass, depth tested and not written. */
159
+ drawTransparent(c: Context, hook: SurfaceTransparency): void;
160
+ /** Whether the cloud is attached to a live engine, so `gpuState` holds its buffers. */
161
+ get attached(): boolean;
162
+ /**
163
+ * The cloud's GPU buffers, for entries that draw or edit it: `sorted` keys, projected `ellipses`, evaluated `colors`
164
+ * (rgb, opacity) and the inputs `positions` (xyz, opacity), `covariances` (two vec4f per splat), `inputColors` (rgb,
165
+ * opacity) and `sh` (SH coefficients, RGB interleaved; 4 unused floats without SH).
166
+ */
167
+ get gpuState(): {
168
+ sorted: GPUBuffer;
169
+ ellipses: GPUBuffer;
170
+ colors: GPUBuffer;
171
+ positions: GPUBuffer;
172
+ covariances: GPUBuffer;
173
+ inputColors: GPUBuffer;
174
+ sh: GPUBuffer;
175
+ };
176
+ private release;
177
+ onDeviceRestored(engine: Engine): void;
178
+ dispose(): void;
179
+ [Symbol.dispose]: () => void;
180
+ /** @deprecated Use dispose(); kept as an alias until 1.0. */
181
+ destroy(): void;
182
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{a as e,c as t,d as n,i as r,l as i,n as a,o,p as s,r as c,s as l,t as u,u as d}from"./data-BDt3mxGg.js";import{t as f}from"./src-BxooDRB9.js";import{i as p,n as m,r as h,t as g}from"./compressed-Bfvhv63J.js";export{f as Splats,t as attributesFromSplats,c as cropSplats,r as decimateSplats,i as decomposeCovariance,g as encodeSog,d as encodeSplat,m as encodeSpz,e as filterSplats,o as mergeSplats,n as parsePly,h as parseSog,u as parseSplat,p as parseSpz,s as splatsFromAttributes,l as transformSplats,a as validateSplats};
@@ -0,0 +1,89 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ import type { Splats } from './index.js';
5
+ /** Options of {@link SplatLighting}. */
6
+ export interface SplatLightingOptions {
7
+ /**
8
+ * Shadow coverage. Unset (the default): stochastic, a splat blocks each shadow-map texel with the probability of its
9
+ * opacity there, so a capture's many small overlapping splats shade as their combined opacity (noisy at a texel,
10
+ * smoothed by the shadow filter). A number from 0 to 1: a splat blocks where its opacity reaches it, as `./depth`
11
+ * (no noise, but a sparse capture leaves gaps). Live: `lighting.threshold`.
12
+ */
13
+ threshold?: number;
14
+ /** Relight the cloud with the scene light (false keeps its captured colours; it still casts). Default true. Live. */
15
+ relight?: boolean;
16
+ }
17
+ /** What `@margoengine/shadows` hands a custom caster for one cascade (its `ShadowContext`). */
18
+ export interface SplatShadowContext {
19
+ context: {
20
+ device: GPUDevice;
21
+ };
22
+ pass: GPURenderPassEncoder;
23
+ /** The cascade's light view-projection matrix, 16 floats, column-major. */
24
+ matrix: Float32Array;
25
+ /** Cascade index, 0 to 3. */
26
+ cascade: number;
27
+ }
28
+ /**
29
+ * WGSL of the relight pass. Uniform: eye, light (xyz toward the light, unit; w intensity), radiance (rgb; w ambient),
30
+ * ambient rgb, counts (x splats, y 1 to relight).
31
+ */
32
+ export declare const relightShader = "struct Light {eye:vec4f,light:vec4f,radiance:vec4f,ambient:vec4f,counts:vec4u}\n@group(0) @binding(0) var<uniform> u:Light;\n@group(0) @binding(1) var<storage,read> positions:array<vec4f>;\n@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;\n@group(0) @binding(3) var<storage,read_write> evaluated:array<vec4f>;\n\nfn flatAxis(m:mat3x3f,view:vec3f)->vec3f {\n let p1=m[0].y*m[0].y+m[0].z*m[0].z+m[1].z*m[1].z;let q=(m[0].x+m[1].y+m[2].z)/3.0;\n let p2=(m[0].x-q)*(m[0].x-q)+(m[1].y-q)*(m[1].y-q)+(m[2].z-q)*(m[2].z-q)+2.0*p1;let p=sqrt(p2/6.0);\n if(p<=1e-6*max(abs(q),1e-30)){return view;}\n let bm=(m-mat3x3f(vec3f(q,0,0),vec3f(0,q,0),vec3f(0,0,q)))*(1.0/p);let r=clamp(determinant(bm)*0.5,-1.0,1.0);\n let smallest=q+2.0*p*cos(acos(r)/3.0+2.0943951024);\n let s=m-mat3x3f(vec3f(smallest,0,0),vec3f(0,smallest,0),vec3f(0,0,smallest));\n let c0=cross(s[0],s[1]);let c1=cross(s[0],s[2]);let c2=cross(s[1],s[2]);\n var n=c0;if(dot(c1,c1)>dot(n,n)){n=c1;}if(dot(c2,c2)>dot(n,n)){n=c2;}\n if(dot(n,n)<1e-30){return view;}return normalize(n);\n}\n@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {\n let index=id.x;if(index>=u.counts.x||u.counts.y==0u){return;}let world=positions[index];if(world.w<=0){return;}\n let a=covariances[index*2];let b=covariances[index*2+1];let cov=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));\n let view=normalize(u.eye.xyz-world.xyz);var n=flatAxis(cov,view);if(dot(n,view)<0){n=-n;}\n let nl=max(dot(n,u.light.xyz),0.0);let e=evaluated[index];\n evaluated[index]=vec4f(e.rgb*(u.radiance.rgb*u.light.w*nl/3.14159265+u.radiance.w*u.ambient.rgb),e.a);\n}";
33
+ /**
34
+ * WGSL of the shadow caster: the colour pass's 3 sigma quad and falloff in the light's clip space, with the Jacobian
35
+ * of clip/w by position. threshold.x: the coverage threshold (negative for stochastic); threshold.yz: the colour pass's
36
+ * 0.3 px^2 dilation in shadow-map texels, so a capture's sub-texel splats still cover texels as they cover pixels.
37
+ */
38
+ export declare const shadowShader = "struct Caster {m:mat4x4f,threshold:vec4f}\n@group(0) @binding(0) var<uniform> u:Caster;\n@group(0) @binding(1) var<storage,read> positions:array<vec4f>;\n@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;\nstruct Out {@builtin(position) @invariant clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32,@location(2) @interpolate(flat) index:u32}\n@vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) index:u32)->Out {\n let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let world=positions[index];var o:Out;\n o.corner=corners[vertex];o.opacity=world.w;o.index=index;o.clip=vec4f(2,2,0,1);\n let c=u.m*vec4f(world.xyz,1);if(world.w<=0||world.w<u.threshold.x||c.w<=0){return o;}\n let a=covariances[index*2];let b=covariances[index*2+1];let cov=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));\n let rw=vec3f(u.m[0].w,u.m[1].w,u.m[2].w);\n let jx=(vec3f(u.m[0].x,u.m[1].x,u.m[2].x)-rw*(c.x/c.w))/c.w;let jy=(vec3f(u.m[0].y,u.m[1].y,u.m[2].y)-rw*(c.y/c.w))/c.w;\n let xx=dot(jx,cov*jx)+u.threshold.y;let xy=dot(jx,cov*jy);let yy=dot(jy,cov*jy)+u.threshold.z;let mid=(xx+yy)*0.5;\n let radius=sqrt(max(0.0,(xx-yy)*(xx-yy)*0.25+xy*xy));let major=max(mid+radius,0.0);let minor=max(mid-radius,0.0);\n var axis=vec2f(1,0);if(abs(xy)>1e-12){axis=normalize(vec2f(xy,major-xx));}else if(yy>xx){axis=vec2f(0,1);}\n let first=axis*(3*sqrt(major));let second=vec2f(-axis.y,axis.x)*(3*sqrt(minor));\n o.clip=vec4f(c.xy/c.w+first*o.corner.x+second*o.corner.y,c.z/c.w,1);return o;\n}\nfn hash(v:u32)->u32 {let s=v*747796405u+2891336453u;let w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}\n@fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}let alpha=min(0.99,i.opacity*exp(power));\n\n var cut=u.threshold.x;if(cut<0){let t=vec2u(i.clip.xy);cut=f32(hash(hash(hash(i.index)^t.x)^t.y)>>8u)/16777216.0;}if(alpha<cut){discard;}}";
39
+ /**
40
+ * Scene light and shadows for a splat cloud: `const lit = SplatLighting.attach(engine, cloud)` relights it with
41
+ * `engine.lighting` every frame, and `shadows.add(lit)` (a `@margoengine/shadows` `Shadows`) makes it cast on meshes.
42
+ * WebGPU only, as `Splats`.
43
+ * @throws RangeError for a threshold outside 0 to 1 (unset is stochastic); TypeError when `cloud` is not a Splats.
44
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` when attached after `dispose()`.
45
+ */
46
+ export declare class SplatLighting implements EnginePlugin {
47
+ private static next;
48
+ readonly name: string;
49
+ readonly cloud: Splats;
50
+ /** Relight with the scene light; false keeps the captured colours. */
51
+ relight: boolean;
52
+ private value;
53
+ private engine?;
54
+ private uniform?;
55
+ private casterUniform?;
56
+ private readonly data;
57
+ private readonly integers;
58
+ private readonly caster;
59
+ private compute?;
60
+ private group?;
61
+ private shadow?;
62
+ private shadows?;
63
+ private dead;
64
+ constructor(cloud: Splats, options?: SplatLightingOptions);
65
+ /** Same as `engine.use(new SplatLighting(cloud, options))`; returns it. */
66
+ static attach(engine: EngineKernel, cloud: Splats, options?: SplatLightingOptions): SplatLighting;
67
+ /** Opacity a splat must reach at a shadow-map texel to block the light (0 to 1), or undefined for stochastic. */
68
+ get threshold(): number | undefined;
69
+ set threshold(value: number | undefined);
70
+ /** True once disposed (`@margoengine/shadows` then drops it). */
71
+ get disposed(): boolean;
72
+ setup(engine: Engine): void;
73
+ registerPasses(graph: FrameGraph): void;
74
+ private light;
75
+ /**
76
+ * Called by `Shadows.add(lighting)`: the shadow map size, read each frame, sets the splats' smallest footprint there.
77
+ * Returns the remover.
78
+ */
79
+ addLighting(shadows: {
80
+ options?: {
81
+ resolution?: number | readonly [number, number];
82
+ };
83
+ }): () => void;
84
+ /** Draws the cloud's depth into one shadow cascade (the `ShadowSource` contract of `@margoengine/shadows`). */
85
+ drawShadow({ context, pass, matrix, cascade }: SplatShadowContext): void;
86
+ onDeviceRestored(engine: Engine): void;
87
+ dispose(): void;
88
+ [Symbol.dispose]: () => void;
89
+ }
@@ -0,0 +1,48 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const e=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as t}from"@margoengine/math/errors";var n=`let a=covariances[index*2];let b=covariances[index*2+1];let cov=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));`,r=`struct Light {eye:vec4f,light:vec4f,radiance:vec4f,ambient:vec4f,counts:vec4u}
5
+ @group(0) @binding(0) var<uniform> u:Light;
6
+ @group(0) @binding(1) var<storage,read> positions:array<vec4f>;
7
+ @group(0) @binding(2) var<storage,read> covariances:array<vec4f>;
8
+ @group(0) @binding(3) var<storage,read_write> evaluated:array<vec4f>;
9
+
10
+ fn flatAxis(m:mat3x3f,view:vec3f)->vec3f {
11
+ let p1=m[0].y*m[0].y+m[0].z*m[0].z+m[1].z*m[1].z;let q=(m[0].x+m[1].y+m[2].z)/3.0;
12
+ let p2=(m[0].x-q)*(m[0].x-q)+(m[1].y-q)*(m[1].y-q)+(m[2].z-q)*(m[2].z-q)+2.0*p1;let p=sqrt(p2/6.0);
13
+ if(p<=1e-6*max(abs(q),1e-30)){return view;}
14
+ let bm=(m-mat3x3f(vec3f(q,0,0),vec3f(0,q,0),vec3f(0,0,q)))*(1.0/p);let r=clamp(determinant(bm)*0.5,-1.0,1.0);
15
+ let smallest=q+2.0*p*cos(acos(r)/3.0+2.0943951024);
16
+ let s=m-mat3x3f(vec3f(smallest,0,0),vec3f(0,smallest,0),vec3f(0,0,smallest));
17
+ let c0=cross(s[0],s[1]);let c1=cross(s[0],s[2]);let c2=cross(s[1],s[2]);
18
+ var n=c0;if(dot(c1,c1)>dot(n,n)){n=c1;}if(dot(c2,c2)>dot(n,n)){n=c2;}
19
+ if(dot(n,n)<1e-30){return view;}return normalize(n);
20
+ }
21
+ @compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
22
+ let index=id.x;if(index>=u.counts.x||u.counts.y==0u){return;}let world=positions[index];if(world.w<=0){return;}
23
+ ${n}
24
+ let view=normalize(u.eye.xyz-world.xyz);var n=flatAxis(cov,view);if(dot(n,view)<0){n=-n;}
25
+ let nl=max(dot(n,u.light.xyz),0.0);let e=evaluated[index];
26
+ evaluated[index]=vec4f(e.rgb*(u.radiance.rgb*u.light.w*nl/3.14159265+u.radiance.w*u.ambient.rgb),e.a);
27
+ }`,i=`struct Caster {m:mat4x4f,threshold:vec4f}
28
+ @group(0) @binding(0) var<uniform> u:Caster;
29
+ @group(0) @binding(1) var<storage,read> positions:array<vec4f>;
30
+ @group(0) @binding(2) var<storage,read> covariances:array<vec4f>;
31
+ struct Out {@builtin(position) @invariant clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32,@location(2) @interpolate(flat) index:u32}
32
+ @vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) index:u32)->Out {
33
+ let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let world=positions[index];var o:Out;
34
+ o.corner=corners[vertex];o.opacity=world.w;o.index=index;o.clip=vec4f(2,2,0,1);
35
+ let c=u.m*vec4f(world.xyz,1);if(world.w<=0||world.w<u.threshold.x||c.w<=0){return o;}
36
+ ${n}
37
+ let rw=vec3f(u.m[0].w,u.m[1].w,u.m[2].w);
38
+ let jx=(vec3f(u.m[0].x,u.m[1].x,u.m[2].x)-rw*(c.x/c.w))/c.w;let jy=(vec3f(u.m[0].y,u.m[1].y,u.m[2].y)-rw*(c.y/c.w))/c.w;
39
+ let xx=dot(jx,cov*jx)+u.threshold.y;let xy=dot(jx,cov*jy);let yy=dot(jy,cov*jy)+u.threshold.z;let mid=(xx+yy)*0.5;
40
+ let radius=sqrt(max(0.0,(xx-yy)*(xx-yy)*0.25+xy*xy));let major=max(mid+radius,0.0);let minor=max(mid-radius,0.0);
41
+ var axis=vec2f(1,0);if(abs(xy)>1e-12){axis=normalize(vec2f(xy,major-xx));}else if(yy>xx){axis=vec2f(0,1);}
42
+ let first=axis*(3*sqrt(major));let second=vec2f(-axis.y,axis.x)*(3*sqrt(minor));
43
+ o.clip=vec4f(c.xy/c.w+first*o.corner.x+second*o.corner.y,c.z/c.w,1);return o;
44
+ }
45
+ fn hash(v:u32)->u32 {let s=v*747796405u+2891336453u;let w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}
46
+ @fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}let alpha=min(0.99,i.opacity*exp(power));
47
+
48
+ var cut=u.threshold.x;if(cut<0){let t=vec2u(i.clip.xy);cut=f32(hash(hash(hash(i.index)^t.x)^t.y)>>8u)/16777216.0;}if(alpha<cut){discard;}}`,a=class n{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(e,t={}){if(this.name=`splats-lighting:`+n.next++,this.data=/* @__PURE__ */ new Float32Array(20),this.integers=new Uint32Array(this.data.buffer),this.caster=/* @__PURE__ */ new Float32Array(20),this.dead=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatLighting needs a Splats cloud`);this.cloud=e,this.value=t.threshold===void 0?void 0:o(t.threshold),this.relight=t.relight??!0}static attach(t,r,i={}){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let a=new n(r,i);return e(t).use(a),a}get threshold(){return this.value}set threshold(e){this.value=e===void 0?void 0:o(e)}get disposed(){return this.dead}setup(e){if(this.dead||!e.gpu)throw new t(this.dead?`disposed`:`unsupported`,`SplatLighting needs WebGPU; attach a new SplatLighting to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.uniform=e.gpu.createBuffer({size:80,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:this.name,order:-6.5,execute:e=>{e.backend===`webgpu`&&this.light(e)}})}light(e){if(!this.relight||!this.cloud.attached)return;let t=this.cloud.gpuState,n=e.device;this.compute??=n.createComputePipeline({layout:`auto`,compute:{module:n.createShaderModule({code:r}),entryPoint:`main`}}),(!this.group||this.group.colors!==t.colors||this.group.positions!==t.positions)&&(this.group={group:n.createBindGroup({layout:this.compute.getBindGroupLayout(0),entries:[this.uniform,t.positions,t.covariances,t.colors].map((e,t)=>({binding:t,resource:{buffer:e}}))}),colors:t.colors,positions:t.positions});let{direction:i,radiance:a,ambient:o}=this.engine.lighting,s=this.data,c=Math.hypot(i[0],i[1],i[2])||1;s.set(e.camera.position,0);for(let e=0;e<3;e++)s[4+e]=i[e]/c;s[7]=i[3],s.set(a,8),o?s.set(o,12):s[12]=s[13]=s[14]=1,this.integers[16]=this.cloud.count,this.integers[17]=1,n.queue.writeBuffer(this.uniform,0,s);let l=e.encoder.beginComputePass();l.setPipeline(this.compute),l.setBindGroup(0,this.group.group),l.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),l.end()}addLighting(e){return this.shadows=e,()=>{this.shadows===e&&(this.shadows=void 0)}}drawShadow({context:e,pass:t,matrix:n,cascade:r}){if(this.dead||!this.cloud.attached)return;let a=this.cloud.gpuState,o=e.device;if(!this.shadow||this.shadow.positions!==a.positions||this.shadow.device!==o){this.casterUniform?.destroy(),this.casterUniform=o.createBuffer({size:1024,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let e=o.createShaderModule({code:i}),t=o.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vertex`},fragment:{module:e,entryPoint:`fragment`,targets:[]},primitive:{topology:`triangle-strip`},depthStencil:{format:`depth32float`,depthWriteEnabled:!0,depthCompare:`less-equal`}}),n=t.getBindGroupLayout(0),r=[0,1,2,3].map(e=>o.createBindGroup({layout:n,entries:[{binding:0,resource:{buffer:this.casterUniform,offset:e*256,size:80}},{binding:1,resource:{buffer:a.positions}},{binding:2,resource:{buffer:a.covariances}}]}));this.shadow={pipeline:t,groups:r,positions:a.positions,device:o}}this.caster.set(n),this.caster[16]=this.value??-1;let s=this.shadows?.options?.resolution??2048,[c,l]=typeof s==`number`?[s,s]:s;this.caster[17]=.3*(2/c)**2,this.caster[18]=.3*(2/l)**2,o.queue.writeBuffer(this.casterUniform,r*256,this.caster),t.setPipeline(this.shadow.pipeline),t.setBindGroup(0,this.shadow.groups[r]),t.draw(4,this.cloud.count)}onDeviceRestored(e){this.compute=this.group=this.shadow=this.casterUniform=void 0,this.setup(e)}dispose(){this.dead||(this.dead=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.uniform?.destroy(),this.casterUniform?.destroy(),this.uniform=this.casterUniform=this.engine=this.compute=this.group=this.shadow=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}};function o(e){if(typeof e!=`number`||!(e>=0&&e<=1))throw RangeError(`SplatLighting threshold must be 0 to 1`);return e}export{a as SplatLighting,r as relightShader,i as shadowShader};
@@ -0,0 +1,44 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { SplatData } from './data.js';
3
+ import type { SplatLodNode, SplatLodSource } from './lod.js';
4
+ /** Loading options for a streamed SOG hierarchy. */
5
+ export interface StreamedSogOptions {
6
+ /** Cancels manifest, metadata and subsequent chunk requests. */
7
+ signal?: AbortSignal;
8
+ /** Fetch implementation, for authentication or local file maps. Default global fetch. */
9
+ fetch?: typeof fetch;
10
+ /** Most decoded, idle chunks retained on the CPU. Default 2; zero retains none. */
11
+ cacheChunks?: number;
12
+ }
13
+ /**
14
+ * An abortable, lazy streamed SOG source. Spatial interior nodes hold no splats; each leaf is a chain from its
15
+ * coarsest available LOD to its finest. The environment is an unconditional sibling of the spatial tree.
16
+ * Metadata is resident; texture requests and decoded chunks are shared, with independent caller cancellation.
17
+ */
18
+ export declare class StreamedSogSource implements SplatLodSource {
19
+ readonly nodes: readonly SplatLodNode[];
20
+ /** Uniform coefficient count, promoted to the largest chunk's degree (0, 4, 9, 16 or 25). */
21
+ readonly coefficients: number;
22
+ private readonly abort;
23
+ private readonly idle;
24
+ private readonly cacheChunks;
25
+ private readonly ranges;
26
+ private readonly chunks;
27
+ private readonly fetcher;
28
+ private readonly stop?;
29
+ private readonly signal?;
30
+ private dead;
31
+ /** Use {@link loadStreamedSog}; the constructor takes validated manifest metadata. */
32
+ private constructor();
33
+ /** Loads a manifest and its small chunk metadata; no texture is fetched until `load`. */
34
+ static open(url: string | URL, options?: StreamedSogOptions): Promise<StreamedSogSource>;
35
+ /** Fetches and decodes only the chunk holding this node, then copies its storage-order run. */
36
+ load(index: number, signal: AbortSignal): Promise<SplatData>;
37
+ private acquire;
38
+ private decode;
39
+ /** Releases decoded chunks and cancels pending requests. Idempotent. */
40
+ dispose(): void;
41
+ [Symbol.dispose]: () => void;
42
+ }
43
+ /** Opens a streamed SOG v1 or pre-release manifest as a lazy {@link SplatLodSource}. */
44
+ export declare function loadStreamedSog(url: string | URL, options?: StreamedSogOptions): Promise<StreamedSogSource>;
@@ -0,0 +1 @@
1
+ import{t as e}from"./sog-TlM17j4y.js";import{MargoError as t}from"@margoengine/math/errors";var n=class n{constructor(e,t,n,r){this.abort=new AbortController,this.idle=/* @__PURE__ */ new Map,this.dead=!1,this.nodes=e,this.ranges=t,this.chunks=n,this.fetcher=r.fetch??globalThis.fetch,this.cacheChunks=r.cacheChunks??2,this.coefficients=n.reduce((e,t)=>Math.max(e,t.meta.shN?(t.meta.shN.bands+1)**2:0),0),this.signal=r.signal,this.stop=r.signal?()=>this.dispose():void 0,r.signal?.addEventListener(`abort`,this.stop,{once:!0})}static async open(e,i={}){i.signal?.throwIfAborted();let a=i.cacheChunks??2;if(!Number.isSafeInteger(a)||a<0)throw RangeError(`cacheChunks must be an integer of 0 or more; set the decoded chunk cache size`);let o=i.fetch??globalThis.fetch,s=new URL(e,globalThis.location?.href),c=await r(s,o,i.signal);if(c.version!==void 0&&c.version!==1)throw RangeError(`Unsupported streamed SOG version; export version 1`);if(!Number.isSafeInteger(c.lodLevels)||c.lodLevels<1||!Array.isArray(c.filenames)||!c.filenames.length||c.filenames.some(e=>typeof e!=`string`||!e))throw RangeError(`Invalid streamed SOG levels or filenames; supply a complete lod-meta.json`);if(c.model!==void 0&&c.model!==`antialiased`)throw new t(`unsupported`,`Streamed SOG model ${c.model} is not supported; 2D Gaussian scenes cannot be drawn here.`);let l=[...c.filenames];if(c.environment!=null){if(typeof c.environment!=`string`||!c.environment)throw RangeError(`Invalid environment path; use a SOG meta.json path`);l.push(c.environment)}let u=Array(l.length),d=0;await Promise.all(Array.from({length:Math.min(8,l.length)},async()=>{for(;d<l.length;){let e=d++,n=new URL(l[e],s),r=await o(n,{signal:i.signal});if(!r.ok)throw new t(`failed`,`SOG metadata ${n} returned HTTP ${r.status}; check the URL and server access`);let a=new Uint8Array(await r.arrayBuffer()),c=JSON.parse(new TextDecoder().decode(a));if(![2,3].includes(c.version)||!Number.isSafeInteger(c.count)||c.count<1||c.count>3e6||c.shN&&(!Number.isInteger(c.shN.bands)||c.shN.bands<1||c.shN.bands>(c.version===3?4:3)))throw RangeError(`Invalid SOG chunk version, count or SH degree; supply SOG v2 or v3 chunks`);u[e]={url:n,bytes:a,meta:c}}}));let f=[],p=[],m=c.filenames.map(()=>[]),h=Array(c.lodLevels).fill(0),g=/* @__PURE__ */ new Set,_=e=>{let{min:t,max:n}=e?.bound??{};if(!Array.isArray(t)||!Array.isArray(n)||t.length!==3||n.length!==3||t.some((e,t)=>!Number.isFinite(e)||!Number.isFinite(n[t])||e>n[t]))throw RangeError(`Invalid streamed SOG bounds; supply finite ordered xyz min/max`);return{center:t.map((e,t)=>e/2+n[t]/2),radius:Math.hypot(...n.map((e,n)=>e/2-t[n]/2))}},v=(e,t)=>{if(t>128||g.has(e))throw RangeError(`Invalid streamed SOG tree depth or cycle; supply an acyclic spatial tree`);g.add(e);let n=_(e),r=f.length;if(e.children){if(e.lods||!Array.isArray(e.children)||e.children.length!==2)throw RangeError(`A streamed SOG interior needs exactly two children and no lods; repair the manifest`);f.push({...n,count:0,error:0,children:[]}),p.push(void 0);let i=e.children.map(e=>v(e,t+1));f[r]={...n,count:0,error:0,children:i}}else{if(!e.lods||typeof e.lods!=`object`)throw RangeError(`A streamed SOG leaf needs lods; repair the manifest`);let t=Object.keys(e.lods).map(t=>{let n=Number(t),r=e.lods[t];if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n>=c.lodLevels||!r||!Number.isSafeInteger(r.file)||r.file<0||r.file>=c.filenames.length||!Number.isSafeInteger(r.offset)||r.offset<0||!Number.isSafeInteger(r.count)||r.count<1||r.offset+r.count>u[r.file].meta.count)throw RangeError(`Invalid streamed SOG LOD range; use in-bounds file, offset and count`);return m[r.file].push({...r,level:n}),h[n]+=r.count,n}).sort((e,t)=>t-e);if(!t.length)throw RangeError(`A streamed SOG leaf has no levels; supply at least one splat range`);if(c.lodErrors===!0){let n=-1/0;for(let r of[...t].reverse()){let t=e.errors?.[r];if(t===void 0||!Number.isFinite(t)||t<0||t<n)throw RangeError(`Invalid streamed SOG errors; supply non-negative non-decreasing errors for held levels`);n=t}}let r=e.lods[String(t.at(-1))].count;t.forEach((i,a)=>{let o=e.lods[String(i)],s=a===t.length-1;f.push({...n,count:o.count,error:s?0:c.lodErrors===!0?e.errors[i]:n.radius*Math.cbrt(Math.max(0,1-o.count/r)),children:s?[]:[f.length+1]}),p.push(o)})}return r};if(c.environment!=null){let e=_(c.tree);f.push({...e,count:0,error:0,children:[]}),p.push(void 0);let t=u.length-1;f.push({...e,count:u[t].meta.count,error:0,children:[]}),p.push({file:t,offset:0,count:u[t].meta.count});let n=v(c.tree,0);f[0]={...e,count:0,error:0,children:[1,n]}}else v(c.tree,0);for(let e=0;e<m.length;e++){let t=m[e].sort((e,t)=>e.offset-t.offset),n=0;for(let e of t){if(e.offset!==n||e.level!==t[0].level)throw RangeError(`SOG chunk runs must cover a single level without overlaps or gaps; repair the manifest`);n+=e.count}if(n!==u[e].meta.count)throw RangeError(`SOG chunk runs do not cover its count; repair the manifest`)}if(c.count!==void 0&&c.count!==h.reduce((e,t)=>e+t,0)||c.counts!==void 0&&(!Array.isArray(c.counts)||c.counts.length!==h.length||h.some((e,t)=>e!==c.counts[t])))throw RangeError(`Streamed SOG count totals disagree with its ranges; repair the manifest`);return i.signal?.throwIfAborted(),new n(f,p,u,i)}async load(e,n){if(n.throwIfAborted(),this.signal?.throwIfAborted(),this.dead)throw new t(`disposed`,`Streamed SOG source was disposed; open a new source`);let r=this.ranges[e];if(!Number.isInteger(e)||!this.nodes[e])throw RangeError(`Unknown streamed SOG node; use an index from nodes`);if(!r)return{positions:/* @__PURE__ */ new Float32Array,covariances:/* @__PURE__ */ new Float32Array,colors:/* @__PURE__ */ new Float32Array};let i=this.chunks[r.file],a=await this.acquire(i,n),{offset:o,count:s}=r,c=this.coefficients,l=c?new Float32Array(s*c*3):void 0,u=a.sphericalHarmonics?a.sphericalHarmonics.length/(a.positions.length/3)/3:0;if(n.throwIfAborted(),this.abort.signal.throwIfAborted(),l)for(let e=0;e<s;e++)if(u)l.set(a.sphericalHarmonics.subarray((o+e)*u*3,(o+e+1)*u*3),e*c*3);else for(let t=0;t<3;t++)l[e*c*3+t]=(a.colors[(o+e)*4+t]-.5)/.2820947918;return{positions:a.positions.slice(o*3,(o+s)*3),covariances:a.covariances.slice(o*6,(o+s)*6),colors:a.colors.slice(o*4,(o+s)*4),...l?{sphericalHarmonics:l}:{}}}async acquire(e,t){if(e.data)return this.idle.delete(e),this.idle.set(e,e.data),e.data;if(!e.pending){let t=new AbortController,n=AbortSignal.any([t.signal,this.abort.signal]);e.pending={controller:t,promise:this.decode(e,n),users:0}}let n=e.pending;n.users++;try{let r=await new Promise((e,r)=>{let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),n.promise.then(e,r).finally(()=>t.removeEventListener(`abort`,i))});if(t.throwIfAborted(),this.abort.signal.throwIfAborted(),this.cacheChunks)for(e.data=r,this.idle.delete(e),this.idle.set(e,r);this.idle.size>this.cacheChunks;){let e=this.idle.keys().next().value;e.data=void 0,this.idle.delete(e)}return r}finally{--n.users===0&&(n.controller.abort(),e.pending===n&&(e.pending=void 0))}}async decode(n,r){let i={"meta.json":n.bytes},a=/* @__PURE__ */ new Set;for(let e of Object.values(n.meta))if(e&&typeof e==`object`&&`files`in e&&Array.isArray(e.files))for(let t of e.files){if(typeof t!=`string`)throw RangeError(`Invalid SOG texture name; supply string filenames`);a.add(t)}return await Promise.all([...a].map(async e=>{let a=await this.fetcher(new URL(e,n.url),{signal:r});if(!a.ok)throw new t(`failed`,`SOG texture ${e} returned HTTP ${a.status}; check the chunk files`);i[e]=await a.arrayBuffer()})),e(i,{signal:r})}dispose(){if(!this.dead){this.dead=!0,this.abort.abort(new t(`disposed`,`Streamed SOG source was disposed; open a new source`)),this.signal?.removeEventListener(`abort`,this.stop);for(let e of this.chunks)e.data=void 0;this.idle.clear()}}[Symbol.dispose??Symbol()](){this.dispose()}};async function r(e,n,r){let i=await n(e,{signal:r});if(!i.ok)throw new t(`failed`,`Streamed SOG manifest returned HTTP ${i.status}; check ${e}`);return i.json()}function i(e,t={}){return n.open(e,t)}export{n as StreamedSogSource,i as loadStreamedSog};