@margoengine/splats 0.0.0-stage → 0.1.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 -0
- package/NOTICE +4 -0
- package/README.md +443 -3
- package/dist/animate.d.ts +138 -0
- package/dist/animate.js +31 -0
- package/dist/brush.d.ts +94 -0
- package/dist/brush.js +36 -0
- package/dist/compat-CDoDsXE8.js +19 -0
- package/dist/compat.d.ts +7 -0
- package/dist/compressed.d.ts +40 -0
- package/dist/data-D31W24Wu.js +2 -0
- package/dist/data.d.ts +28 -0
- package/dist/data.js +1 -0
- package/dist/depth.d.ts +42 -0
- package/dist/depth.js +14 -0
- package/dist/edit.d.ts +48 -0
- package/dist/encode-BA6xu973.js +1 -0
- package/dist/encode.d.ts +40 -0
- package/dist/formats.d.ts +24 -0
- package/dist/formats.js +5 -0
- package/dist/index.d.ts +167 -0
- package/dist/index.js +1 -0
- package/dist/lighting.d.ts +89 -0
- package/dist/lighting.js +48 -0
- package/dist/lod-sog.d.ts +44 -0
- package/dist/lod-sog.js +1 -0
- package/dist/lod.d.ts +129 -0
- package/dist/lod.js +4 -0
- package/dist/modify.d.ts +83 -0
- package/dist/modify.js +24 -0
- package/dist/pick.d.ts +75 -0
- package/dist/pick.js +14 -0
- package/dist/ply.d.ts +62 -0
- package/dist/progressive.d.ts +37 -0
- package/dist/progressive.js +5 -0
- package/dist/scene-scope-C5HWuOIb.js +4 -0
- package/dist/session.d.ts +127 -0
- package/dist/session.js +1 -0
- package/dist/set.d.ts +59 -0
- package/dist/set.js +4 -0
- package/dist/shader-B7zZyYz-.js +64 -0
- package/dist/shader.d.ts +17 -0
- package/dist/shared/fog.d.ts +33 -0
- package/dist/shared/pass.d.ts +53 -0
- package/dist/sog-D0LYo48N.js +1 -0
- package/dist/sog.d.ts +20 -0
- package/dist/sort.d.ts +4 -0
- package/dist/spz-BTy6CPTp.js +1 -0
- package/dist/spz.d.ts +23 -0
- package/dist/src-DlpBlCx1.js +48 -0
- package/dist/view-DyJeX8rJ.js +1 -0
- package/dist/view-rect-G-t2gTqO.js +1 -0
- package/dist/webp.d.ts +11 -0
- package/dist/zip-DNluwYbe.js +1 -0
- package/dist/zip.d.ts +7 -0
- package/dist/zstd-BPbUkXlY.js +1 -0
- package/package.json +107 -6
package/README.md
CHANGED
|
@@ -1,3 +1,443 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
|
|
4
|
+
import { type SplatData } from './data.js';
|
|
5
|
+
import type { Splats } from './index.js';
|
|
6
|
+
type Context = Extract<PassContext, {
|
|
7
|
+
backend: 'webgpu';
|
|
8
|
+
}>;
|
|
9
|
+
/** Options of {@link SplatSequence}. */
|
|
10
|
+
export interface SplatSequenceOptions {
|
|
11
|
+
/** Frames per second of the capture. Default 30. */
|
|
12
|
+
fps?: number;
|
|
13
|
+
/** Start again after the last frame (true, the default) or hold it. */
|
|
14
|
+
loop?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* WGSL of the sequence pass: frames a and b (per splat: centre and opacity, two covariance vec4s, colour) mixed by
|
|
18
|
+
* `u.mix.x` into the cloud's positions, covariances and colours.
|
|
19
|
+
*/
|
|
20
|
+
export declare const sequenceShader = "struct Mix {mix:vec4f,counts:vec4u}\n@group(0) @binding(0) var<uniform> u:Mix;\n@group(0) @binding(1) var<storage,read> a:array<vec4f>;\n@group(0) @binding(2) var<storage,read> b:array<vec4f>;\n@group(0) @binding(3) var<storage,read_write> positions:array<vec4f>;\n@group(0) @binding(4) var<storage,read_write> covariances:array<vec4f>;\n@group(0) @binding(5) var<storage,read_write> colors:array<vec4f>;\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 t=u.mix.x;\n 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);\n colors[i]=mix(a[i*4+3],b[i*4+3],t);\n}";
|
|
21
|
+
/** The plugin plumbing both players share: setup checks, the pass at order -7.5, dispose. */
|
|
22
|
+
declare abstract class Player implements EnginePlugin {
|
|
23
|
+
abstract readonly name: string;
|
|
24
|
+
readonly cloud: Splats;
|
|
25
|
+
protected engine?: Engine;
|
|
26
|
+
protected device?: GPUDevice;
|
|
27
|
+
protected uniform?: GPUBuffer;
|
|
28
|
+
protected pipeline?: GPUComputePipeline;
|
|
29
|
+
protected buffers: GPUBuffer[];
|
|
30
|
+
protected dead: boolean;
|
|
31
|
+
constructor(cloud: Splats, what: string);
|
|
32
|
+
setup(engine: Engine): void;
|
|
33
|
+
protected buffer(size: number, usage: number, data?: Float32Array | Uint32Array): GPUBuffer;
|
|
34
|
+
protected compute(code: string): GPUComputePipeline;
|
|
35
|
+
registerPasses(graph: FrameGraph): void;
|
|
36
|
+
/** Writes the pose into the cloud's inputs; `first` is the frame's first view (time advances once a frame). */
|
|
37
|
+
protected abstract pose(c: Context, first: boolean): void;
|
|
38
|
+
protected run(e: GPUCommandEncoder, group: GPUBindGroup): void;
|
|
39
|
+
protected release(): void;
|
|
40
|
+
onDeviceRestored(engine: Engine): void;
|
|
41
|
+
/** True once disposed. */
|
|
42
|
+
get disposed(): boolean;
|
|
43
|
+
dispose(): void;
|
|
44
|
+
[Symbol.dispose]: () => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Plays a 4D splat capture: `SplatSequence.attach(engine, cloud, frames, { fps })`, with `frames` a list of clouds of
|
|
48
|
+
* the cloud's splats in the same order. Each frame the cloud draws the mix of the two frames around `time` (centres,
|
|
49
|
+
* covariances, colours and opacity; SH stays the cloud's). `playing`, `time` and `speed` are live. All frames live on
|
|
50
|
+
* the GPU, 64 bytes per splat each. WebGPU only, as `Splats`.
|
|
51
|
+
* @throws TypeError when `cloud` is not a Splats; RangeError for no frames, a frame of another splat count or an
|
|
52
|
+
* invalid one, or an fps that is not above 0; MargoError `'unsupported'` on a WebGL engine.
|
|
53
|
+
*/
|
|
54
|
+
export declare class SplatSequence extends Player {
|
|
55
|
+
private static next;
|
|
56
|
+
readonly name: string;
|
|
57
|
+
/** Frames per second of the capture. */
|
|
58
|
+
readonly fps: number;
|
|
59
|
+
/** Start again after the last frame, or hold it. Live. */
|
|
60
|
+
loop: boolean;
|
|
61
|
+
/** Play time in seconds, advanced by each frame's delta times `speed` while `playing`. Live. */
|
|
62
|
+
time: number;
|
|
63
|
+
/** Play rate (1 real time, negative backwards). Live. */
|
|
64
|
+
speed: number;
|
|
65
|
+
/** Advance `time` each frame. Live. */
|
|
66
|
+
playing: boolean;
|
|
67
|
+
private readonly frames;
|
|
68
|
+
private readonly values;
|
|
69
|
+
private readonly integers;
|
|
70
|
+
private groups;
|
|
71
|
+
private gpuFrames;
|
|
72
|
+
constructor(cloud: Splats, frames: readonly SplatData[], options?: SplatSequenceOptions);
|
|
73
|
+
/** Same as `engine.use(new SplatSequence(cloud, frames, options))`; returns it. */
|
|
74
|
+
static attach(engine: EngineKernel, cloud: Splats, frames: readonly SplatData[], options?: SplatSequenceOptions): SplatSequence;
|
|
75
|
+
/** Number of frames. */
|
|
76
|
+
get length(): number;
|
|
77
|
+
/** Length of the capture in seconds: frames / fps. */
|
|
78
|
+
get duration(): number;
|
|
79
|
+
/**
|
|
80
|
+
* Moves `time` by `delta` seconds times `speed` while `playing`, without drawing (a delta of 0 or less moves
|
|
81
|
+
* nothing). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
|
|
82
|
+
*/
|
|
83
|
+
advanceTime(delta: number): void;
|
|
84
|
+
onPreUpdate(delta: number): void;
|
|
85
|
+
/** The two frames and the mix between them at `time` (looped or held). */
|
|
86
|
+
sample(time?: number): {
|
|
87
|
+
from: number;
|
|
88
|
+
to: number;
|
|
89
|
+
mix: number;
|
|
90
|
+
};
|
|
91
|
+
setup(engine: Engine): void;
|
|
92
|
+
protected pose(c: Context, first: boolean): void;
|
|
93
|
+
protected release(): void;
|
|
94
|
+
}
|
|
95
|
+
/** Options of {@link SplatSkin}. */
|
|
96
|
+
export interface SplatSkinOptions {
|
|
97
|
+
/** Joint count: `matrices` holds 16 floats for each. */
|
|
98
|
+
joints: number;
|
|
99
|
+
/** Four joint indices per splat (unused slots take weight 0). */
|
|
100
|
+
indices: ArrayLike<number>;
|
|
101
|
+
/** Four weights per splat; each splat's are normalised to sum 1 (all zero keeps the splat at rest). */
|
|
102
|
+
weights: ArrayLike<number>;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* WGSL of the skinning pass: the rest pose (copied from the cloud when bound) times the blend of up to four joint
|
|
106
|
+
* matrices per splat, centres by the whole matrix and covariances by its linear part, A S A^T.
|
|
107
|
+
*/
|
|
108
|
+
export declare const skinShader = "struct Skin {counts:vec4u}\n@group(0) @binding(0) var<uniform> u:Skin;\n@group(0) @binding(1) var<storage,read> matrices:array<mat4x4f>;\n@group(0) @binding(2) var<storage,read> influence:array<vec4f>;\n@group(0) @binding(3) var<storage,read> restPositions:array<vec4f>;\n@group(0) @binding(4) var<storage,read> restCovariances:array<vec4f>;\n@group(0) @binding(5) var<storage,read_write> positions:array<vec4f>;\n@group(0) @binding(6) var<storage,read_write> covariances:array<vec4f>;\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 j=bitcast<vec4u>(influence[i*2]);let w=influence[i*2+1];\n var m=matrices[j.x]*w.x+matrices[j.y]*w.y+matrices[j.z]*w.z+matrices[j.w]*w.w;\n if(w.x+w.y+w.z+w.w<=0){m=mat4x4f(vec4f(1,0,0,0),vec4f(0,1,0,0),vec4f(0,0,1,0),vec4f(0,0,0,1));}\n let p=restPositions[i];positions[i]=vec4f((m*vec4f(p.xyz,1)).xyz,positions[i].w);\n 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));\n let l=mat3x3f(m[0].xyz,m[1].xyz,m[2].xyz);let c=l*s*transpose(l);\n 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);\n}";
|
|
109
|
+
/**
|
|
110
|
+
* Poses a splat cloud with a skeleton by linear blend skinning: `const skin = SplatSkin.attach(engine, cloud,
|
|
111
|
+
* { joints, indices, weights })`, then set `skin.matrices` (16 floats per joint, column-major, rest space to posed
|
|
112
|
+
* world) each frame, from `@margoengine/animation` or your own rig. The cloud's centres and covariances when it is
|
|
113
|
+
* first posed (or after `rebind()`) are the rest pose; opacity and colours are kept. WebGPU only, as `Splats`.
|
|
114
|
+
* @throws TypeError when `cloud` is not a Splats; RangeError for a joint count outside 1 to 65,536, indices or
|
|
115
|
+
* weights of another length than 4 per splat, an index outside the joints, or a negative or non-finite weight;
|
|
116
|
+
* MargoError `'unsupported'` on a WebGL engine.
|
|
117
|
+
*/
|
|
118
|
+
export declare class SplatSkin extends Player {
|
|
119
|
+
private static next;
|
|
120
|
+
readonly name: string;
|
|
121
|
+
/** Joint matrices, 16 floats per joint (identity at first), read every frame. Live: write into it. */
|
|
122
|
+
readonly matrices: Float32Array;
|
|
123
|
+
private readonly influence;
|
|
124
|
+
private matrixBuffer?;
|
|
125
|
+
private restPositions?;
|
|
126
|
+
private restCovariances?;
|
|
127
|
+
private bound?;
|
|
128
|
+
private stale;
|
|
129
|
+
constructor(cloud: Splats, options: SplatSkinOptions);
|
|
130
|
+
/** Same as `engine.use(new SplatSkin(cloud, options))`; returns it. */
|
|
131
|
+
static attach(engine: EngineKernel, cloud: Splats, options: SplatSkinOptions): SplatSkin;
|
|
132
|
+
/** Takes the cloud's current centres and covariances as the rest pose on the next frame (after `Splats.write`). */
|
|
133
|
+
rebind(): this;
|
|
134
|
+
setup(engine: Engine): void;
|
|
135
|
+
protected pose(c: Context): void;
|
|
136
|
+
protected release(): void;
|
|
137
|
+
}
|
|
138
|
+
export {};
|
package/dist/animate.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const t=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e}from"./data-D31W24Wu.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
|
+
@group(0) @binding(0) var<uniform> u:Mix;
|
|
6
|
+
@group(0) @binding(1) var<storage,read> a:array<vec4f>;
|
|
7
|
+
@group(0) @binding(2) var<storage,read> b:array<vec4f>;
|
|
8
|
+
@group(0) @binding(3) var<storage,read_write> positions:array<vec4f>;
|
|
9
|
+
@group(0) @binding(4) var<storage,read_write> covariances:array<vec4f>;
|
|
10
|
+
@group(0) @binding(5) var<storage,read_write> colors:array<vec4f>;
|
|
11
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
12
|
+
let i=id.x;if(i>=u.counts.x){return;}let t=u.mix.x;
|
|
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
|
+
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("0.1.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("0.1.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("0.1.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
|
+
@group(0) @binding(0) var<uniform> u:Skin;
|
|
17
|
+
@group(0) @binding(1) var<storage,read> matrices:array<mat4x4f>;
|
|
18
|
+
@group(0) @binding(2) var<storage,read> influence:array<vec4f>;
|
|
19
|
+
@group(0) @binding(3) var<storage,read> restPositions:array<vec4f>;
|
|
20
|
+
@group(0) @binding(4) var<storage,read> restCovariances:array<vec4f>;
|
|
21
|
+
@group(0) @binding(5) var<storage,read_write> positions:array<vec4f>;
|
|
22
|
+
@group(0) @binding(6) var<storage,read_write> covariances:array<vec4f>;
|
|
23
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
24
|
+
let i=id.x;if(i>=u.counts.x){return;}let j=bitcast<vec4u>(influence[i*2]);let w=influence[i*2+1];
|
|
25
|
+
var m=matrices[j.x]*w.x+matrices[j.y]*w.y+matrices[j.z]*w.z+matrices[j.w]*w.w;
|
|
26
|
+
if(w.x+w.y+w.z+w.w<=0){m=mat4x4f(vec4f(1,0,0,0),vec4f(0,1,0,0),vec4f(0,0,1,0),vec4f(0,0,0,1));}
|
|
27
|
+
let p=restPositions[i];positions[i]=vec4f((m*vec4f(p.xyz,1)).xyz,positions[i].w);
|
|
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
|
+
let l=mat3x3f(m[0].xyz,m[1].xyz,m[2].xyz);let c=l*s*transpose(l);
|
|
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("0.1.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("0.1.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};
|