@margoengine/splats 0.1.0 → 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.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +547 -443
- package/dist/animate.js +5 -5
- package/dist/brush.d.ts +58 -4
- package/dist/brush.js +3 -3
- package/dist/compressed-Bfvhv63J.js +1 -0
- package/dist/data-BDt3mxGg.js +2 -0
- package/dist/data.js +1 -1
- package/dist/depth.js +3 -3
- package/dist/{encode-BA6xu973.js → encode-BfG7xkVn.js} +1 -1
- package/dist/formats.js +2 -2
- package/dist/index.d.ts +15 -0
- package/dist/index.js +1 -1
- package/dist/lighting.js +3 -3
- package/dist/lod-sog.js +1 -1
- package/dist/lod.js +3 -3
- package/dist/modify.js +4 -4
- package/dist/pick.js +2 -2
- package/dist/progressive.js +1 -1
- package/dist/scene-scope-C5HWuOIb.js +2 -2
- package/dist/session.js +1 -1
- package/dist/set.js +3 -3
- package/dist/shared/fog.d.ts +33 -33
- package/dist/shared/pass.d.ts +53 -53
- package/dist/{sog-D0LYo48N.js → sog-TlM17j4y.js} +1 -1
- package/dist/{spz-BTy6CPTp.js → spz-ivoWSN9h.js} +1 -1
- package/dist/src-BxooDRB9.js +48 -0
- package/dist/zip-Cgj7EvkG.js +1 -0
- package/package.json +107 -107
- package/dist/data-D31W24Wu.js +0 -2
- package/dist/src-DlpBlCx1.js +0 -48
- package/dist/zip-DNluwYbe.js +0 -1
package/dist/animate.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const t=(engine,version="
|
|
4
|
-
import{n as e}from"./data-
|
|
3
|
+
const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e}from"./data-BDt3mxGg.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as n}from"@margoengine/math/errors";var r=`struct Mix {mix:vec4f,counts:vec4u}
|
|
5
5
|
@group(0) @binding(0) var<uniform> u:Mix;
|
|
6
6
|
@group(0) @binding(1) var<storage,read> a:array<vec4f>;
|
|
7
7
|
@group(0) @binding(2) var<storage,read> b:array<vec4f>;
|
|
@@ -12,7 +12,7 @@ import{n as e}from"./data-D31W24Wu.js";import{engineRuntime as __margoRuntime}fr
|
|
|
12
12
|
let i=id.x;if(i>=u.counts.x){return;}let t=u.mix.x;
|
|
13
13
|
positions[i]=mix(a[i*4],b[i*4],t);covariances[i*2]=mix(a[i*4+1],b[i*4+1],t);covariances[i*2+1]=mix(a[i*4+2],b[i*4+2],t);
|
|
14
14
|
colors[i]=mix(a[i*4+3],b[i*4+3],t);
|
|
15
|
-
}`;function i(t,n){if(e(t)!==n)throw RangeError(`Every sequence frame needs ${n} splats, as the cloud has; pass frames of the same splats`);let r=new Float32Array(n*16);for(let e=0;e<n;e++)r.set(t.positions.subarray(e*3,e*3+3),e*16),r[e*16+3]=t.colors[e*4+3],r.set(t.covariances.subarray(e*6,e*6+6),e*16+4),r.set(t.colors.subarray(e*4,e*4+4),e*16+12);return r}var a=class{coreRequirement=__margoCoreRequirement("
|
|
15
|
+
}`;function i(t,n){if(e(t)!==n)throw RangeError(`Every sequence frame needs ${n} splats, as the cloud has; pass frames of the same splats`);let r=new Float32Array(n*16);for(let e=0;e<n;e++)r.set(t.positions.subarray(e*3,e*3+3),e*16),r[e*16+3]=t.colors[e*4+3],r.set(t.covariances.subarray(e*6,e*6+6),e*16+4),r.set(t.colors.subarray(e*4,e*4+4),e*16+12);return r}var a=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t){if(this.buffers=[],this.dead=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`${t} needs a Splats cloud`);this.cloud=e}setup(e){if(this.dead||!e.gpu)throw new n(this.dead?`disposed`:`unsupported`,`Splat animation needs WebGPU; attach a new player to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu,this.uniform=this.buffer(256,GPUBufferUsage.UNIFORM)}buffer(e,t,n){let r=this.device.createBuffer({size:Math.max(16,e),usage:t|GPUBufferUsage.COPY_DST});return n&&this.device.queue.writeBuffer(r,0,n),this.buffers.push(r),r}compute(e){return this.pipeline??=this.device.createComputePipeline({layout:`auto`,compute:{module:this.device.createShaderModule({code:e}),entryPoint:`main`}})}registerPasses(e){e.add({name:this.name,order:-7.5,execute:e=>{e.backend===`webgpu`&&this.cloud.attached&&this.pose(e,!e.view?.index)}})}run(e,t){let n=e.beginComputePass();n.setPipeline(this.pipeline),n.setBindGroup(0,t),n.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),n.end()}release(){for(let e of this.buffers)e.destroy();this.buffers=[],this.uniform=this.pipeline=void 0}onDeviceRestored(e){this.release(),this.setup(e)}get disposed(){return this.dead}dispose(){this.dead||(this.dead=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=this.device=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}},o=class e extends a{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(t,n,r={}){if(super(t,`SplatSequence`),this.name=`splats-sequence:`+e.next++,this.time=0,this.speed=1,this.playing=!0,this.values=/* @__PURE__ */ new Float32Array(8),this.integers=new Uint32Array(this.values.buffer),this.groups=[],this.gpuFrames=[],!Array.isArray(n)||!n.length)throw RangeError(`SplatSequence needs one frame or more; pass a list of clouds`);let a=r.fps??30;if(!(a>0&&Number.isFinite(a)))throw RangeError(`SplatSequence fps must be above 0; pass the capture rate`);this.fps=a,this.loop=r.loop??!0,this.frames=n.map(e=>i(e,t.count))}static attach(n,r,i,a={}){__margoAssertCore(n,__margoCoreRequirement("1.0.0",import.meta.url));let o=new e(r,i,a);return t(n).use(o),o}get length(){return this.frames.length}get duration(){return this.frames.length/this.fps}advanceTime(e){e>0&&this.playing&&(this.time+=e*this.speed)}onPreUpdate(e){this.advanceTime(e)}sample(e=this.time){let t=this.frames.length,n=e*this.fps;n=this.loop?(n%t+t)%t:Math.min(Math.max(n,0),t-1);let r=Math.floor(n);return{from:r,to:this.loop?(r+1)%t:Math.min(r+1,t-1),mix:n-r}}setup(e){super.setup(e),this.gpuFrames=this.frames.map(e=>this.buffer(e.byteLength,GPUBufferUsage.STORAGE,e)),this.groups=[]}pose(e,t){let{from:n,to:i,mix:a}=this.sample(),o=this.cloud.gpuState,s=this.compute(r),c=this.groups[n*this.frames.length+i];(!c||c.positions!==o.positions)&&(c={group:this.device.createBindGroup({layout:s.getBindGroupLayout(0),entries:[this.uniform,this.gpuFrames[n],this.gpuFrames[i],o.positions,o.covariances,o.inputColors].map((e,t)=>({binding:t,resource:{buffer:e}}))}),positions:o.positions},this.groups[n*this.frames.length+i]=c),this.values[0]=a,this.integers[4]=this.cloud.count,this.device.queue.writeBuffer(this.uniform,0,this.values),this.run(e.encoder,c.group)}release(){super.release(),this.gpuFrames=[],this.groups=[]}},s=`struct Skin {counts:vec4u}
|
|
16
16
|
@group(0) @binding(0) var<uniform> u:Skin;
|
|
17
17
|
@group(0) @binding(1) var<storage,read> matrices:array<mat4x4f>;
|
|
18
18
|
@group(0) @binding(2) var<storage,read> influence:array<vec4f>;
|
|
@@ -28,4 +28,4 @@ import{n as e}from"./data-D31W24Wu.js";import{engineRuntime as __margoRuntime}fr
|
|
|
28
28
|
let a=restCovariances[i*2];let b=restCovariances[i*2+1];let s=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));
|
|
29
29
|
let l=mat3x3f(m[0].xyz,m[1].xyz,m[2].xyz);let c=l*s*transpose(l);
|
|
30
30
|
covariances[i*2]=vec4f(c[0].x,c[0].y,c[0].z,c[1].y);covariances[i*2+1]=vec4f(c[1].z,c[2].z,0,0);
|
|
31
|
-
}`,c=class e extends a{coreRequirement=__margoCoreRequirement("
|
|
31
|
+
}`,c=class e extends a{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(t,n){super(t,`SplatSkin`),this.name=`splats-skin:`+e.next++,this.stale=!0;let{joints:r,indices:i,weights:a}=n??{},o=t.count;if(!Number.isInteger(r)||r<1||r>65536)throw RangeError(`SplatSkin needs 1 to 65,536 joints; pass the joint count`);if(i?.length!==o*4||a?.length!==o*4)throw RangeError(`SplatSkin needs 4 joint indices and 4 weights per splat (${o*4} each); pass one set per splat`);this.matrices=new Float32Array(r*16);for(let e=0;e<r;e++)this.matrices[e*16]=this.matrices[e*16+5]=this.matrices[e*16+10]=this.matrices[e*16+15]=1;this.influence=new Float32Array(o*8);let s=new Uint32Array(this.influence.buffer);for(let e=0;e<o;e++){let t=0;for(let n=0;n<4;n++){let o=i[e*4+n],c=a[e*4+n];if(!Number.isInteger(o)||o<0||o>=r)throw RangeError(`SplatSkin joint index ${o} is outside 0 to ${r-1}; fix the indices`);if(!(c>=0&&Number.isFinite(c)))throw RangeError(`SplatSkin weights must be finite and 0 or more; fix the weights`);s[e*8+n]=o,t+=c}for(let n=0;n<4;n++)this.influence[e*8+4+n]=t>0?a[e*4+n]/t:0}}static attach(n,r,i){__margoAssertCore(n,__margoCoreRequirement("1.0.0",import.meta.url));let a=new e(r,i);return t(n).use(a),a}rebind(){return this.stale=!0,this}setup(e){super.setup(e),this.matrixBuffer=this.buffer(this.matrices.byteLength,GPUBufferUsage.STORAGE),this.restPositions=this.buffer(this.cloud.count*16,GPUBufferUsage.STORAGE),this.restCovariances=this.buffer(this.cloud.count*32,GPUBufferUsage.STORAGE),this.bound=void 0,this.stale=!0}pose(e){let t=this.cloud.gpuState,n=this.device,r=this.compute(s),i=this.cloud.count;if(!this.bound||this.bound.positions!==t.positions){let e=this.buffer(this.influence.byteLength,GPUBufferUsage.STORAGE,this.influence);this.bound={group:n.createBindGroup({layout:r.getBindGroupLayout(0),entries:[this.uniform,this.matrixBuffer,e,this.restPositions,this.restCovariances,t.positions,t.covariances].map((e,t)=>({binding:t,resource:{buffer:e}}))}),positions:t.positions},this.stale=!0}this.stale&&=(e.encoder.copyBufferToBuffer(t.positions,0,this.restPositions,0,i*16),e.encoder.copyBufferToBuffer(t.covariances,0,this.restCovariances,0,i*32),!1),n.queue.writeBuffer(this.uniform,0,new Uint32Array([i,0,0,0])),n.queue.writeBuffer(this.matrixBuffer,0,this.matrices),this.run(e.encoder,this.bound.group)}release(){super.release(),this.matrixBuffer=this.restPositions=this.restCovariances=this.bound=void 0}};export{o as SplatSequence,c as SplatSkin,r as sequenceShader,s as skinShader};
|
package/dist/brush.d.ts
CHANGED
|
@@ -29,12 +29,24 @@ export type BrushTarget = BrushRegion | 'selection' | 'all';
|
|
|
29
29
|
* 1 rect, 2 selection, 3 all; w SH coefficients per channel).
|
|
30
30
|
*/
|
|
31
31
|
export declare const brushShader = "struct Brush {view:mat4x4f,region:vec4f,color:vec4f,params:vec4f,counts:vec4u}\nstruct Ellipse {center:vec4f,axes:vec4f}\n@group(0) @binding(0) var<uniform> u:Brush;\n@group(0) @binding(1) var<storage,read> ellipses:array<Ellipse>;\n@group(0) @binding(2) var<storage,read_write> positions:array<vec4f>;\n@group(0) @binding(3) var<storage,read_write> colors:array<vec4f>;\n@group(0) @binding(4) var<storage,read_write> sh:array<f32>;\n@group(0) @binding(5) var<storage,read_write> mask:array<u32>;\n@group(0) @binding(6) var<storage,read_write> result:array<atomic<u32>,2>;\nfn drawn(i:u32)->bool {let e=ellipses[i];return positions[i].w>0&&e.center.w>0&&any(e.axes!=vec4f(0));}\nfn inside(i:u32)->bool {\n let t=u.counts.z;if(t==3u){return true;}if(t==2u){return mask[i]!=0u;}if(!drawn(i)){return false;}\n let c=ellipses[i].center;let p=vec2f((c.x+1)*0.5*u.params.y,(1-c.y)*0.5*u.params.z);\n if(t==0u){let d=p-u.region.xy;return dot(d,d)<=u.region.z*u.region.z;}return all(p>=u.region.xy)&&all(p<=u.region.zw);\n}\n@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {\n let i=id.x;if(i>=u.counts.x){return;}let op=u.counts.y;\n if(op<=2u){let hit=inside(i);if(op==0u){mask[i]=u32(hit);}else if(hit){mask[i]=u32(op==1u);}return;}\n if(op==3u){if(inside(i)){positions[i].w=0;colors[i].a=0;}return;}\n if(op==4u){\n if(positions[i].w<=0||!inside(i)){return;}let s=u.color.a;let c=colors[i];colors[i]=vec4f(mix(c.rgb,u.color.rgb,s),c.a);\n let k=u.counts.w;if(k==0u){return;}let at=i*k*3;let dc=vec3f(sh[at],sh[at+1],sh[at+2]);\n let n=(mix(vec3f(0.5)+0.2820947918*dc,u.color.rgb,s)-vec3f(0.5))/0.2820947918;sh[at]=n.x;sh[at+1]=n.y;sh[at+2]=n.z;\n for(var j=3u;j<k*3u;j++){sh[at+j]*=1-s;}return;\n }\n if(!drawn(i)){return;}let e=ellipses[i];\n let d=vec2f(2*(u.region.x+0.5)/u.params.y-1,1-2*(u.region.y+0.5)/u.params.z)-e.center.xy;\n let a=dot(d,e.axes.xy)/dot(e.axes.xy,e.axes.xy);let b=dot(d,e.axes.zw)/dot(e.axes.zw,e.axes.zw);let power=-4.5*(a*a+b*b);\n if(power<-4.5||min(0.99,e.center.w*exp(power))<u.params.x){return;}\n\n let bits=bitcast<u32>(-(u.view*vec4f(positions[i].xyz,1)).z);let key=select(bits^0x80000000u,~bits,(bits>>31u)==1u);\n if(op==5u){atomicMin(&result[0],key);}else if(key==atomicLoad(&result[0])){atomicMin(&result[1],i);}\n}";
|
|
32
|
+
/** Options of a {@link SplatBrush}. */
|
|
33
|
+
export interface SplatBrushOptions {
|
|
34
|
+
/**
|
|
35
|
+
* How many strokes `undo` can take back, 0 or more; the oldest is dropped past it. Each kept stroke holds a GPU copy
|
|
36
|
+
* of what it changed: 32 bytes a splat for an erase, 16 bytes plus the SH (4 bytes per coefficient) for a paint.
|
|
37
|
+
* Default 32.
|
|
38
|
+
*/
|
|
39
|
+
readonly history?: number;
|
|
40
|
+
}
|
|
32
41
|
/**
|
|
33
42
|
* GPU picking and brush editing of a splat cloud: `const brush = SplatBrush.attach(engine, cloud)`, then
|
|
34
43
|
* `await brush.pick(x, y)`, `brush.select(region)`, `brush.erase('selection')` or `brush.paint(region, [1, 0, 0])`
|
|
35
44
|
* in pixels of the last drawn frame. Edits change the cloud's GPU buffers at once (shown from the next frame);
|
|
36
45
|
* `await brush.commit()` copies them into the cloud's data (`Splats.read`), which export and device restoration use.
|
|
37
|
-
*
|
|
46
|
+
* Erase and paint keep a stroke history on the GPU: edits between `beginStroke()` and `endStroke()` are one stroke (an
|
|
47
|
+
* edit outside a stroke is a stroke of its own), `undo()` takes the last stroke back and `reset()` restores the cloud
|
|
48
|
+
* as it was before the first edit. Selections are not strokes. The history copies whole buffers, so a `cloud.write`
|
|
49
|
+
* made between strokes is taken back with the stroke after it. WebGPU, or the WebGL2 compatibility layer, as `Splats`.
|
|
38
50
|
* @throws TypeError when `cloud` is not a Splats; MargoError `'unsupported'` on a WebGL engine, `'disposed'` after
|
|
39
51
|
* `dispose()`, `'state'` before the cloud has drawn a frame.
|
|
40
52
|
*/
|
|
@@ -54,9 +66,38 @@ export declare class SplatBrush implements EnginePlugin {
|
|
|
54
66
|
private pipeline?;
|
|
55
67
|
private group?;
|
|
56
68
|
private dead;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
69
|
+
private readonly limit;
|
|
70
|
+
private steps;
|
|
71
|
+
private original?;
|
|
72
|
+
private stroke?;
|
|
73
|
+
private stroking;
|
|
74
|
+
/** @throws RangeError for a `history` that is not a whole number of 0 or more. */
|
|
75
|
+
constructor(cloud: Splats, options?: SplatBrushOptions);
|
|
76
|
+
/** Same as `engine.use(new SplatBrush(cloud, options))`; returns it. */
|
|
77
|
+
static attach(engine: EngineKernel, cloud: Splats, options?: SplatBrushOptions): SplatBrush;
|
|
78
|
+
/** Strokes `undo` can take back. */
|
|
79
|
+
get strokes(): number;
|
|
80
|
+
/** Whether a stroke is open (`beginStroke` without its `endStroke`). */
|
|
81
|
+
get inStroke(): boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Starts a stroke: every erase and paint until `endStroke()` is taken back by one `undo()`, as one drag of a brush
|
|
84
|
+
* tool. An open stroke ends first.
|
|
85
|
+
*/
|
|
86
|
+
beginStroke(): this;
|
|
87
|
+
/** Ends the open stroke, if any. */
|
|
88
|
+
endStroke(): this;
|
|
89
|
+
/**
|
|
90
|
+
* Takes back the last stroke (ending an open one first), restoring the positions, opacities, colours and SH it
|
|
91
|
+
* changed. Returns false when there is nothing to undo.
|
|
92
|
+
* @throws MargoError `'disposed'` after `dispose()`.
|
|
93
|
+
*/
|
|
94
|
+
undo(): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Restores the cloud as it was before the brush's first erase or paint (the scan as loaded, or as last written
|
|
97
|
+
* before that edit) and clears the stroke history. Does nothing before any edit.
|
|
98
|
+
* @throws MargoError `'disposed'` after `dispose()`.
|
|
99
|
+
*/
|
|
100
|
+
reset(): this;
|
|
60
101
|
/** Width and height in pixels of the frame the cloud last drew, the space of every region and pick; 0 before. */
|
|
61
102
|
get frame(): [number, number];
|
|
62
103
|
setup(engine: Engine): void;
|
|
@@ -87,6 +128,19 @@ export declare class SplatBrush implements EnginePlugin {
|
|
|
87
128
|
/** Checks the state and writes the region, ready for a dispatch; returns the device. */
|
|
88
129
|
private ready;
|
|
89
130
|
private submit;
|
|
131
|
+
/** Whether a snapshot was taken of the cloud's current buffers (not before a device restore or re-attach). */
|
|
132
|
+
private live;
|
|
133
|
+
/** The live input buffer of a snapshot part. */
|
|
134
|
+
private source;
|
|
135
|
+
/** Copies the `wanted` live buffers into `step` where it holds none yet, in `e`, before the edit. */
|
|
136
|
+
private keep;
|
|
137
|
+
/** Records what an erase or paint is about to change: the cloud before the first edit, and the stroke's step. */
|
|
138
|
+
private remember;
|
|
139
|
+
/** Copies a snapshot back into the live buffers. */
|
|
140
|
+
private restore;
|
|
141
|
+
private drop;
|
|
142
|
+
/** Drops the whole history and the copy of the cloud before the first edit. */
|
|
143
|
+
private forget;
|
|
90
144
|
private run;
|
|
91
145
|
onDeviceRestored(engine: Engine): void;
|
|
92
146
|
dispose(): void;
|
package/dist/brush.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const t=(engine,version="
|
|
3
|
+
const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
4
|
import{t as e}from"./view-DyJeX8rJ.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as n}from"@margoengine/math/errors";var r=`struct Brush {view:mat4x4f,region:vec4f,color:vec4f,params:vec4f,counts:vec4u}
|
|
5
5
|
struct Ellipse {center:vec4f,axes:vec4f}
|
|
6
6
|
@group(0) @binding(0) var<uniform> u:Brush;
|
|
@@ -33,4 +33,4 @@ fn inside(i:u32)->bool {
|
|
|
33
33
|
|
|
34
34
|
let bits=bitcast<u32>(-(u.view*vec4f(positions[i].xyz,1)).z);let key=select(bits^0x80000000u,~bits,(bits>>31u)==1u);
|
|
35
35
|
if(op==5u){atomicMin(&result[0],key);}else if(key==atomicLoad(&result[0])){atomicMin(&result[1],i);}
|
|
36
|
-
}`,i={circle:0,rect:1,selection:2,all:3},a=class
|
|
36
|
+
}`,i={circle:0,rect:1,selection:2,all:3},a=[`positions`,`colors`,`sh`],o=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(e,t={}){if(this.name=`splats-brush:`+o.next++,this.width=0,this.height=0,this.data=/* @__PURE__ */ new Float32Array(32),this.integers=new Uint32Array(this.data.buffer),this.dead=!1,this.steps=[],this.stroking=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatBrush needs a Splats cloud`);let n=t?.history??32;if(!(Number.isInteger(n)&&n>=0))throw RangeError(`SplatBrush history must be a whole number of strokes, 0 or more`);this.cloud=e,this.limit=n}static attach(e,n,r){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let i=new o(n,r);return t(e).use(i),i}get strokes(){return this.steps.length}get inStroke(){return this.stroking}beginStroke(){return this.endStroke(),this.stroking=!0,this}endStroke(){return this.stroking=!1,this.stroke=void 0,this}undo(){if(this.endStroke(),this.dead)throw new n(`disposed`,`SplatBrush is disposed; attach a new one`);let e=this.steps.pop();return e?(this.live(e)&&this.restore(e),this.drop(e),!0):!1}reset(){if(this.endStroke(),this.dead)throw new n(`disposed`,`SplatBrush is disposed; attach a new one`);for(let e of this.steps)this.drop(e);return this.steps=[],this.original&&this.live(this.original)&&this.restore(this.original),this}get frame(){return[this.width,this.height]}setup(e){if(this.dead||!e.gpu)throw new n(this.dead?`disposed`:`unsupported`,`SplatBrush needs WebGPU; attach a new SplatBrush to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu,this.uniform=e.gpu.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.result=e.gpu.createBuffer({size:8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})}registerPasses(t){t.add({name:this.name,order:-6.9,execute:t=>{t.backend===`webgpu`&&this.cloud.attached&&(this.width=t.width,this.height=t.height,e(this.data.subarray(0,16),t.camera))}})}async pick(e,t,n=.1){if(!(n>=0&&n<=1))throw RangeError(`SplatBrush.pick threshold must be 0 to 1`);let r=this.ready({x:e,y:t,radius:0}),i=r.createBuffer({size:8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});this.data[24]=n,r.queue.writeBuffer(this.result,0,new Uint32Array([4294967295,4294967295])),this.submit(5,{x:e,y:t,radius:0});let a=r.createCommandEncoder();this.run(a,6),a.copyBufferToBuffer(this.result,0,i,0,8),r.queue.submit([a.finish()]);try{await i.mapAsync(GPUMapMode.READ);let e=new Uint32Array(i.getMappedRange())[1];return e===4294967295?-1:e}finally{i.destroy()}}select(e,t=`replace`){let n=[`replace`,`add`,`subtract`].indexOf(t);if(n<0)throw RangeError(`SplatBrush.select mode must be 'replace', 'add' or 'subtract'`);return e===`none`?t===`replace`?this.submit(2,`all`):this:this.submit(n,e)}async selection(){let e=this.ready(`all`),t=this.cloud.count*4,n=e.createBuffer({size:t,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),r=e.createCommandEncoder();r.copyBufferToBuffer(this.mask,0,n,0,t),e.queue.submit([r.finish()]);try{await n.mapAsync(GPUMapMode.READ);let e=new Uint32Array(n.getMappedRange()),t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(n);return Uint32Array.from(t)}finally{n.destroy()}}erase(e=`selection`){return this.submit(3,e)}paint(e,t,n=1){if(t?.length!==3||![...Array.from(t),n].every(e=>e>=0&&e<=1))throw RangeError(`SplatBrush.paint needs an RGB colour and a strength, each 0 to 1`);return this.data.set([t[0],t[1],t[2],n],20),this.submit(4,e)}commit(){return this.cloud.read()}ready(e){if(this.dead||!this.device)throw new n(`disposed`,`SplatBrush is disposed or not attached; attach a new one`);if(!this.width||!this.cloud.attached)throw new n(`state`,`SplatBrush works on a drawn frame; render the engine once before editing`);let t=this.device,a=this.cloud.gpuState,o=this.data,s;if(typeof e==`string`)s=i[e];else{let t=`radius`in e,n=t?[e.x,e.y,e.radius]:[e.x,e.y,e.width,e.height];if(!n.every(Number.isFinite)||n.slice(2).some(e=>e<0))throw RangeError(`A brush region needs finite x and y and a radius, or a width and height, of 0 or more`);s=+!t,o.set(t?[e.x,e.y,e.radius,0]:[e.x,e.y,e.x+n[2],e.y+n[3]],16)}if(s===void 0)throw RangeError(`A brush target must be a region, 'selection' or 'all'`);return o[25]=this.width,o[26]=this.height,this.integers[28]=this.cloud.count,this.integers[30]=s,this.integers[31]=this.cloud.coefficients,(!this.group||this.group.ellipses!==a.ellipses)&&(this.mask?.destroy(),this.mask=t.createBuffer({size:this.cloud.count*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),this.pipeline??=t.createComputePipeline({layout:`auto`,compute:{module:t.createShaderModule({code:r}),entryPoint:`main`}}),this.group={group:t.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[this.uniform,a.ellipses,a.positions,a.inputColors,a.sh,this.mask,this.result].map((e,t)=>({binding:t,resource:{buffer:e}}))}),ellipses:a.ellipses}),t}submit(e,t){let n=this.ready(t),r=n.createCommandEncoder();return(e===3||e===4)&&this.remember(r,e===3?[`positions`,`colors`]:[`colors`,`sh`]),this.run(r,e),n.queue.submit([r.finish()]),this}live(e){return!!this.device&&this.cloud.attached&&e.owner===this.cloud.gpuState.positions}source(e){let t=this.cloud.gpuState;return e===`positions`?t.positions:e===`colors`?t.inputColors:t.sh}keep(e,t,n){for(let r of n){if(t[r]||r===`sh`&&!this.cloud.coefficients)continue;let n=this.source(r),i=this.device.createBuffer({size:n.size,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST});e.copyBufferToBuffer(n,0,i,0,n.size),t[r]=i}}remember(e,t){let n=this.cloud.gpuState.positions;if(this.original?.owner!==n&&(this.forget(),this.original={owner:n},this.keep(e,this.original,a)),!this.limit)return;let r=this.stroking?this.stroke:void 0;r||(r={owner:n},this.steps.push(r),this.steps.length>this.limit&&this.drop(this.steps.shift()),this.stroking&&(this.stroke=r)),this.keep(e,r,t)}restore(e){let t=this.device.createCommandEncoder();for(let n of a){let r=e[n];r&&t.copyBufferToBuffer(r,0,this.source(n),0,r.size)}this.device.queue.submit([t.finish()])}drop(e){for(let t of a)e[t]?.destroy()}forget(){for(let e of this.steps)this.drop(e);this.original&&this.drop(this.original),this.steps=[],this.original=this.stroke=void 0}run(e,t){this.integers[29]=t,this.device.queue.writeBuffer(this.uniform,0,this.data);let n=e.beginComputePass();n.setPipeline(this.pipeline),n.setBindGroup(0,this.group.group),n.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),n.end()}onDeviceRestored(e){this.steps=[],this.original=this.stroke=void 0,this.mask?.destroy(),this.mask=this.pipeline=this.group=void 0,this.width=0,this.setup(e)}dispose(){if(!this.dead){this.dead=!0,this.engine?.sceneOf(this)?.removePlugin(this.name);for(let e of[this.uniform,this.result,this.mask])e?.destroy();this.forget(),this.uniform=this.result=this.mask=this.pipeline=this.group=this.device=this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as SplatBrush,r as brushShader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function e(e,t){return(await import(`./spz-ivoWSN9h.js`).then(e=>e.n)).parseSpz(e,t)}async function t(e,t){return(await import(`./sog-TlM17j4y.js`).then(e=>e.n)).parseSog(e,t)}async function n(e,t){return(await import(`./encode-BfG7xkVn.js`)).encodeSpz(e,t)}async function r(e){return(await import(`./encode-BfG7xkVn.js`)).encodeSog(e)}export{e as i,n,t as r,r as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{SRGBToLinear as e}from"@margoengine/math/color";import{MargoError as t}from"@margoengine/math/errors";var n=Object.defineProperty,r=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},i=/* @__PURE__ */ r({attributesFromSplats:()=>g,decomposeCovariance:()=>f,encodeSplat:()=>h,parsePly:()=>c,splatsFromAttributes:()=>l}),a=.2820947918,o={char:[1,(e,t)=>e.getInt8(t)],int8:[1,(e,t)=>e.getInt8(t)],uchar:[1,(e,t)=>e.getUint8(t)],uint8:[1,(e,t)=>e.getUint8(t)],short:[2,(e,t)=>e.getInt16(t,!0)],int16:[2,(e,t)=>e.getInt16(t,!0)],ushort:[2,(e,t)=>e.getUint16(t,!0)],uint16:[2,(e,t)=>e.getUint16(t,!0)],int:[4,(e,t)=>e.getInt32(t,!0)],int32:[4,(e,t)=>e.getInt32(t,!0)],uint:[4,(e,t)=>e.getUint32(t,!0)],uint32:[4,(e,t)=>e.getUint32(t,!0)],float:[4,(e,t)=>e.getFloat32(t,!0)],float32:[4,(e,t)=>e.getFloat32(t,!0)],double:[8,(e,t)=>e.getFloat64(t,!0)],float64:[8,(e,t)=>e.getFloat64(t,!0)]},s=e=>{let t=Math.min(1,Math.max(0,e));return t<=.04045?1/12.92:2.4/1.055*((t+.055)/1.055)**1.4};function c(e){if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`Expected .ply bytes; pass an ArrayBuffer or typed array of the file`);let n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Math.min(n.length,65536),i=-1,a=new TextDecoder(`latin1`).decode(n.subarray(0,r)),s=a.indexOf(`end_header`);if(a.startsWith(`ply`)&&s>=0&&(i=a.indexOf(`
|
|
2
|
+
`,s)+1),i<=0)throw RangeError(`Not a PLY file: it must start with "ply" and have an end_header line.`);let c=a.slice(0,i).split(/\r?\n/),u=``,d=-1,f=!1,p=[];for(let e of c){let n=e.trim().split(/\s+/);if(n[0]===`format`)u=n[1];else if(n[0]===`element`){if(f=n[1]===`vertex`,f)d=Number(n[2]);else if(n[1]===`chunk`)throw new t(`unsupported`,`Packed (chunked) splat PLY files are not supported; export an uncompressed Gaussian-splat PLY.`)}else if(n[0]===`property`&&f){if(n[1]===`list`)throw RangeError(`Splat PLY vertex properties must be scalars, not lists.`);if(!o[n[1]])throw RangeError(`Unknown PLY property type ${n[1]}; use float, double or an integer type.`);p.push({type:n[1],name:n[2]})}}if(u===`binary_big_endian`)throw new t(`unsupported`,`Big-endian PLY files are not supported; export binary_little_endian or ascii.`);if(u!==`binary_little_endian`&&u!==`ascii`)throw RangeError(`Unknown PLY format ${u}; use binary_little_endian or ascii.`);if(!Number.isInteger(d)||d<1||d>3e6)throw RangeError(`A splat PLY needs 1 to 3,000,000 vertices.`);let m=new Map(p.map((e,t)=>[e.name,t])),h=[`x`,`y`,`z`,`f_dc_0`,`f_dc_1`,`f_dc_2`,`opacity`,`scale_0`,`scale_1`,`scale_2`,`rot_0`,`rot_1`,`rot_2`,`rot_3`].filter(e=>!m.has(e));if(h.length)throw RangeError(`Not a Gaussian-splat PLY: missing ${h.join(`, `)}; export the splat attributes.`);let g=0;for(;m.has(`f_rest_${g}`);)g++;let _=g/3+1;if(g%3||![1,4,9,16,25].includes(_))throw RangeError(`Splat PLY f_rest_* must hold 3, 8, 15 or 24 coefficients per colour channel (SH degree 1-4).`);let v=p.length,y=new Float64Array(d*v);if(u===`ascii`){let e=new TextDecoder(`latin1`).decode(n.subarray(i)).trim().split(/\s+/);if(e.length<d*v)throw RangeError(`The ascii PLY has fewer values than its header promises; check that the file is complete.`);for(let t=0;t<d*v;t++)y[t]=Number(e[t])}else{let e=[],t=0;for(let n of p)e.push(t),t+=o[n.type][0];if(n.length-i<d*t)throw RangeError(`The PLY file is shorter than its header promises; check that it downloaded completely.`);let r=new DataView(n.buffer,n.byteOffset+i,d*t),a=p.map(e=>o[e.type][1]);for(let n=0;n<d;n++)for(let i=0;i<v;i++)y[n*v+i]=a[i](r,n*t+e[i])}let b=e=>m.get(e),x=b(`x`),S=b(`f_dc_0`),C=b(`opacity`),w=b(`scale_0`),T=b(`rot_0`),E=g?b(`f_rest_0`):0,D=_-1,O={count:d,positions:new Float32Array(d*3),logScales:new Float32Array(d*3),rotations:new Float32Array(d*4),dc:new Float32Array(d*3),alphas:new Float32Array(d),rest:D?new Float32Array(d*D*3):void 0};for(let e=0;e<d;e++){let t=t=>y[e*v+t];if(O.positions.set([t(x),t(b(`y`)),t(b(`z`))],e*3),O.rotations.set([t(T),t(T+1),t(T+2),t(T+3)],e*4),O.logScales.set([t(w),t(w+1),t(w+2)],e*3),O.dc.set([t(S),t(S+1),t(S+2)],e*3),O.alphas[e]=1/(1+Math.exp(-t(C))),O.rest)for(let n=0;n<3;n++)for(let r=0;r<D;r++)O.rest[(e*D+r)*3+n]=t(E+n*D+r)}return l(O)}function l(t,{linear:n=!1}={}){let{count:r}=t,i=t.rest?t.rest.length/r/3:0,o=i+1;if(!Number.isInteger(i)||![0,3,8,15,24].includes(i))throw RangeError(`Splat spherical harmonics must hold 3, 8, 15 or 24 coefficients per colour channel (degree 1-4).`);let c=new Float32Array(r*6),l=new Float32Array(r*4),u=i?new Float32Array(r*o*3):void 0;for(let f=0;f<r;f++){let r=t.rotations[f*4],p=t.rotations[f*4+1],m=t.rotations[f*4+2],h=t.rotations[f*4+3],g=Math.hypot(r,p,m,h);if(!(g>0))throw RangeError(`A splat rotation is the zero quaternion; check the file.`);r/=g,p/=g,m/=g,h/=g,d(c,f,[p,m,h,r],[Math.exp(t.logScales[f*3]),Math.exp(t.logScales[f*3+1]),Math.exp(t.logScales[f*3+2])]),l[f*4+3]=t.alphas[f];for(let r=0;r<3;r++){let c=.5+a*t.dc[f*3+r],d=Math.min(1,Math.max(0,c)),p=n?d:e(d);if(l[f*4+r]=p,!u)continue;let m=n?1:s(c);u[f*o*3+r]=(p-.5)/a;for(let e=1;e<o;e++)u[(f*o+e)*3+r]=t.rest[(f*i+e-1)*3+r]*m}}let f=u?{positions:t.positions,covariances:c,colors:l,sphericalHarmonics:u}:{positions:t.positions,covariances:c,colors:l};return D(f),f}var u=2**-20;function d(e,t,n,r){let[i,a,o,s]=n,c=[1-2*(a*a+o*o),2*(i*a-o*s),2*(i*o+a*s),2*(i*a+o*s),1-2*(i*i+o*o),2*(a*o-i*s),2*(i*o-a*s),2*(a*o+i*s),1-2*(i*i+a*a)],l=[r[0]*r[0],r[1]*r[1],r[2]*r[2]],d=Math.max(Math.max(...l)*u,1e-30),f=l.map(e=>Math.max(e,d)),p=0;for(let n=0;n<3;n++)for(let r=n;r<3;r++)e[t*6+p++]=c[n*3]*c[r*3]*f[0]+c[n*3+1]*c[r*3+1]*f[1]+c[n*3+2]*c[r*3+2]*f[2]}function f(e,t=0){let n=[[e[t],e[t+1],e[t+2]],[e[t+1],e[t+3],e[t+4]],[e[t+2],e[t+4],e[t+5]]],r=[[1,0,0],[0,1,0],[0,0,1]];for(let e=0;e<32&&!(Math.abs(n[0][1])+Math.abs(n[0][2])+Math.abs(n[1][2])<1e-30*(Math.abs(n[0][0])+Math.abs(n[1][1])+Math.abs(n[2][2])));e++)for(let[e,t]of[[0,1],[0,2],[1,2]]){if(n[e][t]===0)continue;let i=(n[t][t]-n[e][e])/(2*n[e][t]),a=Math.sign(i||1)/(Math.abs(i)+Math.sqrt(i*i+1)),o=1/Math.sqrt(a*a+1),s=a*o;for(let r=0;r<3;r++){let i=n[r][e],a=n[r][t];n[r][e]=o*i-s*a,n[r][t]=s*i+o*a}for(let r=0;r<3;r++){let i=n[e][r],a=n[t][r];n[e][r]=o*i-s*a,n[t][r]=s*i+o*a}for(let n=0;n<3;n++){let i=r[n][e],a=r[n][t];r[n][e]=o*i-s*a,r[n][t]=s*i+o*a}}if(r[0][0]*(r[1][1]*r[2][2]-r[1][2]*r[2][1])-r[0][1]*(r[1][0]*r[2][2]-r[1][2]*r[2][0])+r[0][2]*(r[1][0]*r[2][1]-r[1][1]*r[2][0])<0)for(let e=0;e<3;e++)r[e][2]=-r[e][2];return{scale:[0,1,2].map(e=>Math.sqrt(Math.max(n[e][e],0))),rotation:p(r)}}function p(e){let t=e[0][0]+e[1][1]+e[2][2],n,r,i,a;if(t>0){let o=Math.sqrt(t+1)*2;a=o/4,n=(e[2][1]-e[1][2])/o,r=(e[0][2]-e[2][0])/o,i=(e[1][0]-e[0][1])/o}else if(e[0][0]>e[1][1]&&e[0][0]>e[2][2]){let t=Math.sqrt(1+e[0][0]-e[1][1]-e[2][2])*2;a=(e[2][1]-e[1][2])/t,n=t/4,r=(e[0][1]+e[1][0])/t,i=(e[0][2]+e[2][0])/t}else if(e[1][1]>e[2][2]){let t=Math.sqrt(1+e[1][1]-e[0][0]-e[2][2])*2;a=(e[0][2]-e[2][0])/t,n=(e[0][1]+e[1][0])/t,r=t/4,i=(e[1][2]+e[2][1])/t}else{let t=Math.sqrt(1+e[2][2]-e[0][0]-e[1][1])*2;a=(e[1][0]-e[0][1])/t,n=(e[0][2]+e[2][0])/t,r=(e[1][2]+e[2][1])/t,i=t/4}let o=Math.hypot(n,r,i,a);return[n/o,r/o,i/o,a/o]}var m=e=>{let t=Math.min(1,Math.max(0,e));return t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055};function h(e){let t=D(e),n=new Uint8Array(t*32),r=new DataView(n.buffer);if(e.colors.some((e,t)=>t%4==3&&e>1))throw RangeError(`The .splat format stores opacity through 1; use SOG for this cloud`);for(let i=0;i<t;i++){let t=i*32;for(let n=0;n<3;n++)r.setFloat32(t+n*4,e.positions[i*3+n],!0);let{scale:a,rotation:o}=f(e.covariances,i*6);for(let e=0;e<3;e++)r.setFloat32(t+12+e*4,Math.max(a[e],1e-12),!0);for(let r=0;r<3;r++)n[t+24+r]=Math.round(m(e.colors[i*4+r])*255);n[t+27]=Math.round(e.colors[i*4+3]*255);let[s,c,l,u]=o;[u,s,c,l].forEach((e,r)=>n[t+28+r]=Math.min(255,Math.max(0,Math.round(e*128+128))))}return n}function g(e){let t=D(e),n=e.sphericalHarmonics,r=n?n.length/t/3:1,i={count:t,positions:e.positions.slice(),logScales:new Float32Array(t*3),rotations:new Float32Array(t*4),dc:new Float32Array(t*3),alphas:new Float32Array(t),...n?{rest:new Float32Array(t*(r-1)*3)}:{}};for(let o=0;o<t;o++){let{scale:t,rotation:c}=f(e.covariances,o*6),[l,u,d,p]=c;for(let e=0;e<3;e++)i.logScales[o*3+e]=Math.log(Math.max(t[e],1e-30));i.rotations.set([p,l,u,d],o*4),i.alphas[o]=e.colors[o*4+3];for(let t=0;t<3;t++){let c=m(n?.5+a*n[o*r*3+t]:e.colors[o*4+t]),l=s(c);i.dc[o*3+t]=(c-.5)/a;for(let e=1;e<r;e++)i.rest[(o*(r-1)+e-1)*3+t]=n[(o*r+e)*3+t]/l}}return i}var _=(e,t)=>e.sphericalHarmonics?e.sphericalHarmonics.length/t/3:0;function v(e,t){let n=D(e);if(typeof t!=`function`)throw TypeError(`filterSplats needs a keep(index) function`);let r=[];for(let i=0;i<n;i++)t(i,e)&&r.push(i);return y(e,r,_(e,n))}function y(e,t,n){if(!t.length)throw RangeError(`No splats are left; widen the region or the filter.`);let r=t.length,i=new Float32Array(r*3),a=new Float32Array(r*6),o=new Float32Array(r*4),s=n?new Float32Array(r*n*3):void 0;return t.forEach((t,r)=>{i.set(e.positions.subarray(t*3,t*3+3),r*3),a.set(e.covariances.subarray(t*6,t*6+6),r*6),o.set(e.colors.subarray(t*4,t*4+4),r*4),s&&s.set(e.sphericalHarmonics.subarray(t*n*3,(t+1)*n*3),r*n*3)}),s?{positions:i,covariances:a,colors:o,sphericalHarmonics:s}:{positions:i,covariances:a,colors:o}}function b(e,t,n={}){let r=n.invert??!1,i=e=>Array.isArray(e)&&e.length===3&&e.every(e=>typeof e==`number`&&Number.isFinite(e)),a;if(t&&`box`in t&&i(t.box?.min)&&i(t.box?.max)){let{min:e,max:n}=t.box;a=(t,r,i)=>t>=e[0]&&t<=n[0]&&r>=e[1]&&r<=n[1]&&i>=e[2]&&i<=n[2]}else if(t&&`sphere`in t&&i(t.sphere?.center)&&t.sphere.radius>=0){let{center:e,radius:n}=t.sphere;a=(t,r,i)=>(t-e[0])**2+(r-e[1])**2+(i-e[2])**2<=n*n}else throw RangeError(`Invalid crop region; pass {box: {min: [x, y, z], max: [x, y, z]}} or {sphere: {center: [x, y, z], radius}}`);let o=e?.positions;return v(e,e=>a(o[e*3],o[e*3+1],o[e*3+2])!==r)}function x(e,t,n,r){return r[0]=.2820947918,r[1]=-.4886025119*t,r[2]=.4886025119*n,r[3]=-.4886025119*e,r[4]=1.0925484306*e*t,r[5]=-1.0925484306*t*n,r[6]=.3153915653*(3*n*n-1),r[7]=-1.0925484306*e*n,r[8]=.5462742153*(e*e-t*t),r[9]=-.5900435899*t*(3*e*e-t*t),r[10]=2.8906114426*e*t*n,r[11]=-.4570457995*t*(5*n*n-1),r[12]=.3731763326*n*(5*n*n-3),r[13]=-.4570457995*e*(5*n*n-1),r[14]=1.4453057213*n*(e*e-t*t),r[15]=-.5900435899*e*(e*e-3*t*t),r[16]=2.5033429418*e*t*(e*e-t*t),r[17]=-1.7701307698*t*n*(3*e*e-t*t),r[18]=.9461746958*e*t*(7*n*n-1),r[19]=-.6690465436*t*n*(7*n*n-3),r[20]=.1057855469*(35*n**4-30*n*n+3),r[21]=-.6690465436*e*n*(7*n*n-3),r[22]=.4730873479*(e*e-t*t)*(7*n*n-1),r[23]=-1.7701307698*e*n*(e*e-3*t*t),r[24]=.6258357354*(e**4-6*e*e*t*t+t**4),r}function S(e,t){let n=new Float64Array(t),r=[],i=[];for(let a=0;a<128;a++){let o=1-2*(a+.5)/128,s=Math.sqrt(1-o*o),c=a*Math.PI*(3-Math.sqrt(5)),l=[Math.cos(c)*s,o,Math.sin(c)*s];r.push(x(l[0],l[1],l[2],new Float64Array(t)).slice(0,t));let u=[e[0]*l[0]+e[3]*l[1]+e[6]*l[2],e[1]*l[0]+e[4]*l[1]+e[7]*l[2],e[2]*l[0]+e[5]*l[1]+e[8]*l[2]];i.push(x(u[0],u[1],u[2],n).slice(0,t))}let a=new Float64Array(t*t),o=new Float64Array(t*t);for(let e=0;e<128;e++)for(let n=0;n<t;n++)for(let s=0;s<t;s++)a[n*t+s]+=r[e][n]*r[e][s],o[n*t+s]+=r[e][n]*i[e][s];for(let e=0;e<t;e++){let n=e;for(let r=e+1;r<t;r++)Math.abs(a[r*t+e])>Math.abs(a[n*t+e])&&(n=r);for(let r=0;r<t;r++)[a[e*t+r],a[n*t+r]]=[a[n*t+r],a[e*t+r]],[o[e*t+r],o[n*t+r]]=[o[n*t+r],o[e*t+r]];for(let n=0;n<t;n++){if(n===e)continue;let r=a[n*t+e]/a[e*t+e];if(r)for(let i=0;i<t;i++)a[n*t+i]-=r*a[e*t+i],o[n*t+i]-=r*o[e*t+i]}}for(let e=0;e<t;e++)for(let n=0;n<t;n++)o[e*t+n]/=a[e*t+e];return o}function C(e,t){let n=D(e);if(!t||t.length!==16||!Array.from(t).every(Number.isFinite))throw RangeError(`Invalid splat transform; pass a 4x4 column-major matrix of 16 finite numbers`);let r=t,i=[r[0],r[4],r[8],r[1],r[5],r[9],r[2],r[6],r[10]],a=i[0]*(i[4]*i[8]-i[5]*i[7])-i[1]*(i[3]*i[8]-i[5]*i[6])+i[2]*(i[3]*i[7]-i[4]*i[6]);if(!(Math.abs(a)>1e-12))throw RangeError(`A splat transform needs an invertible linear part (no zero scale); fix the matrix.`);let o=new Float32Array(n*3),s=new Float32Array(n*6),c=e.colors.slice();for(let t=0;t<n;t++){let n=e.positions[t*3],a=e.positions[t*3+1],c=e.positions[t*3+2];for(let e=0;e<3;e++)o[t*3+e]=i[e*3]*n+i[e*3+1]*a+i[e*3+2]*c+r[12+e];let l=e.covariances.subarray(t*6,t*6+6),u=[l[0],l[1],l[2],l[1],l[3],l[4],l[2],l[4],l[5]],d=/* @__PURE__ */ new Float64Array(9);for(let e=0;e<3;e++)for(let t=0;t<3;t++)d[e*3+t]=i[e*3]*u[t]+i[e*3+1]*u[3+t]+i[e*3+2]*u[6+t];let f=0;for(let e=0;e<3;e++)for(let n=e;n<3;n++)s[t*6+f++]=d[e*3]*i[n*3]+d[e*3+1]*i[n*3+1]+d[e*3+2]*i[n*3+2]}let l={positions:o,covariances:s,colors:c},u=e.sphericalHarmonics;if(u){let t=_(e,n),r=S(w(i),t),a=new Float32Array(u.length);for(let e=0;e<n;e++)for(let n=0;n<3;n++)for(let i=0;i<t;i++){let o=0;for(let a=0;a<t;a++)o+=r[i*t+a]*u[(e*t+a)*3+n];a[(e*t+i)*3+n]=o}l.sphericalHarmonics=a}return D(l),l}function w(e){let t=e.slice();for(let e=0;e<64;e++){let e=t[0]*(t[4]*t[8]-t[5]*t[7])-t[1]*(t[3]*t[8]-t[5]*t[6])+t[2]*(t[3]*t[7]-t[4]*t[6]),n=[t[4]*t[8]-t[5]*t[7],t[5]*t[6]-t[3]*t[8],t[3]*t[7]-t[4]*t[6],t[2]*t[7]-t[1]*t[8],t[0]*t[8]-t[2]*t[6],t[1]*t[6]-t[0]*t[7],t[1]*t[5]-t[2]*t[4],t[2]*t[3]-t[0]*t[5],t[0]*t[4]-t[1]*t[3]],r=t.map((t,r)=>(t+n[r]/e)/2),i=r.reduce((e,n,r)=>e+Math.abs(n-t[r]),0);if(t=r,i<1e-14)break}return t}function T(...e){if(!e.length)throw RangeError(`mergeSplats needs at least one cloud`);let t=e.map(e=>D(e)),n=new Set(e.map((e,n)=>_(e,t[n])));if(n.size>1)throw RangeError(`Merged clouds need the same spherical-harmonics degree; drop sphericalHarmonics from all or give all the same degree.`);let r=t.reduce((e,t)=>e+t,0),i=[...n][0],a=new Float32Array(r*3),o=new Float32Array(r*6),s=new Float32Array(r*4),c=i?new Float32Array(r*i*3):void 0,l=0;e.forEach((e,n)=>{a.set(e.positions,l*3),o.set(e.covariances,l*6),s.set(e.colors,l*4),c&&c.set(e.sphericalHarmonics,l*i*3),l+=t[n]});let u=c?{positions:a,covariances:o,colors:s,sphericalHarmonics:c}:{positions:a,covariances:o,colors:s};return D(u),u}function E(e,t){let n=D(e),r=t?.cellSize;if(!(r>0&&r<1/0))throw RangeError(`decimateSplats needs a cellSize above 0, world units`);let i=_(e,n),a=/* @__PURE__ */ new Map,o=e.positions;for(let e=0;e<n;e++){let t=`${Math.floor(o[e*3]/r)},${Math.floor(o[e*3+1]/r)},${Math.floor(o[e*3+2]/r)}`,n=a.get(t);n||a.set(t,n=[]),n.push(e)}let s=a.size,c=new Float32Array(s*3),l=new Float32Array(s*6),u=new Float32Array(s*4),d=i?new Float32Array(s*i*3):void 0,f=0;for(let t of a.values()){let n=t.map(t=>{let n=e.covariances.subarray(t*6,t*6+6),r=n[0]*(n[3]*n[5]-n[4]*n[4])-n[1]*(n[1]*n[5]-n[4]*n[2])+n[2]*(n[1]*n[4]-n[3]*n[2]);return Math.max(e.colors[t*4+3],1e-6)*Math.sqrt(Math.max(r,0))}),r=n.reduce((e,t)=>e+t,0)||1,a=[0,0,0];t.forEach((e,t)=>{for(let i=0;i<3;i++)a[i]+=n[t]/r*o[e*3+i]});let s=/* @__PURE__ */ new Float64Array(6);t.forEach((t,c)=>{let l=n[c]/r,p=[o[t*3]-a[0],o[t*3+1]-a[1],o[t*3+2]-a[2]],m=e.covariances.subarray(t*6,t*6+6),h=0;for(let e=0;e<3;e++)for(let t=e;t<3;t++,h++)s[h]+=l*(m[h]+p[e]*p[t]);for(let n=0;n<4;n++)u[f*4+n]+=l*e.colors[t*4+n];if(d)for(let n=0;n<i*3;n++)d[f*i*3+n]+=l*e.sphericalHarmonics[t*i*3+n]}),c.set(a,f*3),l.set(s,f*6),f++}let p=d?{positions:c,covariances:l,colors:u,sphericalHarmonics:d}:{positions:c,covariances:l,colors:u};for(let e=0;e<s*4;e++)p.colors[e]=Math.min(e%4==3?1.5625:1,Math.max(0,p.colors[e]));return D(p),p}function D(e){if(!e||!(e.positions instanceof Float32Array)||!(e.covariances instanceof Float32Array)||!(e.colors instanceof Float32Array))throw TypeError(`Splat data must use Float32 arrays`);let t=e.positions.length/3,n=e.sphericalHarmonics;if(!Number.isInteger(t)||t<1||t>3e6||e.covariances.length!==t*6||e.colors.length!==t*4||n!==void 0&&(!(n instanceof Float32Array)||![4,9,16,25].includes(n.length/t/3)))throw RangeError(`Splat data needs 1 to 3,000,000 splats, covariances of 6 and colors of 4 per splat, and spherical harmonics of 4, 9, 16 or 25 coefficients per channel; fix the array lengths.`);for(let t of[e.positions,e.covariances,e.colors,...n?[n]:[]])for(let e of t)if(!Number.isFinite(e))throw RangeError(`Splat attributes must be finite`);for(let n=0;n<t;n++){let t=n*6,r=e.covariances[t],i=e.covariances[t+1],a=e.covariances[t+2],o=e.covariances[t+3],s=e.covariances[t+4],c=e.covariances[t+5];if(r<=0||r*o-i*i<=0||r*(o*c-s*s)-i*(i*c-a*s)+a*(i*s-a*o)<=0)throw RangeError(`Splat covariance must be positive definite`);for(let t=0;t<4;t++)if(e.colors[n*4+t]<0||e.colors[n*4+t]>(t===3?1.5625:1))throw RangeError(`Splat colors must be 0..1 and opacity 0..1.5625; fix the attribute values`)}return t}function O(t){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw TypeError(`Expected .splat bytes`);let n=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=n.length/32;if(!Number.isInteger(r)||r<1||r>3e6)throw RangeError(`A .splat file must hold 1 to 3,000,000 splats of 32 bytes each; check that the file is complete.`);let i=new DataView(n.buffer,n.byteOffset,n.byteLength),a=new Float32Array(r*3),o=new Float32Array(r*6),s=new Float32Array(r*4);for(let t=0;t<r;t++){let r=t*32;for(let e=0;e<3;e++)a[t*3+e]=i.getFloat32(r+e*4,!0);let c=i.getFloat32(r+12,!0),l=i.getFloat32(r+16,!0),u=i.getFloat32(r+20,!0);if(![c,l,u].every(e=>Number.isFinite(e)&&e>0))throw RangeError(`A .splat scale must be finite and above 0; check that the file is a valid .splat.`);let d=(n[r+28]-128)/128,f=(n[r+29]-128)/128,p=(n[r+30]-128)/128,m=(n[r+31]-128)/128,h=Math.hypot(d,f,p,m);if(!h)throw RangeError(`A .splat rotation is the zero quaternion (all four bytes are 128); check that the file is a valid .splat.`);d/=h,f/=h,p/=h,m/=h;let g=[1-2*(p*p+m*m),2*(f*p-m*d),2*(f*m+p*d),2*(f*p+m*d),1-2*(f*f+m*m),2*(p*m-f*d),2*(f*m-p*d),2*(p*m+f*d),1-2*(f*f+p*p)],_=[c*c,l*l,u*u],v=0;for(let e=0;e<3;e++)for(let n=e;n<3;n++)o[t*6+v++]=g[e*3]*g[n*3]*_[0]+g[e*3+1]*g[n*3+1]*_[1]+g[e*3+2]*g[n*3+2]*_[2];for(let i=0;i<3;i++)s[t*4+i]=e(n[r+24+i]/255);s[t*4+3]=n[r+27]/255}let c={positions:a,covariances:o,colors:s};return D(c),c}export{v as a,g as c,c as d,i as f,E as i,f as l,r as m,D as n,T as o,l as p,b as r,C as s,O as t,h as u};
|
package/dist/data.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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{i as f,n as p,r as m,t as h}from"./compressed-Bfvhv63J.js";export{t as attributesFromSplats,c as cropSplats,r as decimateSplats,i as decomposeCovariance,h as encodeSog,d as encodeSplat,p as encodeSpz,e as filterSplats,o as mergeSplats,n as parsePly,m as parseSog,u as parseSplat,f as parseSpz,s as splatsFromAttributes,l as transformSplats,a as validateSplats};
|
package/dist/depth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const t=(engine,version="
|
|
3
|
+
const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
4
|
import{t as e}from"./view-rect-G-t2gTqO.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as n}from"@margoengine/math/errors";var r=`struct Ellipse {center:vec4f,axes:vec4f}
|
|
5
5
|
@group(0) @binding(0) var<uniform> threshold:vec4f;
|
|
6
6
|
@group(0) @binding(1) var<storage,read> ellipses:array<Ellipse>;
|
|
@@ -11,4 +11,4 @@ struct Out {@builtin(position) clip:vec4f,@location(0) corner:vec2f,@location(1)
|
|
|
11
11
|
o.clip=vec4f(e.center.xy+e.axes.xy*corner.x+e.axes.zw*corner.y,e.center.z,1);o.corner=corner;o.opacity=e.center.w;
|
|
12
12
|
if(e.center.w<threshold.x){o.clip=vec4f(2,2,0,1);}return o;
|
|
13
13
|
}
|
|
14
|
-
@fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5||min(0.99,i.opacity*exp(power))<threshold.x){discard;}}`,i=class i{coreRequirement=__margoCoreRequirement("
|
|
14
|
+
@fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5||min(0.99,i.opacity*exp(power))<threshold.x){discard;}}`,i=class i{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(e,t={}){if(this.name=`splats-depth:`+i.next++,this.data=/* @__PURE__ */ new Float32Array(4),this.pipelines=/* @__PURE__ */ new Map,this.disposed=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatDepth needs a Splats cloud`);if(this.cloud=e,this.value=a(t.threshold??.5),this.order=t.order??3.5,!Number.isFinite(this.order))throw RangeError(`SplatDepth order must be a finite number`)}static attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let a=new i(n,r);return t(e).use(a),a}get threshold(){return this.value}set threshold(e){this.value=a(e)}setup(e){if(this.disposed||!e.gpu)throw new n(this.disposed?`disposed`:`unsupported`,`SplatDepth needs WebGPU and a live depth pass; attach a new SplatDepth to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.uniform=e.gpu.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:this.name,order:this.order,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}draw(t){if(!this.cloud.attached)return;let n=this.cloud.gpuState,i=t.descriptor.multisample?.count??1,a=t.descriptor.depthStencil.format,o=i+`:`+a,s=this.pipelines.get(o);if(!s){let e=t.device.createShaderModule({code:r});s=t.device.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vertex`},fragment:{module:e,entryPoint:`fragment`,targets:[]},primitive:{topology:`triangle-strip`},multisample:t.descriptor.multisample,depthStencil:{format:a,depthWriteEnabled:!0,depthCompare:`greater`}}),this.pipelines.set(o,s)}let c=s.getBindGroupLayout(0);(!this.group||this.group.ellipses!==n.ellipses||this.group.sorted!==n.sorted||this.group.layout!==c)&&(this.group={group:t.device.createBindGroup({layout:c,entries:[this.uniform,n.ellipses,n.sorted].map((e,t)=>({binding:t,resource:{buffer:e}}))}),ellipses:n.ellipses,sorted:n.sorted,layout:c}),this.data[0]=this.value,t.device.queue.writeBuffer(this.uniform,0,this.data);let l=a.includes(`stencil`),u=t.encoder.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:t.depth,depthLoadOp:`load`,depthStoreOp:`store`,...l?{stencilReadOnly:!0}:{}}});e(u,t),u.setPipeline(s),u.setBindGroup(0,this.group.group),u.draw(4,this.cloud.count),u.end(),this.engine.stats.drawCalls++}onDeviceRestored(e){this.pipelines.clear(),this.group=void 0,this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.uniform?.destroy(),this.uniform=this.group=this.engine=void 0,this.pipelines.clear())}[Symbol.dispose??Symbol()](){this.dispose()}};function a(e){if(typeof e!=`number`||!(e>=0&&e<=1))throw RangeError(`SplatDepth threshold must be 0 to 1`);return e}export{i as SplatDepth};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e}from"./data-D31W24Wu.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};
|
|
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};
|
package/dist/formats.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
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
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(
|
|
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
4
|
`)+`
|
|
5
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};
|
package/dist/index.d.ts
CHANGED
|
@@ -46,6 +46,7 @@ export declare class Splats implements EnginePlugin {
|
|
|
46
46
|
private sortPipelines;
|
|
47
47
|
private sortGroups;
|
|
48
48
|
private compatSort?;
|
|
49
|
+
private routeReady;
|
|
49
50
|
private renders;
|
|
50
51
|
private disposed;
|
|
51
52
|
private mip;
|
|
@@ -125,6 +126,20 @@ export declare class Splats implements EnginePlugin {
|
|
|
125
126
|
setFog(fog: FogLike | null): this;
|
|
126
127
|
static attach(instance: EngineKernel, data: SplatData): Splats;
|
|
127
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>;
|
|
128
143
|
registerPasses(graph: FrameGraph): void;
|
|
129
144
|
private sort;
|
|
130
145
|
/** The fog uniform and the fogged projection pipeline and group, made on the first fogged frame. */
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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};
|
package/dist/lighting.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const e=(engine,version="
|
|
3
|
+
const e=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
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
5
|
@group(0) @binding(0) var<uniform> u:Light;
|
|
6
6
|
@group(0) @binding(1) var<storage,read> positions:array<vec4f>;
|
|
@@ -45,4 +45,4 @@ struct Out {@builtin(position) @invariant clip:vec4f,@location(0) corner:vec2f,@
|
|
|
45
45
|
fn hash(v:u32)->u32 {let s=v*747796405u+2891336453u;let w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}
|
|
46
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
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("
|
|
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};
|
package/dist/lod-sog.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./sog-
|
|
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};
|
package/dist/lod.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const r=(engine,version="
|
|
4
|
-
import{i as e,n as t}from"./data-
|
|
3
|
+
const r=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{i as e,n as t}from"./data-BDt3mxGg.js";import{t as n}from"./src-BxooDRB9.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as i}from"@margoengine/math/errors";function a(n,r={}){let i=t(n),a=r.leafSize??65536;if(!Number.isInteger(a)||a<64)throw RangeError(`buildSplatLod leafSize must be an integer of 64 or more`);let c=n.sphericalHarmonics?n.sphericalHarmonics.length/i/3:0,l=[],u=[],d=n.positions,f=new Uint32Array(i);for(let e=0;e<i;e++)f[e]=e;let p=(t,r,i,f)=>{let m=l.length;l.push(void 0),u.push(void 0);let h=[];if(t.length>a&&f<21){let e=i/2,n=new Uint8Array(t.length),a=/* @__PURE__ */ new Uint32Array(8);t.forEach((t,i)=>{let o=0;for(let n=0;n<3;n++)d[t*3+n]>=r[n]+e&&(o|=1<<n);n[i]=o,a[o]++});for(let i=0;i<8;i++){if(!a[i])continue;let o=new Uint32Array(a[i]),s=0;t.forEach((e,t)=>{n[t]===i&&(o[s++]=e)}),h.push(p(o,[0,1,2].map(t=>r[t]+(i>>t&1)*e),e,f+1))}h.length===1&&l[h[0]].children.length===0&&f>=20&&(h=[])}let g=o(n,t,c),_=g,v=0;if(h.length)for(let t=i/64;_=e(g,{cellSize:t}),v=t,!(_.positions.length/3<=a);t*=2);let y=s(_.positions,h.map(e=>l[e]));return l[m]={center:y.center,radius:y.radius,error:v,count:_.positions.length/3,children:h},u[m]=_,m},m=[1/0,1/0,1/0],h=[-1/0,-1/0,-1/0];for(let e=0;e<i;e++)for(let t=0;t<3;t++)m[t]=Math.min(m[t],d[e*3+t]),h[t]=Math.max(h[t],d[e*3+t]);return p(f,m,Math.max(h[0]-m[0],h[1]-m[1],h[2]-m[2])*(1+1e-6)||1,0),{nodes:l,coefficients:c,load:(e,t)=>t.aborted?Promise.reject(t.reason):u[e]?Promise.resolve(u[e]):Promise.reject(/* @__PURE__ */ RangeError(`No splat node ${e}`))}}function o(e,t,n){let r=t.length,i=new Float32Array(r*3),a=new Float32Array(r*6),o=new Float32Array(r*4),s=n?new Float32Array(r*n*3):void 0,c=n*3;return t.forEach((t,n)=>{i.set(e.positions.subarray(t*3,t*3+3),n*3),a.set(e.covariances.subarray(t*6,t*6+6),n*6),o.set(e.colors.subarray(t*4,t*4+4),n*4),s&&s.set(e.sphericalHarmonics.subarray(t*c,t*c+c),n*c)}),{positions:i,covariances:a,colors:o,...s?{sphericalHarmonics:s}:{}}}function s(e,t){let n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=3)for(let i=0;i<3;i++)n[i]=Math.min(n[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);for(let e of t)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e.center[t]-e.radius),r[t]=Math.max(r[t],e.center[t]+e.radius);let i=[0,1,2].map(e=>(n[e]+r[e])/2),a=0;for(let t=0;t<e.length;t+=3)a=Math.max(a,(e[t]-i[0])**2+(e[t+1]-i[1])**2+(e[t+2]-i[2])**2);let o=Math.sqrt(a);for(let e of t)o=Math.max(o,Math.hypot(e.center[0]-i[0],e.center[1]-i[1],e.center[2]-i[2])+e.radius);return{center:i,radius:o}}function c(e,t,n){let r=[];if(!e.length)return{selected:[],wanted:r};if(!n.loaded(0))return{selected:[],wanted:[0]};let i=n=>{let r=e[n];if(!r.children.length)return 0;if(!r.count)return 1/0;let i=Math.hypot(r.center[0]-t.eye[0],r.center[1]-t.eye[1],r.center[2]-t.eye[2])-r.radius;return r.error*t.focal/Math.max(i,t.near)},a=[[i(0),0]],o=[],s=e[0].count,c=+(e[0].count>0);for(;a.length;){a.sort((e,t)=>t[0]-e[0]||e[1]-t[1]);let[t,l]=a.shift(),u=e[l];if(t<=n.maxError){o.push(l,...a.map(e=>e[1]));break}let d=u.children.filter(e=>!n.loaded(e)),f=s-u.count+u.children.reduce((t,n)=>t+e[n].count,0),p=c-+(u.count>0)+u.children.filter(t=>e[t].count>0).length;if(d.length||f>n.budget||p>(n.maxNodes??1/0))d.length&&f<=n.budget&&p<=(n.maxNodes??1/0)&&r.push(...d),o.push(l);else{s=f,c=p;for(let e of u.children)a.push([i(e),e])}}return{selected:o.sort((e,t)=>e-t),wanted:r}}var l=class e{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(t,r={}){this.name=`splats-lod:`+e.next++,this.abort=new AbortController,this.loaded=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.failures=[],this.at=/* @__PURE__ */ new Map,this.cut=[],this.used=0,this.waiters=[],this.disposed=!1;let i=t?.nodes;if(!Array.isArray(i)||!i.length||typeof t.load!=`function`)throw TypeError(`SplatLod needs a source with nodes and load(index, signal)`);if(![0,4,9,16,25].includes(t.coefficients))throw RangeError(`SplatLod source coefficients must be 0, 4, 9, 16 or 25`);let a=r.budget??1e6;this.maxError=r.maxError??2,this.concurrency=r.concurrency??4;for(let[e,t,n]of[[`budget`,a,1],[`maxError`,this.maxError,0],[`concurrency`,this.concurrency,1]])if(!(t>=n)||!Number.isFinite(t))throw RangeError(`SplatLod ${e} must be ${n} or more`);let o=0;if(i.forEach((e,t)=>{if(!(e.count>=0)||!e.count&&!e.children.length||!Number.isInteger(e.count)||!(e.radius>=0)||!(e.error>=0)||e.children.some(e=>!(e>t&&e<i.length)))throw RangeError(`SplatLod node ${t} is invalid (count, radius, error, or a child that is not a later node); give each node a count of 1 or more and only later children`);o=Math.max(o,e.count)}),o>a)throw RangeError(`SplatLod budget ${a} is under the largest node, ${o} splats; raise the budget or split the node`);this.source=t,this.slot=o;let s=i.filter(e=>!e.children.length).length;this.slots=Array(Math.min(Math.floor(a/o),s)).fill(void 0);let c=e=>i[e].count?1:i[e].children.reduce((e,t)=>e+c(t),0);if(c(0)>this.slots.length)throw RangeError(`SplatLod budget needs at least ${c(0)*o} splats to cover all structural branches; raise budget`);this.cacheSize=r.cache??this.slots.length*o*2,this.cloud=n.reserve(this.slots.length*o,t.coefficients),r.signal?.addEventListener(`abort`,()=>this.abort.abort(r.signal.reason),{once:!0})}static attach(t,n,i={}){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let a=new e(n,i),o=r(t);return o.use(a.cloud),o.use(a),a}get selected(){return this.cut}get placement(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.at)e.set(t,n*this.slot);return e}get drawn(){return this.used}get loading(){return this.pending.size}get errors(){return this.failures}settled(){return new Promise(e=>this.waiters.push(e))}setup(e){if(this.disposed||!e.gpu)throw new i(this.disposed?`disposed`:`unsupported`,`SplatLod needs WebGPU and a live hierarchy; attach a new SplatLod to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e}registerPasses(e){e.add({name:this.name,order:-8,execute:e=>{e.backend===`webgpu`&&this.update(e)}})}update(e){let t=e.height/(2*Math.tan(e.camera.fov*Math.PI/360)),n={eye:e.camera.position,focal:t,near:e.camera.near},{selected:r,wanted:i}=c(this.source.nodes,n,{maxError:this.maxError,budget:this.slots.length*this.slot,loaded:e=>this.loaded.has(e),maxNodes:this.slots.length});for(let e of i)this.request(e);let a=new Set(r);for(let e of this.cut)if(!a.has(e)&&this.source.nodes[e].count){let t=this.at.get(e);this.cloud.clear(t*this.slot,this.slot),this.slots[t]=void 0,this.at.delete(e)}for(let e of r)if(this.source.nodes[e].count&&!this.at.has(e)){let t=this.slots.indexOf(void 0);this.slots[t]=e,this.at.set(e,t),this.cloud.clear(t*this.slot,this.slot),this.source.nodes[e].count&&this.cloud.write(t*this.slot,this.loaded.get(e))}if(this.cut=r,this.used=r.reduce((e,t)=>e+this.source.nodes[t].count,0),this.evict(a),!i.length&&!this.pending.size&&this.waiters.length){let e=this.waiters;this.waiters=[];for(let t of e)t()}}request(e){this.source.nodes[e].count?this.pending.has(e)||this.pending.size>=this.concurrency||this.abort.signal.aborted||this.failures.some(t=>t.node===e)||(this.pending.add(e),this.source.load(e,this.abort.signal).then(n=>{if(this.pending.delete(e),this.disposed)return;let r=t(n),i=n.sphericalHarmonics?n.sphericalHarmonics.length/r/3:0;r!==this.source.nodes[e].count||i!==this.source.coefficients?this.failures.push(Object.assign(/* @__PURE__ */ RangeError(`Splat node ${e} loaded ${r} splats with ${i} SH coefficients, not ${this.source.nodes[e].count} with ${this.source.coefficients}`),{node:e})):this.loaded.set(e,n)},t=>{this.pending.delete(e),this.abort.signal.aborted||this.failures.push(Object.assign(t instanceof Error?t:Error(String(t)),{node:e}))})):this.loaded.set(e,{positions:/* @__PURE__ */ new Float32Array,covariances:/* @__PURE__ */ new Float32Array,colors:/* @__PURE__ */ new Float32Array})}evict(e){let t=0;for(let e of this.loaded.keys())t+=this.source.nodes[e].count;for(let n of[...this.loaded.keys()]){if(t<=this.cacheSize)break;e.has(n)||n===0||(this.loaded.delete(n),t-=this.source.nodes[n].count)}}dispose(){if(!this.disposed){this.disposed=!0,this.abort.abort(new i(`disposed`,`The SplatLod was disposed`)),this.engine?.sceneOf(this)?.removePlugin(this.name),this.engine=void 0,this.cloud.dispose(),this.loaded.clear();for(let e of this.waiters)e();this.waiters=[]}}[Symbol.dispose??Symbol()](){this.dispose()}};export{l as SplatLod,a as buildSplatLod,c as chooseSplatNodes};
|
package/dist/modify.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
-
const n=(engine,version="
|
|
4
|
-
import{n as e}from"./data-
|
|
3
|
+
const n=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e}from"./data-BDt3mxGg.js";import{t}from"./scene-scope-C5HWuOIb.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as r}from"@margoengine/math/errors";function i(e={}){for(let t of[`position`,`opacity`,`color`,`declarations`])if(e[t]!==void 0&&(typeof e[t]!=`string`||t!==`declarations`&&!e[t].trim()))throw TypeError(`Splat modifier hooks must be nonempty WGSL strings; pass function bodies returning the documented types`);let t=`struct ModifierFrame {clock:vec4f,counts:vec4u,parameters:array<vec4f,16>}
|
|
5
5
|
@group(0) @binding(0) var<uniform> u:ModifierFrame;
|
|
6
6
|
${e.declarations??``}`,n=`let time=u.clock.x;let delta=u.clock.y;`;return{position:t+`
|
|
7
7
|
@group(0) @binding(1) var<storage,read> canonical:array<vec4f>;
|
|
@@ -21,4 +21,4 @@ fn modifyColor(index:u32,position:vec3f,color:vec3f)->vec3f {${n}${e.color??`ret
|
|
|
21
21
|
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
22
22
|
let index=id.x;if(index>=u.counts.x||u.clock.z<0.5){return;}let original=evaluated[index];
|
|
23
23
|
evaluated[index]=vec4f(max(vec3f(0),modifyColor(index,positions[index].xyz,original.rgb)),original.a);
|
|
24
|
-
}`}}var a=/* @__PURE__ */ new WeakMap,o=class o{coreRequirement=__margoCoreRequirement("
|
|
24
|
+
}`}}var a=/* @__PURE__ */ new WeakMap,o=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(e,t,n){if(this.name=`splats-modifier:`+o.next++,this.parameters=/* @__PURE__ */ new Float32Array(64),this.time=0,this.playing=!0,this.speed=1,this.enabled=!0,this.values=/* @__PURE__ */ new Float32Array(72),this.integers=new Uint32Array(this.values.buffer),this.pipelines=[],this.groups=[],this.dead=!1,this.cloud=e,this.shaders=i(n),this.canonical=new Float32Array(e.count*4),this.setRest(t),n.parameters!==void 0){if(!Number.isSafeInteger(n.parameters.length)||n.parameters.length>64||n.parameters.length<0)throw RangeError(`Splat modifier takes up to 64 parameter floats; shorten the parameter list`);for(let e=0;e<n.parameters.length;e++){if(!Number.isFinite(Math.fround(n.parameters[e])))throw RangeError(`Splat modifier parameters must be finite; fix the parameter values`);this.parameters[e]=n.parameters[e]}}this.signal=n.signal,this.abort=n.signal?()=>this.dispose():void 0,n.signal?.addEventListener(`abort`,this.abort,{once:!0})}static async create(e,t={}){if(!e||typeof e.read!=`function`||!Number.isInteger(e.count))throw TypeError(`SplatModifier needs a Splats cloud; pass the cloud to modify`);t.signal?.throwIfAborted(),i(t);let n=t.signal,r=e.read(),a=await new Promise((e,t)=>{let i=()=>{n?.removeEventListener(`abort`,i),t(n.reason)};n?.addEventListener(`abort`,i,{once:!0}),n?.aborted&&i(),r.then(e,t).finally(()=>n?.removeEventListener(`abort`,i))});return n?.throwIfAborted(),new o(e,a,t)}static async attach(e,r,i={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let a=t(e),s=await o.create(r,i);try{return i.signal?.throwIfAborted(),a.run(()=>n(e).use(s)),s}catch(e){throw s.dispose(),e}}setRest(t){if(this.dead)throw new r(`disposed`,`Splat modifier was disposed; create a new modifier`);if(e(t)!==this.cloud.count)throw RangeError(`Canonical splat count differs from the cloud; pass a full cloud of the same count`);for(let e=0;e<this.cloud.count;e++)this.canonical.set(t.positions.subarray(e*3,e*3+3),e*4),this.canonical[e*4+3]=t.colors[e*4+3];return this.rest&&this.device.queue.writeBuffer(this.rest,0,this.canonical),this}setup(e){if(this.dead||!e.gpu)throw new r(this.dead?`disposed`:`unsupported`,`SplatModifier needs a live WebGPU engine; see https://margoengine.com/errors#webgpu`);if(a.has(this.cloud)&&a.get(this.cloud)!==this)throw new r(`attached`,`This cloud already has a modifier; combine its WGSL hooks or dispose it first`);let t=e.gpu;this.engine=e,this.device=t,this.uniform=t.createBuffer({size:this.values.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.rest=t.createBuffer({size:this.canonical.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this.rest,0,this.canonical),this.pipelines=[this.shaders.position,this.shaders.color].map(e=>t.createComputePipeline({layout:`auto`,compute:{module:t.createShaderModule({code:e}),entryPoint:`main`}})),a.set(this.cloud,this)}registerPasses(e){for(let[t,n]of[[0,-7.25],[1,-6.95]])e.add({name:this.name+`:`+t,order:n,execute:e=>{e.backend===`webgpu`&&this.cloud.attached&&this.run(e,t)}})}run(e,t){if(t===0){if(!Number.isFinite(Math.fround(this.time))||!Number.isFinite(Math.fround(e.delta))||!Number.isFinite(this.speed)||!this.parameters.every(Number.isFinite))throw RangeError(`Modifier clock and parameters must be finite; fix time, speed or parameter values`);this.values.set([this.time,e.delta,+this.enabled,0]),this.integers[4]=this.cloud.count,this.values.set(this.parameters,8),e.device.queue.writeBuffer(this.uniform,0,this.values)}let n=this.cloud.gpuState;(this.bound!==n.positions||this.evaluated!==n.colors)&&(this.groups=[[this.uniform,this.rest,n.positions,n.inputColors],[this.uniform,n.positions,n.colors]].map((t,n)=>e.device.createBindGroup({layout:this.pipelines[n].getBindGroupLayout(0),entries:t.map((e,t)=>({binding:t,resource:{buffer:e}}))})),this.bound=n.positions,this.evaluated=n.colors);let r=e.encoder.beginComputePass();r.setPipeline(this.pipelines[t]),r.setBindGroup(0,this.groups[t]),r.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),r.end()}get disposed(){return this.dead}release(){this.uniform?.destroy(),this.rest?.destroy(),this.uniform=this.rest=this.bound=this.evaluated=void 0,this.groups=[],this.pipelines=[]}advanceTime(e){e>0&&this.playing&&(this.time+=e*this.speed)}onPreUpdate(e){this.advanceTime(e)}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){if(!this.dead){if(this.dead=!0,this.cloud.attached&&this.bound===this.cloud.gpuState.positions&&this.device&&this.rest){let e=this.device.createCommandEncoder();this.values[2]=0,this.integers[4]=this.cloud.count,this.device.queue.writeBuffer(this.uniform,0,this.values);let t=e.beginComputePass();t.setPipeline(this.pipelines[0]),t.setBindGroup(0,this.groups[0]),t.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),t.end(),this.device.queue.submit([e.finish()])}a.get(this.cloud)===this&&a.delete(this.cloud),this.signal?.removeEventListener(`abort`,this.abort),this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=this.device=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as SplatModifier,i as splatModifierShaders};
|