@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/README.md CHANGED
@@ -1,443 +1,547 @@
1
- # @margoengine/splats
2
-
3
- Optional Gaussian splats with GPU covariance projection and stable compute radix sorting.
4
-
5
- Import `margoengine/splats` from the `margoengine` package, or `@margoengine/splats` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
6
-
7
- Use `@margoengine/splats/data` for `parseSplat`, `validateSplats` and the
8
- `SplatData` type without loading GPU rendering or radix-sort shaders. Root
9
- exports retain the same functions for applications that also render splats.
10
-
11
- Optional WebGPU Gaussian rendering that accepts 1-3,000,000 world-space splats (an input cap, not a frame-rate promise: adapter storage/memory limits may allow fewer, and frame time at the cap depends on the GPU). Compute projects each positive-definite 3D covariance through the camera Jacobian into a 2D ellipse with a 0.3-pixel variance floor. The Jacobian is linearised at the splat's view direction clamped to 1.3 times the half-view tangent, as trained captures expect, so a splat beside or behind the edge of the view cannot stretch across the frame. Instanced quads cover three standard deviations; the fragment shader evaluates Gaussian opacity and blends far to near against read-only reversed scene depth.
12
-
13
- ```ts
14
- import {EngineKernel} from 'margoengine/core';
15
- import {Splats,parseSplat} from 'margoengine/splats';
16
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
17
- const response = await fetch('/capture.splat');
18
- if (!response.ok) throw new Error('Failed to load splats: '+response.status);
19
- const cloud = Splats.attach(engine, parseSplat(await response.arrayBuffer()));
20
- engine.start();
21
- // cloud.dispose() when unloading; engine.dispose() releases attached plugins.
22
- ```
23
-
24
- The executable README check maps `/capture.splat`, `/capture.ply`, `/capture.spz` and `/capture.sog` to
25
- the documented 8,385-splat excerpt of Niantic's raccoon capture (MIT), preserving the format each example
26
- requests. The PLY/SPZ/SOG fixtures are the documented real-data inputs; `.splat` is serialized here
27
- from that PLY with `encodeSplat`. This exercises the examples on a real excerpt, without a complete-capture
28
- quality, performance or independent `.splat` encoder-accuracy claim. See [fixture provenance](test/fixtures/NOTICE.md).
29
-
30
- For generated data, supply `SplatData`: `positions` has three Float32 values per splat; `covariances` has six (xx, xy, xz, yy, yz, zz); `colors` has four (linear RGB and opacity, each 0..1). Construction validates lengths, finite values and positive-definite covariance, then copies the data for ownership/device recovery. Colors are converted to sRGB for ordinary display targets and remain linear in HDR targets.
31
-
32
- Optional `sphericalHarmonics` contains 4, 9 or 16 coefficients per splat, with RGB interleaved for each coefficient. Evaluation uses the real SH basis through degree 3, the camera-to-splat direction, and the usual 0.5 offset. SH replaces RGB; `colors` still supplies opacity. Large SH buffers can exceed an adapter's storage binding limit even when the base cloud fits; attachment rejects before allocating. `parseSplat()` decodes the common 32-byte binary layout (xyz, positive xyz scales, byte RGBA, byte quaternion in wxyz order), converts byte sRGB to linear, normalizes quaternions and derives covariance. `parsePly()` reads Gaussian-splat PLY files (below); `parseSpz()` and `parseSog()` read compressed captures (below); training is outside this package.
33
-
34
- Orthographic cameras (any `camera.matrix` with a constant clip w, such as `CameraProjection` from `@margoengine/cameras`) use the affine Jacobian: a splat's pixel size depends only on the zoom, not its depth. The depth range is the projection's own near/far, which may lie behind the eye, sort keys are measured from the near plane, and spherical harmonics use the fixed viewing direction. The package reads only the clip matrix and does not depend on the cameras package.
35
-
36
- Each frame creates sortable unsigned depth keys on the GPU. Eight stable 4-bit LSD radix passes run per-workgroup histograms, hierarchical exclusive prefix scans, a scan of block totals, and scatter. Workgroup bit masks and population counts preserve input order within equal digits; equal-depth splats retain source order. Off-frustum, transparent and out-of-range centers sort to the end and render no fragments. The runtime performs no CPU sorting, per-splat frame allocation or GPU readback.
37
-
38
- Base GPU allocations are approximately 128 bytes per splat (384 MB at three million), plus small histograms/uniforms and optional SH. CPU copies for recovery are additional. Center-depth sorting approximates intersecting ellipsoids; near-plane-crossing centers are culled. Multiple clouds sort independently: combine overlapping clouds into one data set when global order matters. Splats do not write depth unless `./depth` is attached (below), cast directional shadows or receive PBR lighting. They can render alongside shadows, clustered meshes, animation, VFX and TAA; temporal history uses underlying opaque depth. Frame rate and sorting time depend on hardware and fill rate, with no 1-2 ms or locked-60-FPS guarantee.
39
-
40
- `cloud.setFog(fog)` fogs the cloud with `@margoengine/environment`'s `Fog` or any object with its fields (`color`, `near`, `far`, `density`, `heightFalloff`, `height`, `enabled`), read every frame with Fog's maths. Each splat's colour fades toward the fog colour by the fog at its centre, in the projection pass and in linear before the display encoding; opacity is unchanged. The package does not import environment. `fog.enabled = false` clears it without recompiling; `cloud.setFog(null)` (the default) draws exactly as before.
41
-
42
- ```ts
43
- import {Fog} from 'margoengine/environment';
44
- import {Splats, parseSplat} from 'margoengine/splats';
45
- import {Engine} from 'margoengine/core';
46
- const engine = await Engine.create(document.querySelector('canvas')!);
47
- const cloud = Splats.attach(engine, parseSplat(await (await fetch('/capture.splat')).arrayBuffer()));
48
- cloud.setFog(Fog.attach(engine, {color: '#8090a0', density: 0.02}));
49
- ```
50
-
51
- `cloud.antialias = true` turns on Mip-Splatting's 2D filter (Yu et al. 2024): each splat's opacity is scaled by
52
- sqrt(det(S) / det(S + 0.3 I)) of its screen covariance S, so a splat smaller than a pixel fades with its coverage
53
- instead of drawing as a 0.3 px^2 blob at full opacity, and far or small captures stop shimmering and thickening.
54
- Splats several pixels wide keep nearly all their opacity. It is live (no recompile) and off by default, the look
55
- trained 3DGS files expect; a capture trained with the filter (SPZ's antialiased flag) should turn it on.
56
-
57
- ```ts
58
- import {Splats} from 'margoengine/splats';
59
- import {parsePly} from 'margoengine/splats/data';
60
- import {Engine} from 'margoengine/core';
61
- const engine = await Engine.create(document.querySelector('canvas')!);
62
- const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
63
- cloud.antialias = true;
64
- engine.start();
65
- ```
66
-
67
- ## With glass
68
-
69
- The cloud sorts against itself and blends over the scene, so glass in front of it comes out wrong. `addEffect` from
70
- [`margoengine/oit/vfx`](../oit/README.md#particles-splats-and-points-addeffect) draws it in the same pass as the glass:
71
-
72
- ```ts
73
- import {Engine} from 'margoengine/core';
74
- import {ExactOIT} from 'margoengine/oit/exact';
75
- import {addEffect} from 'margoengine/oit/vfx';
76
- import {Splats} from 'margoengine/splats';
77
- const engine = await Engine.create(document.querySelector('canvas')!);
78
- const cloud = Splats.attach(engine, {
79
- positions: new Float32Array([0, 0, -1]),
80
- covariances: new Float32Array([0.1, 0, 0, 0.1, 0, 0.1]),
81
- colors: new Float32Array([0.2, 0.6, 1, 0.8]),
82
- });
83
- addEffect(ExactOIT.attach(engine, {layers: 32}), cloud);
84
- ```
85
-
86
- The depth sort stops while it is in the pass, and `ExactOIT` keeps only the nearest `layers` per pixel, so a dense capture
87
- looks thinner than its own draw. Leave a capture on its own draw unless glass must cut through it.
88
-
89
- ## PLY captures, editing and level of detail (`./data`)
90
-
91
- ```ts
92
- import {EngineKernel} from 'margoengine/core';
93
- import {Splats} from 'margoengine/splats';
94
- import {cropSplats, decimateSplats, encodeSplat, mergeSplats, parsePly, transformSplats} from 'margoengine/splats/data';
95
-
96
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend: 'webgpu'});
97
- const response = await fetch('/capture.ply'); // a trained Gaussian-splat PLY
98
- if (!response.ok) throw new Error('Failed to load splats: ' + response.status);
99
- let cloud = parsePly(await response.arrayBuffer());
100
- // Training frames are often Y-down: turn 180 degrees about X to stand the capture up in Margo's Y-up world.
101
- cloud = transformSplats(cloud, [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]);
102
- cloud = cropSplats(cloud, {sphere: {center: [0, 0, 0], radius: 5}}); // drop floaters far from the subject
103
- const preview = decimateSplats(cloud, {cellSize: 0.05}); // a coarser cloud for a distant view
104
- const both = mergeSplats(cloud, transformSplats(cloud, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 4, 0, 0, 1]));
105
- const saved = new Blob([encodeSplat(cloud)]); // back to .splat, for parseSplat or other viewers
106
- Splats.attach(engine, preview);
107
- engine.start();
108
- console.log(both.positions.length / 3, saved.size);
109
- ```
110
-
111
- - **`parsePly(bytes)`** reads the PLY layout Gaussian-splat training writes (`binary_little_endian` or `ascii`, one `vertex` element with `x y z`, `f_dc_0..2`, optional `f_rest_*` for SH degrees 1-3, `opacity` as a logit, `scale_0..2` as logs and `rot_0..3` as w x y z). Opacity goes through the sigmoid, scales through exp, rotation and scale become the covariance. These files store display (sRGB) colour; the base colour is converted to linear exactly and the view-dependent terms to first order around it, since the renderer works in linear. Coordinates are kept as stored. Big-endian and packed (chunked) PLY files throw a `MargoError` with code `unsupported`; files without the splat properties throw a `RangeError` naming what is missing.
112
- - **`splatsFromAttributes(raw, {linear})`** turns attributes as training stores them (`GaussianAttributes`: positions, log scales, w x y z rotations, band-0 and higher SH, opacity) into `SplatData`, for readers of other containers (`@margoengine/gltf/splats` uses it). `linear: true` is for colour stored linear, in place of display colour. Every reader goes through it, so a splat flatter than Float32 can store keeps an axis at 1/1024 of its longest, or a whole file of real captures would be refused; projection adds 0.3 px^2 to each ellipse, so the lift never shows.
113
- - **`encodeSplat(data)`** writes the 32-byte `.splat` layout `parseSplat` reads, splitting each covariance into axis scales and a rotation (`decomposeCovariance`, Jacobi). `.splat` has no SH, so the base colour is kept; a round trip is exact to byte precision.
114
- - **`cropSplats(data, {box: {min, max}} | {sphere: {center, radius}}, {invert})`** keeps the splats whose centres are inside (or outside) the region; **`filterSplats(data, keep)`** keeps those `keep(index)` accepts. SH travels with the kept splats.
115
- - **`transformSplats(data, matrix)`** applies a column-major 4x4 affine matrix: centres by the matrix, covariances by its linear part (scale and shear stretch the splats), and SH by the matrix's rotation (from its polar decomposition, by an exact least-squares fit per SH band), so view-dependent colour turns with the cloud.
116
- - **`mergeSplats(...clouds)`** concatenates clouds with the same SH degree. **`decimateSplats(data, {cellSize})`** merges the splats of each grid cell into one Gaussian with the same weighted mean and second moment (weights: opacity times volume); colour, opacity and SH are the weighted means. It is a moment-matched preview level, not a trained one.
117
- - **`parseSpz(bytes, {signal})`** reads SPZ versions 2, 3 and 4 (24-bit fixed-point positions, byte log-scales, byte colours, 3-byte or smallest-three rotations, SH degrees 0-3). Versions 2 and 3 are one gzip stream and need `DecompressionStream` (current browsers, Node 18+). Version 4, the default of current exporters such as PlayCanvas splat-transform, is a plain header, a table of contents and one Zstandard stream per attribute; it is read by a built-in Zstandard decoder (RFC 8878: Huffman and FSE, repeat offsets, content checksums, several and skippable frames), which loads only when a version 4 file arrives. Each stream is limited to the size the table of contents declares; a version 2 or 3 gzip stream stops with a `RangeError` once it expands past the largest possible body (3,000,000 degree-3 splats, 195,000,016 bytes), and a deflated SOG ZIP entry once it passes its declared size, so a small hostile file cannot inflate without bound. Damaged, truncated or checksum-failing files throw a `RangeError` saying to check the file; a stream that needs a Zstandard dictionary throws a `MargoError` with code `unsupported`.
118
- - **`parseSog(bytes | files, {signal})`** reads SOG version 2, bundled (`.sog` ZIP) or as loose files (`meta.json` plus its lossless WebP textures; `@margoengine/decoders/webp-lossless` bundled in, no image API needed). It needs `DecompressionStream` for deflated ZIP entries; lossy SOG textures throw a `MargoError` with code `unsupported`.
119
- - Both return a promise and honour an `AbortSignal`. They are tested against real captures (`test/fixtures/NOTICE.md`): SPZ version 2 and SOG bit for bit against the PlayCanvas splat-transform decode, SPZ version 4 bit for bit against version 3 of the same scene.
120
-
121
- ```ts
122
- import {parseSog, parseSpz} from 'margoengine/splats/data';
123
-
124
- const abort = new AbortController();
125
- // Any SPZ version: 2 and 3 (gzip) or 4 (Zstandard), detected from the file.
126
- const spz = await parseSpz(await (await fetch('/capture.spz')).arrayBuffer(), {signal: abort.signal});
127
- const sog = await parseSog(await (await fetch('/capture.sog')).arrayBuffer());
128
- console.log(spz.positions.length / 3, sog.positions.length / 3);
129
- ```
130
-
131
- ## Compressed export (`./data`)
132
-
133
- `encodeSpz` and `encodeSog` write a cloud as SPZ (version 3) or a bundled SOG (version 2), so an edited capture ships
134
- small; `encodeSplat` writes the 32-byte `.splat` layout:
135
-
136
- ```ts
137
- import {encodeSog, encodeSpz, parsePly, parseSpz} from 'margoengine/splats/data';
138
-
139
- const cloud = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
140
- const spz = await encodeSpz(cloud); // gzip, about a tenth of the PLY
141
- const sog = await encodeSog(cloud); // ZIP of meta.json and lossless WebP textures
142
- const back = await parseSpz(spz); // the cloud up to SPZ's quantisation
143
- console.log(spz.length, sog.length, back.positions.length / 3);
144
- ```
145
-
146
- - Both start from the stored attributes: axis scales and rotation from each covariance (eigen-decomposition), display
147
- (sRGB) colour from linear, exactly for the base band and to first order for the view-dependent terms.
148
- - SPZ: positions are 24-bit fixed point with the most fractional bits that fit the largest coordinate (up to 16;
149
- `fractionalBits` to choose), opacity, colour and log scale one byte each, rotations the smallest-three 10-bit
150
- packing, spherical harmonics one byte per coefficient. Version 3 is written (gzip), which version 3 and 4 readers
151
- read.
152
- - SOG: positions are 16-bit after a log transform within the cloud's bounds, log scales and base colours 256-entry
153
- codebooks (1D k-means), rotations three bytes, opacity a byte. Spherical-harmonic bands use a palette of up to
154
- 65,536 entries: each splat's own when the cloud has at most 65,536 splats, else the means of equal groups along the
155
- bands' principal axis, which blurs view-dependent colour on large clouds. The WebP textures are lossless, written by
156
- a built-in encoder whose images Margo's decoder and the browser's (`createImageBitmap`) read back exactly.
157
- - From a `Splats` cloud edited on the GPU, export `await cloud.read()` (or `await brush.commit()`).
158
-
159
- `gpuState` exposes sorted key/index pairs, projected ellipses and evaluated colors (fogged while a fog is set) for diagnostics. Ellipse records are eight floats: normalized center xyz and opacity, then two normalized-screen ellipse axes. `dispose()`/`destroy()` releases all owned GPU resources. Device restoration reuploads the copied input and recreates sorting/rendering passes. The package stays outside core/stage and has no dependencies on other optional renderers; parser-only imports discard GPU code. It follows the workspace's `@margoengine/*` naming convention.
160
-
161
- ## Depth with meshes (`./depth`)
162
-
163
- Meshes drawn before a cloud (every `@margoengine/materials` mesh) already hide the splats behind them: the cloud depth
164
- tests against the scene. What draws after the cloud (later passes, other clouds, points, particles, post effects that
165
- read depth) cannot see it, because splats blend and write no depth. `SplatDepth` writes it:
166
-
167
- ```ts
168
- import {Engine} from 'margoengine/core';
169
- import {Splats} from 'margoengine/splats';
170
- import {SplatDepth} from 'margoengine/splats/depth';
171
- const engine = await Engine.create(document.querySelector('canvas')!);
172
- const cloud = Splats.attach(engine, {
173
- positions: new Float32Array([0, 0, 0]),
174
- covariances: new Float32Array([0.25, 0, 0, 0.25, 0, 0.01]),
175
- colors: new Float32Array([1, 0, 0, 0.95]),
176
- });
177
- const depth = SplatDepth.attach(engine, cloud, {threshold: 0.5});
178
- depth.threshold = 0.3; // live: lower writes more of a thin capture
179
- ```
180
-
181
- - Right after the cloud draws (frame-graph order 3.5, option `order`), each splat writes the scene depth where its own
182
- Gaussian opacity at the pixel reaches `threshold` (default 0.5; the colour pass caps opacity at 0.99, so 1 writes
183
- nothing). The nearest such splat wins (reversed Z). No colour is written, and the cloud draws exactly as before.
184
- - It is alpha-tested depth, not accumulated: a pixel where many faint splats add up to a solid look, each under the
185
- threshold, gets no depth. On the real raccoon capture (test fixture) threshold 0.5 gave depth to 1,514 of the 4,463
186
- pixels the capture covers; lower it for thin captures.
187
- - Depth is the splat's centre depth over its whole ellipse, as the colour pass places it.
188
- - `dispose()` stops the writes; a cloud that is not attached, or is disposed, writes nothing.
189
-
190
- ## Streamed level of detail (`./lod`)
191
-
192
- For captures larger than one cloud takes (3,000,000 splats) or than a GPU should draw at once, `./lod` draws a cut of a
193
- splat hierarchy chosen by the view, loading only the nodes the cut needs:
194
-
195
- ```ts
196
- import {Engine} from 'margoengine/core';
197
- import {parsePly} from 'margoengine/splats/data';
198
- import {SplatLod, buildSplatLod} from 'margoengine/splats/lod';
199
- const engine = await Engine.create(document.querySelector('canvas')!);
200
- const capture = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
201
- const lod = SplatLod.attach(engine, buildSplatLod(capture, {leafSize: 1024}), {budget: 1_000_000, maxError: 2});
202
- engine.start();
203
- await lod.settled(); // the current view is fully streamed in
204
- console.log(lod.selected.length, lod.drawn);
205
- ```
206
-
207
- - `buildSplatLod(data, {leafSize})` splits the capture into an octree until a cell holds at most `leafSize` splats
208
- (default 65,536); leaves keep the trained splats untouched, and each inner cell gets a moment-matched merge of its
209
- splats (`decimateSplats`) on the coarsest grid that still fits `leafSize`, with that grid cell as its `error`.
210
- - A streamed capture is any `SplatLodSource`: `{nodes, coefficients, load(index, signal)}`, each node a bounding sphere,
211
- an `error` in world units (0 for a leaf), its `count` and `children`. `load` may fetch the node (for instance a
212
- `.splat` from `encodeSplat`, one file per node) and must return `count` splats with `coefficients` SH.
213
- - Each frame, before the splats project, `chooseSplatNodes` replaces the node of largest projected error
214
- (`error x focal / distance`, pixels) by its children while that error exceeds `maxError` (default 2), all its children
215
- are loaded and the cut fits `budget` (default 1,000,000). Children it lacks are loaded, at most `concurrency` (4) at
216
- a time; until they arrive the parent stays, so streaming never leaves a hole.
217
- - Drawn nodes live in fixed slots of one `Splats` (`lod.cloud`, `budget` rounded down to whole slots of the largest
218
- node, and to no more slots than the source has leaves), written with `Splats.write` and hidden with `Splats.clear`, so every drawn node sorts together. Loaded nodes
219
- stay on the CPU up to `cache` splats (twice the budget), oldest dropped first.
220
- - `Splats.reserve(count, coefficients)` makes such a pool of hidden splats; `write(first, data)` and
221
- `clear(first, count)` work on any cloud.
222
- - `lod.placement` maps each drawn node to the pool index of its first splat, for picking or editing.
223
- - On the real raccoon fixture (41 nodes of at most 1,024 splats) `maxError: 0` streams in all 8,385
224
- leaf splats and draws exactly what one plain cloud of the pool's splats draws; against the capture in its own order
225
- 188 of 262,144 channels differ (exact depth ties blend in another order); 400 units away the root alone. A procedural stand-in of 16,777,216 splats (256 leaves of 65,536) streams within a
226
- 2,097,152 budget (1,110,016 drawn, 16 leaves near the camera).
227
-
228
- ## One sort for many clouds (`./set`)
229
-
230
- Separate `Splats` clouds sort and draw one after the other, so where two captures overlap the one drawn last covers the
231
- other whole. A `SplatSet` puts every cloud added to it into ranges of one pooled `Splats`, so all their splats sort and
232
- blend far to near together, as one merged cloud would, while each stays movable and removable on its own:
233
-
234
- ```ts
235
- import {Engine} from 'margoengine/core';
236
- import {parsePly} from 'margoengine/splats/data';
237
- import {SplatSet} from 'margoengine/splats/set';
238
- const engine = await Engine.create(document.querySelector('canvas')!);
239
- const capture = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
240
- // Every member has the set's SH count: this capture's coefficients per channel (0 when it has none).
241
- const coefficients = (capture.sphericalHarmonics?.length ?? 0) / capture.positions.length;
242
- const set = SplatSet.attach(engine, {capacity: 500_000, coefficients});
243
- const first = set.add(capture);
244
- const second = set.add(capture, {matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1]});
245
- engine.start();
246
- second.setMatrix([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 3, 0, 0, 1]); // move it
247
- first.remove(); // its range is free again
248
- ```
249
-
250
- - `capacity` (1 to 3,000,000, default 1,000,000) is the pool; `coefficients` (0, 4, 9 or 16) the SH count every
251
- member must have. `add` takes the first free range that holds the cloud and throws a RangeError when none does.
252
- - A member's `setMatrix(matrix)` rewrites its splats from its own data moved by the matrix (`transformSplats`);
253
- `remove()` hides them and frees the range, merged with free neighbours.
254
- - `member.visible = false` hides a part and `member.opacity = 0.5` fades it (0 to 1, times each splat's own opacity),
255
- without rewriting its covariances or SH: only its positions and colours (32 of the 128 bytes a splat takes) go to the
256
- GPU, and `setMatrix` keeps both settings. `Splats.setOpacities(first, alphas, scale)` is the same for any range.
257
- - Every pool splat is projected and sorted each frame, free ranges too (hidden, culled before drawing), so size
258
- `capacity` to what you add.
259
-
260
- ## Editing session (`./session`)
261
-
262
- `SplatEditSession` is a splat editor's tool set on the CPU (so it also runs headless): select by brush, rectangle,
263
- lasso (screen space, from a view-projection matrix), sphere or box (world space), by colour or by opacity, with
264
- replace/add/subtract modes, invert and clear; hide, unhide and delete the selection; move, turn and scale it (covariances
265
- and SH follow, optionally about a pivot); adjust its colour; undo and redo (each step keeps only the rows it changed,
266
- 64 steps by default, `maxHistory`); export the result. The tool list follows the public feature lists of SuperSplat;
267
- selection by region matches `./edit`'s GPU brush, which stays the choice for strokes on a cloud of millions drawn
268
- this frame.
269
-
270
- ```ts
271
- import {parsePly} from 'margoengine/splats/data';
272
- import {SplatEditSession} from 'margoengine/splats/session';
273
- const session = new SplatEditSession(parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
274
- session.selectByOpacity(0, 0.05).deleteSelected(); // drop faint floaters
275
- session.selectSphere([0, 1, 0], 0.5).transformSelected([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0.2, 0, 1]);
276
- session.selectByColor([1, 0, 0], 0.3).adjustColor({hue: 90, saturation: 1.2});
277
- session.undo(); // the colour change
278
- const file = await session.encode('ply'); // or 'spz', 'splat', 'sog'; hidden and deleted splats are left out
279
- ```
280
-
281
- `SplatEditSession.fromCloud(cloud)` starts from a cloud's data (GPU edits included) and `session.applyTo(cloud)` writes the
282
- edit back (hidden and deleted splats at opacity 0). Selection by screen region takes
283
- `{viewProjection, width, height}`: a column-major 4x4 and the pixel size; centres behind the camera are never hit.
284
- Sources: Kerbl et al. 2023, "3D Gaussian Splatting for Real-Time Radiance Field Rendering"; Chen et al. 2024,
285
- "GaussianEditor: Swift and Controllable 3D Editing with Gaussian Splatting" (arXiv:2311.14521) for the edit operations.
286
- Limits: history holds a full selection mask per selection step (1 byte per splat), so at 3,000,000 splats 64 selection
287
- steps can take about 190 MB; lower `maxHistory` for that. SH colour adjust changes the base band only.
288
-
289
- ## Scene light and shadows (`./lighting`)
290
-
291
- `SplatLighting` relights a cloud with the engine's directional light and ambient every frame, and is a
292
- `@margoengine/shadows` source, so the capture casts shadows on meshes (its caster shader declares the position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit):
293
-
294
- ```ts
295
- import {Engine, box} from 'margoengine/core';
296
- import {Splats} from 'margoengine/splats';
297
- import {parsePly} from 'margoengine/splats/data';
298
- import {SplatLighting} from 'margoengine/splats/lighting';
299
- import {Shadows} from 'margoengine/shadows';
300
- const engine = await Engine.create(document.querySelector('canvas')!);
301
- const ground = engine.createMesh().setGeometry(box()).setScale([20, 0.1, 20]).setPosition([0, -2, 0]);
302
- const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
303
- const lit = SplatLighting.attach(engine, cloud);
304
- const shadows = Shadows.attach(engine);
305
- shadows.add(ground, {static: true});
306
- shadows.add(lit); // the splats cast on the ground
307
- engine.lighting.direction.set([0.6, 1, 0.2, 3]); // toward the sun, w intensity
308
- engine.start();
309
- ```
310
-
311
- - Relighting scales each splat's colour by core's diffuse terms: `nl * radiance * intensity / pi + radiance.w *
312
- ambient`, with `nl` from the splat's flat axis (the axis of its smallest covariance eigenvalue, turned to the
313
- camera; the view direction for a round splat). `relight: false` (live) keeps the captured colours and still casts.
314
- - The captured colours already hold the light they were filmed in, so a relit capture is lit twice; it reads best
315
- under soft capture light. Splats do not receive shadows, and the light has no specular term.
316
- - Shadows: each splat draws its ellipse in the light's view (with the colour pass's 0.3 px^2 dilation in shadow-map
317
- texels). By default a splat blocks each texel with the probability of its opacity there (stochastic transparency),
318
- so overlapping splats shade as their combined opacity, noisy per texel and smoothed by the shadow filter;
319
- `threshold` (0 to 1, live) instead blocks where one splat's opacity reaches it, without noise.
320
-
321
- ## Animated splats (`./animate`)
322
-
323
- `SplatSequence` plays a 4D capture (a list of frames of the same splats); `SplatSkin` poses a cloud with a skeleton
324
- by linear blend skinning, for captured performances:
325
-
326
- ```ts
327
- import {Engine} from 'margoengine/core';
328
- import {Splats} from 'margoengine/splats';
329
- import {parsePly, transformSplats} from 'margoengine/splats/data';
330
- import {SplatSequence, SplatSkin} from 'margoengine/splats/animate';
331
- const engine = await Engine.create(document.querySelector('canvas')!);
332
- const first = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
333
- const frames = [0, 1, 2, 3].map((k) => transformSplats(first, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, k * 0.1, 0, 1]));
334
- const performer = Splats.attach(engine, first);
335
- const sequence = SplatSequence.attach(engine, performer, frames, {fps: 12});
336
- sequence.speed = 0.5; // live: time, speed, playing, loop
337
- const n = first.positions.length / 3;
338
- const second = Splats.attach(engine, first);
339
- const skin = SplatSkin.attach(engine, second, {
340
- joints: 2,
341
- indices: Array.from({length: n * 4}, (_, i) => (i % 4 === 0 ? (first.positions[(i / 4) * 3 + 1] > 0 ? 1 : 0) : 0)),
342
- weights: Array.from({length: n * 4}, (_, i) => (i % 4 === 0 ? 1 : 0)),
343
- });
344
- skin.matrices.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0.5, 0, 0, 1], 16); // joint 1: move the top half 0.5 along x
345
- engine.start();
346
- console.log(sequence.duration, (await second.read()).positions.length);
347
- ```
348
-
349
- - Both run one compute pass before the cloud projects and write its GPU inputs, so sorting, `./depth`,
350
- `./lighting` and `./edit` see the pose; `cloud.read()` returns the posed cloud.
351
- - A sequence mixes centres, covariances, colours and opacity of the two frames around `time` linearly (a mix of
352
- positive-definite covariances stays positive definite); SH stays the cloud's. Every frame lives on the GPU, 64 bytes
353
- per splat, so a long capture at 3,000,000 splats does not fit: stream frames into a few sequences instead.
354
- - A skin moves each centre by the weighted sum of up to four joint matrices and each covariance by the blend's linear
355
- part, A S A^T; weights are normalised, all zero keeps a splat at rest. The rest pose is the cloud as it is when first
356
- posed, or after `rebind()` (call it after `Splats.write`). Like any linear blend skin, a blend of two far-turned
357
- joints shrinks the splats between them. Colours and SH are not turned with the joints.
358
-
359
- ## Picking and brush editing (`./edit`)
360
-
361
- `SplatBrush` picks, selects, erases and paints splats on the GPU, for clean-up tools. Regions are in pixels of the
362
- frame the cloud last drew (`brush.frame`), from the top-left corner:
363
-
364
- ```ts
365
- import {Engine} from 'margoengine/core';
366
- import {Splats} from 'margoengine/splats';
367
- import {parsePly} from 'margoengine/splats/data';
368
- import {SplatBrush} from 'margoengine/splats/edit';
369
- const engine = await Engine.create(document.querySelector('canvas')!);
370
- const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
371
- const brush = SplatBrush.attach(engine, cloud);
372
- engine.render({delta: 0}); // the brush works on a drawn frame
373
- const [width, height] = brush.frame;
374
- const hit = await brush.pick(width / 2, height / 2); // the nearest splat at the pixel, or -1
375
- brush.select({x: width / 2, y: height / 2, radius: 30}); // replace the selection
376
- brush.select({x: 0, y: 0, width: 40, height: 40}, 'add'); // or 'subtract'
377
- brush.erase('selection'); // opacity 0, as Splats.clear
378
- brush.paint({x: width / 4, y: height / 2, radius: 20}, [0.8, 0.1, 0.1], 0.5); // linear RGB, strength
379
- const edited = await brush.commit(); // the edited cloud as SplatData, for export
380
- console.log(hit, (await brush.selection()).length, edited.colors.length);
381
- engine.start();
382
- ```
383
-
384
- - One compute dispatch per operation over every splat, against the ellipses the cloud projected for the last
385
- frame: a splat is in a region when its projected centre is and it was drawn. Picking takes the nearest splat whose
386
- own opacity at the pixel (its Gaussian falloff times its opacity) reaches `threshold` (default 0.1).
387
- - Edits change the cloud's GPU buffers at once and show from the next frame. `commit()` (`cloud.read()`) copies them
388
- into the cloud's data, which `Splats.write`, export and device restoration use: a device loss before a commit
389
- drops the edits since the last one.
390
- - Painting blends the colour by `strength` and keeps opacity; on a cloud with spherical harmonics it sets the DC term
391
- to the blended colour and fades the higher bands by the same strength.
392
- - The selection lives on the GPU (4 bytes per splat); `selection()` reads it back as indices. A restored device
393
- starts with an empty selection.
394
-
395
- ## Picking with meshes (`./pick`)
396
-
397
- `SplatBrush.pick` sees splats only. `SplatPicking` adds a cloud to `Picking` from `margoengine/selection`, so one
398
- `engine.pick`, `picking.pick` or `picking.pickMany` answers whichever of splats and meshes is nearest at the pixel. A mesh
399
- in front of a splat blocks it, and a splat in front of a mesh wins:
400
-
401
- ```ts
402
- import {Engine, box} from 'margoengine/core';
403
- import {Splats} from 'margoengine/splats';
404
- import {parsePly} from 'margoengine/splats/data';
405
- import {SplatPicking} from 'margoengine/splats/pick';
406
- import {Picking} from 'margoengine/selection';
407
- const engine = await Engine.create(document.querySelector('canvas')!);
408
- engine.createMesh().setGeometry(box());
409
- const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
410
- const picking = Picking.attach(engine);
411
- const splatPicking = SplatPicking.attach(picking, cloud); // {threshold: 0.1} by default
412
- const hit = await picking.pick(128, 96); // PickHit, in canvas CSS pixels
413
- if (hit && splatPicking.splatsOf(hit.mesh)) console.log('splat', hit.splat, 'of', hit.splats);
414
- else if (hit) console.log('mesh', hit.mesh);
415
- const hits = await picking.pickMany([[10, 20], [64, 64]]); // one readback for both
416
- console.log(hits.map((h) => h?.splat ?? null));
417
- engine.start();
418
- ```
419
-
420
- - A pick projects every splat of the cloud again for its 3 x 3 tile, with the colour pass's own projection (the same
421
- WGSL function), in a vertex shader: it needs no drawn frame and follows the current camera, perspective or
422
- orthographic, the antialias flag, brush erasing (`./edit`) and poses (`./animate`), which write the same GPU inputs.
423
- - A splat hits where its Gaussian times its opacity at the pixel, capped at 0.99 as drawn, reaches `threshold`
424
- (default 0.1, as `SplatBrush.pick`; settable). Among those the nearest splat centre wins, and it then competes with
425
- the meshes at that depth.
426
- - `picking.pick` returns `PickHit | null`, with the mesh and splat metadata used above. `engine.pick` returns only
427
- `Mesh | null`, without those hit fields. On a splat hit, `hit.mesh` is an empty stand-in mesh; `splatsOf(mesh)` maps
428
- it back to the cloud.
429
- `hit.splat` is the splat's index in the cloud (a pool index under `SplatSet` and `SplatLod`). `dispose()` leaves
430
- Picking and frees the stand-in; the cloud stays.
431
- - A pick's cost grows with the cloud: four vertices of projection per splat, every pick. Picking takes up to 8 overlays.
432
-
433
- ### Attaching from a second scene
434
-
435
- `SplatModifier.attach` and `loadProgressiveSplats` remember the scene that is active when you call them, before their first await, and join that scene when they finish. Start it inside a second scene's plugin `setup` and the plugin belongs to that scene; start it anywhere else and it belongs to the default scene. An abort or a failure leaves nothing in either scene.
436
-
437
- ## Preview tier contract
438
-
439
- GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.
440
-
441
- ## Film time
442
-
443
- `SplatSequence` and `SplatModifier` move `time` (by `speed`, while `playing`) in the frame update with `advanceTime(delta)`, not in their passes, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the frame a continuous run shows.
1
+ # @margoengine/splats
2
+
3
+ Optional Gaussian splats with GPU covariance projection and stable compute radix sorting.
4
+
5
+ Import `margoengine/splats` from the `margoengine` package, or `@margoengine/splats` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
6
+
7
+ Use `@margoengine/splats/data` for `parseSplat`, `validateSplats` and the
8
+ `SplatData` type without loading GPU rendering or radix-sort shaders. Root
9
+ exports retain the same functions for applications that also render splats.
10
+
11
+ Optional WebGPU Gaussian rendering that accepts 1-3,000,000 world-space splats (an input cap, not a frame-rate promise: adapter storage/memory limits may allow fewer, and frame time at the cap depends on the GPU). Compute projects each positive-definite 3D covariance through the camera Jacobian into a 2D ellipse with a 0.3-pixel variance floor. The Jacobian is linearised at the splat's view direction clamped to 1.3 times the half-view tangent, as trained captures expect, so a splat beside or behind the edge of the view cannot stretch across the frame. Instanced quads cover three standard deviations; the fragment shader evaluates Gaussian opacity and blends far to near against read-only reversed scene depth.
12
+
13
+ ```ts
14
+ import {EngineKernel} from 'margoengine/core';
15
+ import {Splats,parseSplat} from 'margoengine/splats';
16
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
17
+ const response = await fetch('/capture.splat');
18
+ if (!response.ok) throw new Error('Failed to load splats: '+response.status);
19
+ const cloud = Splats.attach(engine, parseSplat(await response.arrayBuffer()));
20
+ engine.start();
21
+ // cloud.dispose() when unloading; engine.dispose() releases attached plugins.
22
+ ```
23
+
24
+ The executable README check maps `/capture.splat`, `/capture.ply`, `/capture.spz` and `/capture.sog` to
25
+ the documented 8,385-splat excerpt of Niantic's raccoon capture (MIT), preserving the format each example
26
+ requests. The PLY/SPZ/SOG fixtures are the documented real-data inputs; `.splat` is serialized here
27
+ from that PLY with `encodeSplat`. This exercises the examples on a real excerpt, without a complete-capture
28
+ quality, performance or independent `.splat` encoder-accuracy claim. See [fixture provenance](test/fixtures/NOTICE.md).
29
+
30
+ For generated data, supply `SplatData`: `positions` has three Float32 values per splat; `covariances` has six (xx, xy, xz, yy, yz, zz); `colors` has four (linear RGB and opacity, each 0..1). Construction validates lengths, finite values and positive-definite covariance, then copies the data for ownership/device recovery. Colors are converted to sRGB for ordinary display targets and remain linear in HDR targets.
31
+
32
+ Optional `sphericalHarmonics` contains 4, 9 or 16 coefficients per splat, with RGB interleaved for each coefficient. Evaluation uses the real SH basis through degree 3, the camera-to-splat direction, and the usual 0.5 offset. SH replaces RGB; `colors` still supplies opacity. Large SH buffers can exceed an adapter's storage binding limit even when the base cloud fits; attachment rejects before allocating. `parseSplat()` decodes the common 32-byte binary layout (xyz, positive xyz scales, byte RGBA, byte quaternion in wxyz order), converts byte sRGB to linear, normalizes quaternions and derives covariance. `parsePly()` reads Gaussian-splat PLY files (below); `parseSpz()` and `parseSog()` read compressed captures (below); training is outside this package.
33
+
34
+ Orthographic cameras (any `camera.matrix` with a constant clip w, such as `CameraProjection` from `@margoengine/cameras`) use the affine Jacobian: a splat's pixel size depends only on the zoom, not its depth. The depth range is the projection's own near/far, which may lie behind the eye, sort keys are measured from the near plane, and spherical harmonics use the fixed viewing direction. The package reads only the clip matrix and does not depend on the cameras package.
35
+
36
+ Each frame creates sortable unsigned depth keys on the GPU. Eight stable 4-bit LSD radix passes run per-workgroup histograms, hierarchical exclusive prefix scans, a scan of block totals, and scatter. Workgroup bit masks and population counts preserve input order within equal digits; equal-depth splats retain source order. Off-frustum, transparent and out-of-range centers sort to the end and render no fragments. The runtime performs no CPU sorting, per-splat frame allocation or GPU readback.
37
+
38
+ Base GPU allocations are approximately 128 bytes per splat (384 MB at three million), plus small histograms/uniforms and optional SH. CPU copies for recovery are additional. Center-depth sorting approximates intersecting ellipsoids; near-plane-crossing centers are culled. Multiple clouds sort independently: combine overlapping clouds into one data set when global order matters. Splats do not write depth unless `./depth` is attached (below), cast directional shadows or receive PBR lighting. They can render alongside shadows, clustered meshes, animation, VFX and TAA; temporal history uses underlying opaque depth. Frame rate and sorting time depend on hardware and fill rate, with no 1-2 ms or locked-60-FPS guarantee.
39
+
40
+ `cloud.setFog(fog)` fogs the cloud with `@margoengine/environment`'s `Fog` or any object with its fields (`color`, `near`, `far`, `density`, `heightFalloff`, `height`, `enabled`), read every frame with Fog's maths. Each splat's colour fades toward the fog colour by the fog at its centre, in the projection pass and in linear before the display encoding; opacity is unchanged. The package does not import environment. `fog.enabled = false` clears it without recompiling; `cloud.setFog(null)` (the default) draws exactly as before.
41
+
42
+ ```ts
43
+ import {Fog} from 'margoengine/environment';
44
+ import {Splats, parseSplat} from 'margoengine/splats';
45
+ import {Engine} from 'margoengine/core';
46
+ const engine = await Engine.create(document.querySelector('canvas')!);
47
+ const cloud = Splats.attach(engine, parseSplat(await (await fetch('/capture.splat')).arrayBuffer()));
48
+ cloud.setFog(Fog.attach(engine, {color: '#8090a0', density: 0.02}));
49
+ ```
50
+
51
+ `cloud.antialias = true` turns on Mip-Splatting's 2D filter (Yu et al. 2024): each splat's opacity is scaled by
52
+ sqrt(det(S) / det(S + 0.3 I)) of its screen covariance S, so a splat smaller than a pixel fades with its coverage
53
+ instead of drawing as a 0.3 px^2 blob at full opacity, and far or small captures stop shimmering and thickening.
54
+ Splats several pixels wide keep nearly all their opacity. It is live (no recompile) and off by default, the look
55
+ trained 3DGS files expect; a capture trained with the filter (SPZ's antialiased flag) should turn it on.
56
+
57
+ ```ts
58
+ import {Splats} from 'margoengine/splats';
59
+ import {parsePly} from 'margoengine/splats/data';
60
+ import {Engine} from 'margoengine/core';
61
+ const engine = await Engine.create(document.querySelector('canvas')!);
62
+ const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
63
+ cloud.antialias = true;
64
+ engine.start();
65
+ ```
66
+
67
+ ## With glass
68
+
69
+ The cloud sorts against itself and blends over the scene, so glass in front of it comes out wrong. `addEffect` from
70
+ [`margoengine/oit/vfx`](../oit/README.md#particles-splats-and-points-addeffect) draws it in the same pass as the glass:
71
+
72
+ ```ts
73
+ import {Engine} from 'margoengine/core';
74
+ import {ExactOIT} from 'margoengine/oit/exact';
75
+ import {addEffect} from 'margoengine/oit/vfx';
76
+ import {Splats} from 'margoengine/splats';
77
+ const engine = await Engine.create(document.querySelector('canvas')!);
78
+ const cloud = Splats.attach(engine, {
79
+ positions: new Float32Array([0, 0, -1]),
80
+ covariances: new Float32Array([0.1, 0, 0, 0.1, 0, 0.1]),
81
+ colors: new Float32Array([0.2, 0.6, 1, 0.8]),
82
+ });
83
+ addEffect(ExactOIT.attach(engine, {layers: 32}), cloud);
84
+ ```
85
+
86
+ The depth sort stops while it is in the pass, and `ExactOIT` keeps only the nearest `layers` per pixel, so a dense capture
87
+ looks thinner than its own draw. Leave a capture on its own draw unless glass must cut through it.
88
+
89
+ ## PLY captures, editing and level of detail (`./data`)
90
+
91
+ ```ts
92
+ import {EngineKernel} from 'margoengine/core';
93
+ import {Splats} from 'margoengine/splats';
94
+ import {cropSplats, decimateSplats, encodeSplat, mergeSplats, parsePly, transformSplats} from 'margoengine/splats/data';
95
+
96
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend: 'webgpu'});
97
+ const response = await fetch('/capture.ply'); // a trained Gaussian-splat PLY
98
+ if (!response.ok) throw new Error('Failed to load splats: ' + response.status);
99
+ let cloud = parsePly(await response.arrayBuffer());
100
+ // Training frames are often Y-down: turn 180 degrees about X to stand the capture up in Margo's Y-up world.
101
+ cloud = transformSplats(cloud, [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]);
102
+ cloud = cropSplats(cloud, {sphere: {center: [0, 0, 0], radius: 5}}); // drop floaters far from the subject
103
+ const preview = decimateSplats(cloud, {cellSize: 0.05}); // a coarser cloud for a distant view
104
+ const both = mergeSplats(cloud, transformSplats(cloud, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 4, 0, 0, 1]));
105
+ const saved = new Blob([encodeSplat(cloud)]); // back to .splat, for parseSplat or other viewers
106
+ Splats.attach(engine, preview);
107
+ engine.start();
108
+ console.log(both.positions.length / 3, saved.size);
109
+ ```
110
+
111
+ - **`parsePly(bytes)`** reads the PLY layout Gaussian-splat training writes (`binary_little_endian` or `ascii`, one `vertex` element with `x y z`, `f_dc_0..2`, optional `f_rest_*` for SH degrees 1-3, `opacity` as a logit, `scale_0..2` as logs and `rot_0..3` as w x y z). Opacity goes through the sigmoid, scales through exp, rotation and scale become the covariance. These files store display (sRGB) colour; the base colour is converted to linear exactly and the view-dependent terms to first order around it, since the renderer works in linear. Coordinates are kept as stored. Big-endian and packed (chunked) PLY files throw a `MargoError` with code `unsupported`; files without the splat properties throw a `RangeError` naming what is missing.
112
+ - **`splatsFromAttributes(raw, {linear})`** turns attributes as training stores them (`GaussianAttributes`: positions, log scales, w x y z rotations, band-0 and higher SH, opacity) into `SplatData`, for readers of other containers (`@margoengine/gltf/splats` uses it). `linear: true` is for colour stored linear, in place of display colour. Every reader goes through it, so a splat flatter than Float32 can store keeps an axis at 1/1024 of its longest, or a whole file of real captures would be refused; projection adds 0.3 px^2 to each ellipse, so the lift never shows.
113
+ - **`encodeSplat(data)`** writes the 32-byte `.splat` layout `parseSplat` reads, splitting each covariance into axis scales and a rotation (`decomposeCovariance`, Jacobi). `.splat` has no SH, so the base colour is kept; a round trip is exact to byte precision.
114
+ - **`cropSplats(data, {box: {min, max}} | {sphere: {center, radius}}, {invert})`** keeps the splats whose centres are inside (or outside) the region; **`filterSplats(data, keep)`** keeps those `keep(index)` accepts. SH travels with the kept splats.
115
+ - **`transformSplats(data, matrix)`** applies a column-major 4x4 affine matrix: centres by the matrix, covariances by its linear part (scale and shear stretch the splats), and SH by the matrix's rotation (from its polar decomposition, by an exact least-squares fit per SH band), so view-dependent colour turns with the cloud.
116
+ - **`mergeSplats(...clouds)`** concatenates clouds with the same SH degree. **`decimateSplats(data, {cellSize})`** merges the splats of each grid cell into one Gaussian with the same weighted mean and second moment (weights: opacity times volume); colour, opacity and SH are the weighted means. It is a moment-matched preview level, not a trained one.
117
+ - **`parseSpz(bytes, {signal})`** reads SPZ versions 2, 3 and 4 (24-bit fixed-point positions, byte log-scales, byte colours, 3-byte or smallest-three rotations, SH degrees 0-3). Versions 2 and 3 are one gzip stream and need `DecompressionStream` (current browsers, Node 18+). Version 4, the default of current exporters such as PlayCanvas splat-transform, is a plain header, a table of contents and one Zstandard stream per attribute; it is read by a built-in Zstandard decoder (RFC 8878: Huffman and FSE, repeat offsets, content checksums, several and skippable frames), which loads only when a version 4 file arrives. Each stream is limited to the size the table of contents declares; a version 2 or 3 gzip stream stops with a `RangeError` once it expands past the largest possible body (3,000,000 degree-3 splats, 195,000,016 bytes), and a deflated SOG ZIP entry once it passes its declared size, so a small hostile file cannot inflate without bound. Damaged, truncated or checksum-failing files throw a `RangeError` saying to check the file; a stream that needs a Zstandard dictionary throws a `MargoError` with code `unsupported`.
118
+ - **`parseSog(bytes | files, {signal})`** reads SOG version 2, bundled (`.sog` ZIP) or as loose files (`meta.json` plus its lossless WebP textures; `@margoengine/decoders/webp-lossless` bundled in, no image API needed). It needs `DecompressionStream` for deflated ZIP entries; lossy SOG textures throw a `MargoError` with code `unsupported`.
119
+ - Both return a promise and honour an `AbortSignal`. They are tested against real captures (`test/fixtures/NOTICE.md`): SPZ version 2 and SOG bit for bit against the PlayCanvas splat-transform decode, SPZ version 4 bit for bit against version 3 of the same scene.
120
+
121
+ ```ts
122
+ import {parseSog, parseSpz} from 'margoengine/splats/data';
123
+
124
+ const abort = new AbortController();
125
+ // Any SPZ version: 2 and 3 (gzip) or 4 (Zstandard), detected from the file.
126
+ const spz = await parseSpz(await (await fetch('/capture.spz')).arrayBuffer(), {signal: abort.signal});
127
+ const sog = await parseSog(await (await fetch('/capture.sog')).arrayBuffer());
128
+ console.log(spz.positions.length / 3, sog.positions.length / 3);
129
+ ```
130
+
131
+ ## Compressed export (`./data`)
132
+
133
+ `encodeSpz` and `encodeSog` write a cloud as SPZ (version 3) or a bundled SOG (version 2), so an edited capture ships
134
+ small; `encodeSplat` writes the 32-byte `.splat` layout:
135
+
136
+ ```ts
137
+ import {encodeSog, encodeSpz, parsePly, parseSpz} from 'margoengine/splats/data';
138
+
139
+ const cloud = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
140
+ const spz = await encodeSpz(cloud); // gzip, about a tenth of the PLY
141
+ const sog = await encodeSog(cloud); // ZIP of meta.json and lossless WebP textures
142
+ const back = await parseSpz(spz); // the cloud up to SPZ's quantisation
143
+ console.log(spz.length, sog.length, back.positions.length / 3);
144
+ ```
145
+
146
+ - Both start from the stored attributes: axis scales and rotation from each covariance (eigen-decomposition), display
147
+ (sRGB) colour from linear, exactly for the base band and to first order for the view-dependent terms.
148
+ - SPZ: positions are 24-bit fixed point with the most fractional bits that fit the largest coordinate (up to 16;
149
+ `fractionalBits` to choose), opacity, colour and log scale one byte each, rotations the smallest-three 10-bit
150
+ packing, spherical harmonics one byte per coefficient. Version 3 is written (gzip), which version 3 and 4 readers
151
+ read.
152
+ - SOG: positions are 16-bit after a log transform within the cloud's bounds, log scales and base colours 256-entry
153
+ codebooks (1D k-means), rotations three bytes, opacity a byte. Spherical-harmonic bands use a palette of up to
154
+ 65,536 entries: each splat's own when the cloud has at most 65,536 splats, else the means of equal groups along the
155
+ bands' principal axis, which blurs view-dependent colour on large clouds. The WebP textures are lossless, written by
156
+ a built-in encoder whose images Margo's decoder and the browser's (`createImageBitmap`) read back exactly.
157
+ - From a `Splats` cloud edited on the GPU, export `await cloud.read()` (or `await brush.commit()`).
158
+
159
+ `gpuState` exposes sorted key/index pairs, projected ellipses and evaluated colors (fogged while a fog is set) for diagnostics. Ellipse records are eight floats: normalized center xyz and opacity, then two normalized-screen ellipse axes. `dispose()`/`destroy()` releases all owned GPU resources. Device restoration reuploads the copied input and recreates sorting/rendering passes. The package stays outside core/stage and has no dependencies on other optional renderers; parser-only imports discard GPU code. It follows the workspace's `@margoengine/*` naming convention.
160
+
161
+ ## Depth with meshes (`./depth`)
162
+
163
+ Meshes drawn before a cloud (every `@margoengine/materials` mesh) already hide the splats behind them: the cloud depth
164
+ tests against the scene. What draws after the cloud (later passes, other clouds, points, particles, post effects that
165
+ read depth) cannot see it, because splats blend and write no depth. `SplatDepth` writes it:
166
+
167
+ ```ts
168
+ import {Engine} from 'margoengine/core';
169
+ import {Splats} from 'margoengine/splats';
170
+ import {SplatDepth} from 'margoengine/splats/depth';
171
+ const engine = await Engine.create(document.querySelector('canvas')!);
172
+ const cloud = Splats.attach(engine, {
173
+ positions: new Float32Array([0, 0, 0]),
174
+ covariances: new Float32Array([0.25, 0, 0, 0.25, 0, 0.01]),
175
+ colors: new Float32Array([1, 0, 0, 0.95]),
176
+ });
177
+ const depth = SplatDepth.attach(engine, cloud, {threshold: 0.5});
178
+ depth.threshold = 0.3; // live: lower writes more of a thin capture
179
+ ```
180
+
181
+ - Right after the cloud draws (frame-graph order 3.5, option `order`), each splat writes the scene depth where its own
182
+ Gaussian opacity at the pixel reaches `threshold` (default 0.5; the colour pass caps opacity at 0.99, so 1 writes
183
+ nothing). The nearest such splat wins (reversed Z). No colour is written, and the cloud draws exactly as before.
184
+ - It is alpha-tested depth, not accumulated: a pixel where many faint splats add up to a solid look, each under the
185
+ threshold, gets no depth. On the real raccoon capture (test fixture) threshold 0.5 gave depth to 1,514 of the 4,463
186
+ pixels the capture covers; lower it for thin captures.
187
+ - Depth is the splat's centre depth over its whole ellipse, as the colour pass places it.
188
+ - `dispose()` stops the writes; a cloud that is not attached, or is disposed, writes nothing.
189
+
190
+ ## Streamed level of detail (`./lod`)
191
+
192
+ For captures larger than one cloud takes (3,000,000 splats) or than a GPU should draw at once, `./lod` draws a cut of a
193
+ splat hierarchy chosen by the view, loading only the nodes the cut needs:
194
+
195
+ ```ts
196
+ import {Engine} from 'margoengine/core';
197
+ import {parsePly} from 'margoengine/splats/data';
198
+ import {SplatLod, buildSplatLod} from 'margoengine/splats/lod';
199
+ const engine = await Engine.create(document.querySelector('canvas')!);
200
+ const capture = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
201
+ const lod = SplatLod.attach(engine, buildSplatLod(capture, {leafSize: 1024}), {budget: 1_000_000, maxError: 2});
202
+ engine.start();
203
+ await lod.settled(); // the current view is fully streamed in
204
+ console.log(lod.selected.length, lod.drawn);
205
+ ```
206
+
207
+ - `buildSplatLod(data, {leafSize})` splits the capture into an octree until a cell holds at most `leafSize` splats
208
+ (default 65,536); leaves keep the trained splats untouched, and each inner cell gets a moment-matched merge of its
209
+ splats (`decimateSplats`) on the coarsest grid that still fits `leafSize`, with that grid cell as its `error`.
210
+ - A streamed capture is any `SplatLodSource`: `{nodes, coefficients, load(index, signal)}`, each node a bounding sphere,
211
+ an `error` in world units (0 for a leaf), its `count` and `children`. `load` may fetch the node (for instance a
212
+ `.splat` from `encodeSplat`, one file per node) and must return `count` splats with `coefficients` SH.
213
+ - Each frame, before the splats project, `chooseSplatNodes` replaces the node of largest projected error
214
+ (`error x focal / distance`, pixels) by its children while that error exceeds `maxError` (default 2), all its children
215
+ are loaded and the cut fits `budget` (default 1,000,000). Children it lacks are loaded, at most `concurrency` (4) at
216
+ a time; until they arrive the parent stays, so streaming never leaves a hole.
217
+ - Drawn nodes live in fixed slots of one `Splats` (`lod.cloud`, `budget` rounded down to whole slots of the largest
218
+ node, and to no more slots than the source has leaves), written with `Splats.write` and hidden with `Splats.clear`, so every drawn node sorts together. Loaded nodes
219
+ stay on the CPU up to `cache` splats (twice the budget), oldest dropped first.
220
+ - `Splats.reserve(count, coefficients)` makes such a pool of hidden splats; `write(first, data)` and
221
+ `clear(first, count)` work on any cloud.
222
+ - `lod.placement` maps each drawn node to the pool index of its first splat, for picking or editing.
223
+ - On the real raccoon fixture (41 nodes of at most 1,024 splats) `maxError: 0` streams in all 8,385
224
+ leaf splats and draws exactly what one plain cloud of the pool's splats draws; against the capture in its own order
225
+ 188 of 262,144 channels differ (exact depth ties blend in another order); 400 units away the root alone. A procedural stand-in of 16,777,216 splats (256 leaves of 65,536) streams within a
226
+ 2,097,152 budget (1,110,016 drawn, 16 leaves near the camera).
227
+
228
+ ## Streaming a capture as it downloads (`./progressive`)
229
+
230
+ `loadProgressiveSplats(engine, response.body, { format })` draws a PLY, raw `.splat` or SPZ capture while it is still
231
+ downloading: it reserves the whole cloud from the header (or `count` for raw `.splat`), adds it to the scene and
232
+ writes each batch as its bytes arrive, largest visible splats first in each batch. Call `engine.start()` before you
233
+ await it to see the frames fill in. `readSplatsProgressive(source, options)` is the decoder alone, an async generator
234
+ of `{ first, total, data }` batches for your own upload.
235
+
236
+ ```ts
237
+ import { readSplatsProgressive } from 'margoengine/splats/progressive';
238
+
239
+ // Three raw .splat records: position, scale, RGBA and a rotation quaternion, 32 bytes each.
240
+ const records = new Uint8Array(32 * 3);
241
+ const view = new DataView(records.buffer);
242
+ for (let i = 0; i < 3; i++) {
243
+ view.setFloat32(i * 32, i, true); // x
244
+ for (let k = 0; k < 3; k++) view.setFloat32(i * 32 + 12 + k * 4, 0.1, true); // scale
245
+ records.set([255, 255, 255, 255, 255, 128, 128, 128], i * 32 + 24); // white, opaque, identity rotation
246
+ }
247
+ async function* network() {
248
+ yield records.subarray(0, 40); // one whole record and part of the next
249
+ yield records.subarray(40);
250
+ }
251
+ for await (const batch of readSplatsProgressive(network(), { format: 'splat', count: 3, batchSize: 2 }))
252
+ console.log(batch.first, batch.total, batch.data.positions.length / 3); // 0 3 1, then 1 3 2
253
+
254
+ const controller = new AbortController();
255
+ const reads = readSplatsProgressive(network(), { format: 'splat', count: 3, batchSize: 1, signal: controller.signal });
256
+ console.log((await reads.next()).value.first); // 0
257
+ controller.abort(new Error('user left'));
258
+ await reads.next().catch((error) => console.log(error.message)); // user left
259
+ ```
260
+
261
+ - `source` is a `ReadableStream<Uint8Array>` (such as `response.body`) or any `AsyncIterable<Uint8Array>`.
262
+ - `format` is required (`'ply'`, `'splat'` or `'spz'`); `count` is required for `'splat'`; `batchSize` (default
263
+ 16,384) caps the records in one batch. A batch is emitted as soon as whole records are in, so a partial record waits
264
+ for the next chunk; SPZ's last batch replaces its colour-only preview with full spherical harmonics.
265
+ - `signal` stops the load at once, also while a read is still pending and between batches already decoded from the
266
+ same chunk: the pending `next()` rejects with the signal's reason without waiting for the network.
267
+ - The reader owns the source while it runs and closes it on every early stop (abort, an error, or a `break` out of
268
+ your `for await`): a stream's reader is cancelled and its lock released; an async iterable's `return()` is called.
269
+ A source that ends normally is not cancelled. Do not read the same stream elsewhere while the load runs.
270
+ - `loadProgressiveSplats` disposes the half-written cloud and removes it from the scene on abort or failure, and
271
+ rejects with a `RangeError` for a stream with no splats or a truncated one (check the file).
272
+
273
+ ## One sort for many clouds (`./set`)
274
+
275
+ Separate `Splats` clouds sort and draw one after the other, so where two captures overlap the one drawn last covers the
276
+ other whole. A `SplatSet` puts every cloud added to it into ranges of one pooled `Splats`, so all their splats sort and
277
+ blend far to near together, as one merged cloud would, while each stays movable and removable on its own:
278
+
279
+ ```ts
280
+ import {Engine} from 'margoengine/core';
281
+ import {parsePly} from 'margoengine/splats/data';
282
+ import {SplatSet} from 'margoengine/splats/set';
283
+ const engine = await Engine.create(document.querySelector('canvas')!);
284
+ const capture = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
285
+ // Every member has the set's SH count: this capture's coefficients per channel (0 when it has none).
286
+ const coefficients = (capture.sphericalHarmonics?.length ?? 0) / capture.positions.length;
287
+ const set = SplatSet.attach(engine, {capacity: 500_000, coefficients});
288
+ const first = set.add(capture);
289
+ const second = set.add(capture, {matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1]});
290
+ engine.start();
291
+ second.setMatrix([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 3, 0, 0, 1]); // move it
292
+ first.remove(); // its range is free again
293
+ ```
294
+
295
+ - `capacity` (1 to 3,000,000, default 1,000,000) is the pool; `coefficients` (0, 4, 9 or 16) the SH count every
296
+ member must have. `add` takes the first free range that holds the cloud and throws a RangeError when none does.
297
+ - A member's `setMatrix(matrix)` rewrites its splats from its own data moved by the matrix (`transformSplats`);
298
+ `remove()` hides them and frees the range, merged with free neighbours.
299
+ - `member.visible = false` hides a part and `member.opacity = 0.5` fades it (0 to 1, times each splat's own opacity),
300
+ without rewriting its covariances or SH: only its positions and colours (32 of the 128 bytes a splat takes) go to the
301
+ GPU, and `setMatrix` keeps both settings. `Splats.setOpacities(first, alphas, scale)` is the same for any range.
302
+ - Every pool splat is projected and sorted each frame, free ranges too (hidden, culled before drawing), so size
303
+ `capacity` to what you add.
304
+
305
+ ## Editing session (`./session`)
306
+
307
+ `SplatEditSession` is a splat editor's tool set on the CPU (so it also runs headless): select by brush, rectangle,
308
+ lasso (screen space, from a view-projection matrix), sphere or box (world space), by colour or by opacity, with
309
+ replace/add/subtract modes, invert and clear; hide, unhide and delete the selection; move, turn and scale it (covariances
310
+ and SH follow, optionally about a pivot); adjust its colour; undo and redo (each step keeps only the rows it changed,
311
+ 64 steps by default, `maxHistory`); export the result. The tool list follows the public feature lists of SuperSplat;
312
+ selection by region matches `./edit`'s GPU brush, which stays the choice for strokes on a cloud of millions drawn
313
+ this frame.
314
+
315
+ ```ts
316
+ import {parsePly} from 'margoengine/splats/data';
317
+ import {SplatEditSession} from 'margoengine/splats/session';
318
+ const session = new SplatEditSession(parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
319
+ session.selectByOpacity(0, 0.05).deleteSelected(); // drop faint floaters
320
+ session.selectSphere([0, 1, 0], 0.5).transformSelected([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0.2, 0, 1]);
321
+ session.selectByColor([1, 0, 0], 0.3).adjustColor({hue: 90, saturation: 1.2});
322
+ session.undo(); // the colour change
323
+ const file = await session.encode('ply'); // or 'spz', 'splat', 'sog'; hidden and deleted splats are left out
324
+ ```
325
+
326
+ `SplatEditSession.fromCloud(cloud)` starts from a cloud's data (GPU edits included) and `session.applyTo(cloud)` writes the
327
+ edit back (hidden and deleted splats at opacity 0). Selection by screen region takes
328
+ `{viewProjection, width, height}`: a column-major 4x4 and the pixel size; centres behind the camera are never hit.
329
+ Sources: Kerbl et al. 2023, "3D Gaussian Splatting for Real-Time Radiance Field Rendering"; Chen et al. 2024,
330
+ "GaussianEditor: Swift and Controllable 3D Editing with Gaussian Splatting" (arXiv:2311.14521) for the edit operations.
331
+ Limits: history holds a full selection mask per selection step (1 byte per splat), so at 3,000,000 splats 64 selection
332
+ steps can take about 190 MB; lower `maxHistory` for that. SH colour adjust changes the base band only.
333
+
334
+ ## Scene light and shadows (`./lighting`)
335
+
336
+ `SplatLighting` relights a cloud with the engine's directional light and ambient every frame, and is a
337
+ `@margoengine/shadows` source, so the capture casts shadows on meshes (its caster shader declares the position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit):
338
+
339
+ ```ts
340
+ import {Engine, box} from 'margoengine/core';
341
+ import {Splats} from 'margoengine/splats';
342
+ import {parsePly} from 'margoengine/splats/data';
343
+ import {SplatLighting} from 'margoengine/splats/lighting';
344
+ import {Shadows} from 'margoengine/shadows';
345
+ const engine = await Engine.create(document.querySelector('canvas')!);
346
+ const ground = engine.createMesh().setGeometry(box()).setScale([20, 0.1, 20]).setPosition([0, -2, 0]);
347
+ const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
348
+ const lit = SplatLighting.attach(engine, cloud);
349
+ const shadows = Shadows.attach(engine);
350
+ shadows.add(ground, {static: true});
351
+ shadows.add(lit); // the splats cast on the ground
352
+ engine.lighting.direction.set([0.6, 1, 0.2, 3]); // toward the sun, w intensity
353
+ engine.start();
354
+ ```
355
+
356
+ - Relighting scales each splat's colour by core's diffuse terms: `nl * radiance * intensity / pi + radiance.w *
357
+ ambient`, with `nl` from the splat's flat axis (the axis of its smallest covariance eigenvalue, turned to the
358
+ camera; the view direction for a round splat). `relight: false` (live) keeps the captured colours and still casts.
359
+ - The captured colours already hold the light they were filmed in, so a relit capture is lit twice; it reads best
360
+ under soft capture light. Splats do not receive shadows, and the light has no specular term.
361
+ - Shadows: each splat draws its ellipse in the light's view (with the colour pass's 0.3 px^2 dilation in shadow-map
362
+ texels). By default a splat blocks each texel with the probability of its opacity there (stochastic transparency),
363
+ so overlapping splats shade as their combined opacity, noisy per texel and smoothed by the shadow filter;
364
+ `threshold` (0 to 1, live) instead blocks where one splat's opacity reaches it, without noise.
365
+
366
+ ## Animated splats (`./animate`)
367
+
368
+ `SplatSequence` plays a 4D capture (a list of frames of the same splats); `SplatSkin` poses a cloud with a skeleton
369
+ by linear blend skinning, for captured performances:
370
+
371
+ ```ts
372
+ import {Engine} from 'margoengine/core';
373
+ import {Splats} from 'margoengine/splats';
374
+ import {parsePly, transformSplats} from 'margoengine/splats/data';
375
+ import {SplatSequence, SplatSkin} from 'margoengine/splats/animate';
376
+ const engine = await Engine.create(document.querySelector('canvas')!);
377
+ const first = parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer());
378
+ const frames = [0, 1, 2, 3].map((k) => transformSplats(first, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, k * 0.1, 0, 1]));
379
+ const performer = Splats.attach(engine, first);
380
+ const sequence = SplatSequence.attach(engine, performer, frames, {fps: 12});
381
+ sequence.speed = 0.5; // live: time, speed, playing, loop
382
+ const n = first.positions.length / 3;
383
+ const second = Splats.attach(engine, first);
384
+ const skin = SplatSkin.attach(engine, second, {
385
+ joints: 2,
386
+ indices: Array.from({length: n * 4}, (_, i) => (i % 4 === 0 ? (first.positions[(i / 4) * 3 + 1] > 0 ? 1 : 0) : 0)),
387
+ weights: Array.from({length: n * 4}, (_, i) => (i % 4 === 0 ? 1 : 0)),
388
+ });
389
+ skin.matrices.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0.5, 0, 0, 1], 16); // joint 1: move the top half 0.5 along x
390
+ engine.start();
391
+ console.log(sequence.duration, (await second.read()).positions.length);
392
+ ```
393
+
394
+ - Both run one compute pass before the cloud projects and write its GPU inputs, so sorting, `./depth`,
395
+ `./lighting` and `./edit` see the pose; `cloud.read()` returns the posed cloud.
396
+ - A sequence mixes centres, covariances, colours and opacity of the two frames around `time` linearly (a mix of
397
+ positive-definite covariances stays positive definite); SH stays the cloud's. Every frame lives on the GPU, 64 bytes
398
+ per splat, so a long capture at 3,000,000 splats does not fit: stream frames into a few sequences instead.
399
+ - A skin moves each centre by the weighted sum of up to four joint matrices and each covariance by the blend's linear
400
+ part, A S A^T; weights are normalised, all zero keeps a splat at rest. The rest pose is the cloud as it is when first
401
+ posed, or after `rebind()` (call it after `Splats.write`). Like any linear blend skin, a blend of two far-turned
402
+ joints shrinks the splats between them. Colours and SH are not turned with the joints.
403
+
404
+ ## Picking and brush editing (`./edit`)
405
+
406
+ `SplatBrush` picks, selects, erases and paints splats on the GPU, for clean-up tools. Regions are in pixels of the
407
+ frame the cloud last drew (`brush.frame`), from the top-left corner:
408
+
409
+ ```ts
410
+ import {Engine} from 'margoengine/core';
411
+ import {Splats} from 'margoengine/splats';
412
+ import {parsePly} from 'margoengine/splats/data';
413
+ import {SplatBrush} from 'margoengine/splats/edit';
414
+ const engine = await Engine.create(document.querySelector('canvas')!);
415
+ const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
416
+ const brush = SplatBrush.attach(engine, cloud);
417
+ engine.render({delta: 0}); // the brush works on a drawn frame
418
+ const [width, height] = brush.frame;
419
+ const hit = await brush.pick(width / 2, height / 2); // the nearest splat at the pixel, or -1
420
+ brush.select({x: width / 2, y: height / 2, radius: 30}); // replace the selection
421
+ brush.select({x: 0, y: 0, width: 40, height: 40}, 'add'); // or 'subtract'
422
+ brush.erase('selection'); // opacity 0, as Splats.clear
423
+ brush.paint({x: width / 4, y: height / 2, radius: 20}, [0.8, 0.1, 0.1], 0.5); // linear RGB, strength
424
+ const edited = await brush.commit(); // the edited cloud as SplatData, for export
425
+ console.log(hit, (await brush.selection()).length, edited.colors.length);
426
+ engine.start();
427
+ ```
428
+
429
+ - One compute dispatch per operation over every splat, against the ellipses the cloud projected for the last
430
+ frame: a splat is in a region when its projected centre is and it was drawn. Picking takes the nearest splat whose
431
+ own opacity at the pixel (its Gaussian falloff times its opacity) reaches `threshold` (default 0.1).
432
+ - Edits change the cloud's GPU buffers at once and show from the next frame. `commit()` (`cloud.read()`) copies them
433
+ into the cloud's data, which `Splats.write`, export and device restoration use: a device loss before a commit
434
+ drops the edits since the last one.
435
+ - Painting blends the colour by `strength` and keeps opacity; on a cloud with spherical harmonics it sets the DC term
436
+ to the blended colour and fades the higher bands by the same strength.
437
+ - The selection lives on the GPU (4 bytes per splat); `selection()` reads it back as indices. A restored device
438
+ starts with an empty selection.
439
+
440
+ ### Strokes, undo and reset
441
+
442
+ Erase and paint keep a stroke history on the GPU. Wrap one drag of a brush tool in `beginStroke()` and `endStroke()`
443
+ so `undo()` takes the whole drag back; an edit outside a stroke is a stroke of its own. `reset()` restores the scan as
444
+ it was before the first edit:
445
+
446
+ ```ts
447
+ import {Engine} from 'margoengine/core';
448
+ import {Splats} from 'margoengine/splats';
449
+ import {parsePly} from 'margoengine/splats/data';
450
+ import {SplatBrush} from 'margoengine/splats/edit';
451
+ const canvas = document.querySelector('canvas')!;
452
+ const engine = await Engine.create(canvas);
453
+ const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
454
+ const brush = SplatBrush.attach(engine, cloud, {history: 32}); // strokes undo can take back
455
+ engine.start();
456
+ const at = (event: PointerEvent) => {
457
+ const box = canvas.getBoundingClientRect(), [width, height] = brush.frame;
458
+ return {x: ((event.clientX - box.left) / box.width) * width, y: ((event.clientY - box.top) / box.height) * height, radius: 24};
459
+ };
460
+ canvas.addEventListener('pointerdown', (event) => brush.beginStroke().paint(at(event), [0.1, 0.6, 0.9], 0.6));
461
+ canvas.addEventListener('pointermove', (event) => {
462
+ if (brush.inStroke) brush.paint(at(event), [0.1, 0.6, 0.9], 0.6);
463
+ });
464
+ canvas.addEventListener('pointerup', () => brush.endStroke());
465
+ addEventListener('keydown', (event) => {
466
+ if (event.key === 'z' && (event.ctrlKey || event.metaKey)) brush.undo(); // false when there is nothing to undo
467
+ if (event.key === 'Escape') brush.reset(); // the scan as loaded
468
+ });
469
+ console.log(brush.strokes);
470
+ ```
471
+
472
+ - Each kept stroke holds a GPU copy of what it changed: 32 bytes a splat for an erase (positions and colours), 16
473
+ bytes a splat plus the SH (4 bytes a coefficient) for a paint. Past `history` strokes (default 32) the oldest is
474
+ dropped; `history: 0` keeps only `reset()`. `reset()` keeps one more copy of positions, colours and SH from before
475
+ the first edit.
476
+ - The copies are whole buffers, so a `cloud.write` made between strokes is taken back with the stroke after it.
477
+ Selections are not strokes. A restored device or a re-attached cloud starts a new history.
478
+
479
+ ## Picking with meshes (`./pick`)
480
+
481
+ `SplatBrush.pick` sees splats only. `SplatPicking` adds a cloud to `Picking` from `margoengine/selection`, so one
482
+ `engine.pick`, `picking.pick` or `picking.pickMany` answers whichever of splats and meshes is nearest at the pixel. A mesh
483
+ in front of a splat blocks it, and a splat in front of a mesh wins:
484
+
485
+ ```ts
486
+ import {Engine, box} from 'margoengine/core';
487
+ import {Splats} from 'margoengine/splats';
488
+ import {parsePly} from 'margoengine/splats/data';
489
+ import {SplatPicking} from 'margoengine/splats/pick';
490
+ import {Picking} from 'margoengine/selection';
491
+ const engine = await Engine.create(document.querySelector('canvas')!);
492
+ engine.createMesh().setGeometry(box());
493
+ const cloud = Splats.attach(engine, parsePly(await (await fetch('/raccoon-v2.ply')).arrayBuffer()));
494
+ const picking = Picking.attach(engine);
495
+ const splatPicking = SplatPicking.attach(picking, cloud); // {threshold: 0.1} by default
496
+ const hit = await picking.pick(128, 96); // PickHit, in canvas CSS pixels
497
+ if (hit && splatPicking.splatsOf(hit.mesh)) console.log('splat', hit.splat, 'of', hit.splats);
498
+ else if (hit) console.log('mesh', hit.mesh);
499
+ const hits = await picking.pickMany([[10, 20], [64, 64]]); // one readback for both
500
+ console.log(hits.map((h) => h?.splat ?? null));
501
+ engine.start();
502
+ ```
503
+
504
+ - A pick projects every splat of the cloud again for its 3 x 3 tile, with the colour pass's own projection (the same
505
+ WGSL function), in a vertex shader: it needs no drawn frame and follows the current camera, perspective or
506
+ orthographic, the antialias flag, brush erasing (`./edit`) and poses (`./animate`), which write the same GPU inputs.
507
+ - A splat hits where its Gaussian times its opacity at the pixel, capped at 0.99 as drawn, reaches `threshold`
508
+ (default 0.1, as `SplatBrush.pick`; settable). Among those the nearest splat centre wins, and it then competes with
509
+ the meshes at that depth.
510
+ - `picking.pick` returns `PickHit | null`, with the mesh and splat metadata used above. `engine.pick` returns only
511
+ `Mesh | null`, without those hit fields. On a splat hit, `hit.mesh` is an empty stand-in mesh; `splatsOf(mesh)` maps
512
+ it back to the cloud.
513
+ `hit.splat` is the splat's index in the cloud (a pool index under `SplatSet` and `SplatLod`). `dispose()` leaves
514
+ Picking and frees the stand-in; the cloud stays.
515
+ - A pick's cost grows with the cloud: four vertices of projection per splat, every pick. Picking takes up to 8 overlays.
516
+
517
+ ### Attaching from a second scene
518
+
519
+ `SplatModifier.attach` and `loadProgressiveSplats` remember the scene that is active when you call them, before their first await, and join that scene when they finish. Start it inside a second scene's plugin `setup` and the plugin belongs to that scene; start it anywhere else and it belongs to the default scene. An abort or a failure leaves nothing in either scene.
520
+
521
+ ## Preview tier contract
522
+
523
+ GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.
524
+
525
+ ## Exact first frames on the WebGL2 layer
526
+
527
+ `cloud.ready` is a promise that settles once every frame orders the splats as it will from then on. On the WebGL2
528
+ compatibility layer `Splats` fetches its sort route (`import()`) when it attaches; until it arrives the WebGPU radix sort
529
+ runs on the layer's CPU tier, which orders splats of equal depth its own way. On WebGPU it is already settled. Await it
530
+ before a frame that must be exact, such as a film frame or a pixel comparison:
531
+
532
+ ```ts
533
+ import {EngineKernel} from 'margoengine/core';
534
+ import {Splats} from 'margoengine/splats';
535
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, {backend:'webgpu'});
536
+ const cloud = Splats.attach(engine, {
537
+ positions: new Float32Array([0, 0, 0]),
538
+ covariances: new Float32Array([0.1, 0, 0, 0.1, 0, 0.1]),
539
+ colors: new Float32Array([1, 0.5, 0.2, 1]),
540
+ });
541
+ await cloud.ready;
542
+ engine.render();
543
+ ```
544
+
545
+ ## Film time
546
+
547
+ `SplatSequence` and `SplatModifier` move `time` (by `speed`, while `playing`) in the frame update with `advanceTime(delta)`, not in their passes, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the frame a continuous run shows.