@margoengine/gltf 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 +1438 -3
- package/dist/accessor-DuqjpuxI.js +1 -0
- package/dist/accessor-nVsu_f1L.js +1 -0
- package/dist/accessor.d.ts +12 -0
- package/dist/asset-1b8ejkZX.js +4 -0
- package/dist/asset-entry.d.ts +1 -0
- package/dist/asset-entry.js +1 -0
- package/dist/asset.d.ts +319 -0
- package/dist/audio.d.ts +47 -0
- package/dist/audio.js +1 -0
- package/dist/auto.d.ts +29 -0
- package/dist/auto.js +1 -0
- package/dist/base-textures.d.ts +20 -0
- package/dist/coalesce.d.ts +29 -0
- package/dist/compression-D4IkO5vE.js +1 -0
- package/dist/compression.d.ts +15 -0
- package/dist/coordinates.d.ts +1 -0
- package/dist/coordinates.js +1 -0
- package/dist/dds.d.ts +7 -0
- package/dist/dds.js +1 -0
- package/dist/decoder-default-CxLH8Vz0.js +1 -0
- package/dist/decoder-default.d.ts +5 -0
- package/dist/default-materials.d.ts +8 -0
- package/dist/draco-state.d.ts +7 -0
- package/dist/draw-batch.d.ts +83 -0
- package/dist/draw-memo.d.ts +136 -0
- package/dist/errors-THVaUwlL.js +1 -0
- package/dist/extended.d.ts +12 -0
- package/dist/extended.js +1 -0
- package/dist/gltf.worker.d.ts +1 -0
- package/dist/group.d.ts +6 -0
- package/dist/image-limit-DvFSfR5T.js +1 -0
- package/dist/image-limit.d.ts +6 -0
- package/dist/index.d.ts +84 -0
- package/dist/index.js +1 -0
- package/dist/instanced-shader-BebTnbkj.js +5 -0
- package/dist/instanced-shader.d.ts +14 -0
- package/dist/instancing.d.ts +9 -0
- package/dist/instancing.js +1 -0
- package/dist/interactivity-graph.d.ts +193 -0
- package/dist/interactivity-model.d.ts +94 -0
- package/dist/interactivity-ops.d.ts +20 -0
- package/dist/interactivity.d.ts +33 -0
- package/dist/interactivity.js +1 -0
- package/dist/lights.d.ts +98 -0
- package/dist/lights.js +1 -0
- package/dist/limits-_LZ441oV.js +1 -0
- package/dist/material-draw-state-BHeTb1FP.js +1 -0
- package/dist/material-draw-state.d.ts +7 -0
- package/dist/material-draw.d.ts +18 -0
- package/dist/material-draw.js +1 -0
- package/dist/material-extension.d.ts +96 -0
- package/dist/mesh-source-DvU8YvMc.js +1 -0
- package/dist/meshopt.d.ts +9 -0
- package/dist/meshopt.js +1 -0
- package/dist/metadata.d.ts +114 -0
- package/dist/metadata.js +1 -0
- package/dist/model-entry.d.ts +2 -0
- package/dist/model-entry.js +1 -0
- package/dist/model-iRvuj19h.js +39 -0
- package/dist/model.d.ts +1011 -0
- package/dist/node-image-decode.d.ts +6 -0
- package/dist/node-matrix-R9BipGnp.js +1 -0
- package/dist/node-matrix.d.ts +16 -0
- package/dist/occlusion.d.ts +8 -0
- package/dist/optimize-7SEzNA23.js +1 -0
- package/dist/pack-BVDYuqZe.js +1 -0
- package/dist/pack.d.ts +27 -0
- package/dist/parts.d.ts +54 -0
- package/dist/pbr-instancing.d.ts +83 -0
- package/dist/pbr-instancing.js +1 -0
- package/dist/pbr.d.ts +13 -0
- package/dist/pbr.js +1 -0
- package/dist/physics.d.ts +148 -0
- package/dist/physics.js +1 -0
- package/dist/prepare.d.ts +26 -0
- package/dist/prepare.js +1 -0
- package/dist/progressive.d.ts +59 -0
- package/dist/progressive.js +4 -0
- package/dist/progressive.worker.d.ts +1 -0
- package/dist/quantized.d.ts +8 -0
- package/dist/quantized.js +1 -0
- package/dist/render-state.d.ts +18 -0
- package/dist/replica.d.ts +37 -0
- package/dist/report.d.ts +128 -0
- package/dist/report.js +1 -0
- package/dist/scene-data.d.ts +61 -0
- package/dist/scene-data.js +1 -0
- package/dist/scene-scope-CZDEkd24.js +4 -0
- package/dist/scene.d.ts +61 -0
- package/dist/scene.js +4 -0
- package/dist/shader-DPqfUcmp.js +405 -0
- package/dist/shader.d.ts +222 -0
- package/dist/shared/caster.d.ts +152 -0
- package/dist/shared/gltf.d.ts +257 -0
- package/dist/shared/iridescence.d.ts +2 -0
- package/dist/shared/prepared-geometry.d.ts +8 -0
- package/dist/side-shader.d.ts +1 -0
- package/dist/soft-mesh.d.ts +94 -0
- package/dist/soft-mesh.js +4 -0
- package/dist/spec-gloss.d.ts +21 -0
- package/dist/spec-gloss.js +18 -0
- package/dist/splat-state.d.ts +7 -0
- package/dist/splats.d.ts +18 -0
- package/dist/splats.js +1 -0
- package/dist/src-WMRHArDp.js +4 -0
- package/dist/stream-C3bKMy1B.js +1 -0
- package/dist/stream.d.ts +87 -0
- package/dist/texture-coordinates-XFsEMdU6.js +2 -0
- package/dist/texture-coordinates.d.ts +26 -0
- package/dist/texture-stream-Cu_XpyVO.js +4 -0
- package/dist/texture-stream.d.ts +88 -0
- package/dist/textured.d.ts +34 -0
- package/dist/textured.js +5 -0
- package/dist/uniform-arena.d.ts +78 -0
- package/dist/unit-light-DvtsuFYP.js +109 -0
- package/dist/version-BmU1nesQ.js +1 -0
- package/dist/version.d.ts +8 -0
- package/dist/vertex-inputs.d.ts +47 -0
- package/dist/view-uniform.d.ts +13 -0
- package/dist/visibility-C_Oqz9Sr.js +1 -0
- package/dist/worker-CY1TQnYX.js +1 -0
- package/dist/worker.d.ts +21 -0
- package/dist/worker.js +4 -0
- package/dist/workers/gltf.js +322 -0
- package/dist/workers/progressive.js +1 -0
- package/package.json +213 -6
package/README.md
CHANGED
|
@@ -1,3 +1,1438 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @margoengine/gltf
|
|
2
|
+
|
|
3
|
+
Import `margoengine/gltf` from the `margoengine` package, or `@margoengine/gltf` 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).
|
|
4
|
+
|
|
5
|
+
glTF 2.0 for Margo Engine in one package: the root is a lazy static glTF/GLB loader (named nodes, shared primitive
|
|
6
|
+
geometry), and [`@margoengine/gltf/pbr`](#pbr-rendering-margoenginegltfpbr) is full metallic-roughness PBR rendering with
|
|
7
|
+
its own entries for workers, streaming, instancing, lights, physics, behaviour graphs and more. Each entry loads only what
|
|
8
|
+
it imports, so a page with the light loader pays nothing for PBR.
|
|
9
|
+
|
|
10
|
+
Package name: `@margoengine/gltf`, version `0.1.0`. Build from source or install a local tarball until the renamed package is published.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @margoengine/core@1.0.0 @margoengine/gltf@1.0.0
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { Engine } from 'margoengine/core';
|
|
18
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
19
|
+
|
|
20
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
21
|
+
const engine = await Engine.create(canvas);
|
|
22
|
+
const model = await loadGLTF(engine, '/model.glb');
|
|
23
|
+
engine.start();
|
|
24
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Optional features
|
|
28
|
+
|
|
29
|
+
The root loader reads static models with float positions and constant colours. Each feature below is its own entry, so
|
|
30
|
+
a file that needs none of them costs none of their bytes. Pass the ones you want in `extensions`, to `loadGLTF` or
|
|
31
|
+
`parseGLTF`; they combine. A file needing something no entry covers still throws, with a pointer to `@margoengine/gltf/pbr`.
|
|
32
|
+
|
|
33
|
+
### Quantized meshes
|
|
34
|
+
|
|
35
|
+
`@margoengine/gltf/quantized` reads `KHR_mesh_quantization`: integer POSITION (signed or unsigned, 8 or 16 bit,
|
|
36
|
+
normalized or not) and normalized signed 8 or 16 bit NORMAL. Optimizers such as gltfpack write these. Values turn into
|
|
37
|
+
floats on load, so the file is smaller on the wire and the same size on the GPU.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { Engine } from 'margoengine/core';
|
|
41
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
42
|
+
import { quantized } from 'margoengine/gltf/quantized';
|
|
43
|
+
|
|
44
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
45
|
+
const engine = await Engine.create(canvas);
|
|
46
|
+
const model = await loadGLTF(engine, '/packed.glb', { extensions: [quantized] });
|
|
47
|
+
engine.start();
|
|
48
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Base colour maps and cut-outs
|
|
52
|
+
|
|
53
|
+
`@margoengine/gltf/textured` draws `baseColorTexture` and `alphaMode: 'MASK'`, so a prop with one texture stays on the
|
|
54
|
+
light path. It reads any `TEXCOORD_n` set, in float or normalized form, applies `KHR_texture_transform`, multiplies by
|
|
55
|
+
`baseColorFactor` and cuts at `alphaCutoff` (default 0.5). PNG and JPEG images come from the GLB, a data URI or a URL
|
|
56
|
+
next to the file. Other maps, `BLEND`, and compressed or WebP textures still need `@margoengine/gltf/pbr`.
|
|
57
|
+
A cut-out's mip levels keep the share of texels that pass its cutoff, so leaves do not thin out in the distance.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { Engine } from 'margoengine/core';
|
|
61
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
62
|
+
import { textured } from 'margoengine/gltf/textured';
|
|
63
|
+
|
|
64
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
65
|
+
const engine = await Engine.create(canvas);
|
|
66
|
+
const model = await loadGLTF(engine, '/prop.glb', { extensions: [textured] });
|
|
67
|
+
engine.start();
|
|
68
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Images decode asynchronously, so for bytes already in memory use `parseGLTFAsync(engine, bytes, [], { extensions })` in
|
|
72
|
+
place of `parseGLTF`. It draws on WebGPU and on the WebGL2 compatibility layer (`install()` from
|
|
73
|
+
`@margoengine/webgl2-compat` before `Engine.create`, where the browser has no WebGPU), with the same pixels on the
|
|
74
|
+
same GPU; the small WebGL2 preview refuses the file with `MargoError` code `unsupported`, naming the layer. The meshes stay core meshes, so they move, pick and
|
|
75
|
+
dispose as usual, and packages that patch core's shader apply to them. A cut-out casts its outline through
|
|
76
|
+
`@margoengine/shadows`, and `engine.stats.drawCalls` counts these draws. GPU picks see a cut-out as solid, because core's
|
|
77
|
+
pick draw has no uv; for a ray that passes through the holes, `texturedAlphaMasks(model, {signal, pixels})` gives
|
|
78
|
+
`AlphaRaycaster` its masks. Call it before `model.dispose()`; it reads each image once through an `OffscreenCanvas`, so in
|
|
79
|
+
Node pass `pixels`.
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { Engine } from 'margoengine/core';
|
|
83
|
+
import { AlphaRaycaster } from 'margoengine/bvh/alpha';
|
|
84
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
85
|
+
import { textured, texturedAlphaMasks } from 'margoengine/gltf/textured';
|
|
86
|
+
|
|
87
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
88
|
+
const model = await loadGLTF(engine, '/fence.glb', { extensions: [textured] });
|
|
89
|
+
const ray = new AlphaRaycaster();
|
|
90
|
+
ray.alphaMask = await texturedAlphaMasks(model);
|
|
91
|
+
ray.firstHitOnly = true; // the nearest solid hit
|
|
92
|
+
ray.setFromEngine(engine, 320, 240);
|
|
93
|
+
console.log(ray.intersectEngine(engine)[0]?.mesh);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Meshopt compression
|
|
97
|
+
|
|
98
|
+
`@margoengine/gltf/meshopt` reads `EXT_meshopt_compression` and `KHR_meshopt_compression`, every mode and filter.
|
|
99
|
+
`@margoengine/decoders/meshopt` is imported on the first file that uses them, so install `@margoengine/decoders` beside
|
|
100
|
+
this package; a file with no compressed views never loads it. A fallback buffer is not downloaded. Optimizers usually
|
|
101
|
+
quantize as well, so pass both.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import { Engine } from 'margoengine/core';
|
|
105
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
106
|
+
import { meshopt } from 'margoengine/gltf/meshopt';
|
|
107
|
+
import { quantized } from 'margoengine/gltf/quantized';
|
|
108
|
+
|
|
109
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
110
|
+
const engine = await Engine.create(canvas);
|
|
111
|
+
const model = await loadGLTF(engine, '/small.glb', { extensions: [meshopt, quantized] });
|
|
112
|
+
engine.start();
|
|
113
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Decoded data may reach 64 MiB per file; a larger one is refused with code `unsupported` naming `@margoengine/gltf/pbr`
|
|
117
|
+
(512 MiB by default), which `loadAuto` moves to by itself. For bytes in memory use `parseGLTFAsync`.
|
|
118
|
+
|
|
119
|
+
What the light loader reads as the glTF 2.0 specification says: `asset.version` 2.x with no `minVersion` or
|
|
120
|
+
`minVersion` 2.0 (section 3.2); a primitive without POSITION is skipped and the rest loads (3.7.2.1); an OPAQUE colour
|
|
121
|
+
draws whatever its alpha (3.9.4); a material is checked only when a primitive uses it; the GLB BIN chunk serves buffer 0
|
|
122
|
+
only (3.6.1.2). A failed or aborted load closes every image it decoded. An extension that holds something from `load`
|
|
123
|
+
releases it in its optional `abandon(file)`, which runs when the load fails or is aborted after `load`.
|
|
124
|
+
|
|
125
|
+
### GPU instancing
|
|
126
|
+
|
|
127
|
+
`@margoengine/gltf/instancing` reads `EXT_mesh_gpu_instancing`, for forests and repeated props. Each instance becomes a
|
|
128
|
+
child node of the instanced node, on the shared mesh, and core draws all of them as one instanced draw per primitive.
|
|
129
|
+
TRANSLATION, ROTATION and SCALE are read in float or quantized form; other instance attributes are ignored.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { Engine } from 'margoengine/core';
|
|
133
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
134
|
+
import { instancing } from 'margoengine/gltf/instancing';
|
|
135
|
+
|
|
136
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
137
|
+
const engine = await Engine.create(canvas);
|
|
138
|
+
const model = await loadGLTF(engine, '/forest.glb', { extensions: [instancing], maxNodes: 500_000 });
|
|
139
|
+
engine.start();
|
|
140
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
An instance costs one core mesh plus one per primitive, shows up in `model.nodes` and `model.meshes`, can be moved like
|
|
144
|
+
any node, and counts toward `maxNodes` (default 100,000).
|
|
145
|
+
|
|
146
|
+
### Any file, without choosing a loader
|
|
147
|
+
|
|
148
|
+
`loadAuto` from `@margoengine/gltf/auto` reads the file, runs the light loader with only the entries that file calls for,
|
|
149
|
+
and imports `@margoengine/gltf/pbr` only if the light loader refuses it as unsupported, or the file passes a limit only
|
|
150
|
+
the light loader has: one million vertices in total, one million values in an accessor, 64 MiB of downloads, or
|
|
151
|
+
instances past `maxNodes`. Each URL is downloaded once, whichever loader runs. A malformed file is an error either way,
|
|
152
|
+
and so is a file over a limit both loaders share: gltf/pbr's 512 MiB, or more real nodes than `maxNodes`. Install `@margoengine/gltf/pbr` beside this package for
|
|
153
|
+
files that need it; without it such a file rejects with a message that says so. It also takes `signal`, `fetch`,
|
|
154
|
+
`maxNodes` and `allowedURLs`.
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import { Engine } from 'margoengine/core';
|
|
158
|
+
import { loadAuto } from 'margoengine/gltf/auto';
|
|
159
|
+
|
|
160
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
161
|
+
const engine = await Engine.create(canvas);
|
|
162
|
+
const { model, loader } = await loadAuto(engine, '/any.glb');
|
|
163
|
+
console.log(`Loaded by ${loader}`);
|
|
164
|
+
engine.start();
|
|
165
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`model` is a light `Model` or a `PBRModel`; `loader` tells them apart, and with `'gltf/pbr'` the result also holds the
|
|
169
|
+
`reason` the light loader gave.
|
|
170
|
+
|
|
171
|
+
### Cameras and lights as data
|
|
172
|
+
|
|
173
|
+
`@margoengine/gltf/scene-data` accepts nodes with a glTF camera or a `KHR_lights_punctual` light, and hands them back as
|
|
174
|
+
plain data, so a scene file can set up its own view and sun. Nothing is created in the engine: the app decides what to do
|
|
175
|
+
with them. `loadAuto` adds the entry for you, and `sceneData` reads its result too.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { Engine } from 'margoengine/core';
|
|
179
|
+
import { loadGLTF } from 'margoengine/gltf';
|
|
180
|
+
import { sceneData, sceneExtras } from 'margoengine/gltf/scene-data';
|
|
181
|
+
|
|
182
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
183
|
+
const engine = await Engine.create(canvas);
|
|
184
|
+
const model = await loadGLTF(engine, '/shot.glb', { extensions: [sceneExtras] });
|
|
185
|
+
const { cameras, lights } = sceneData(model);
|
|
186
|
+
const view = cameras[0];
|
|
187
|
+
if (view) console.log(view.position, view.direction, view.type === 'perspective' ? view.yfov : view.ymag);
|
|
188
|
+
for (const light of lights) console.log(light.type, light.color, light.intensity);
|
|
189
|
+
engine.start();
|
|
190
|
+
// On teardown: model.dispose(); engine.dispose();
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Each entry holds the node's `name`, its `node` handle, and its world `position`, `direction` and `matrix` at load with the
|
|
194
|
+
model at its origin; the projection or light values follow glTF's names and units, with the defaults filled in. Only
|
|
195
|
+
nodes of the loaded scene count. A file still needs a mesh: one with only cameras and lights is refused.
|
|
196
|
+
|
|
197
|
+
This ESM package includes TypeScript declarations and requires `@margoengine/core` 1.0.0. See the supported glTF subset and lifecycle guide before importing assets.
|
|
198
|
+
|
|
199
|
+
Apache-2.0 licensed.
|
|
200
|
+
|
|
201
|
+
### Git LFS pointer files
|
|
202
|
+
|
|
203
|
+
A repository cloned without Git LFS serves small pointer files (text starting `version https://git-lfs`) in place of
|
|
204
|
+
its models. `loadGLTF` and `loadAuto` check every .gltf, .glb, external .bin and image they fetch, and `parseGLTF`
|
|
205
|
+
the bytes or text it is given; a pointer rejects with a `MargoError` (code `failed`) that names the URL and links to
|
|
206
|
+
https://margoengine.com/errors#git-lfs. Run `git lfs pull` where the files are served, then reload.
|
|
207
|
+
|
|
208
|
+
### GLB padding
|
|
209
|
+
|
|
210
|
+
A GLB's BIN chunk may be up to 3 bytes longer than buffer 0's `byteLength`, to pad it to 4 bytes (glTF 2.0 section
|
|
211
|
+
4.4.3.3). `parseGLTF`, `parseGLTFAsync` and `loadGLTF` refuse a longer chunk, as the Khronos glTF Validator does, with a `MargoError` (code `failed`)
|
|
212
|
+
that gives both lengths and links to https://margoengine.com/errors#failed. Export the file again.
|
|
213
|
+
|
|
214
|
+
### Loading into a second scene
|
|
215
|
+
|
|
216
|
+
`parseGLTFAsync`, `loadGLTF` and `loadAuto` remember the scene that is active when you call them, before their first
|
|
217
|
+
await, and build the model there, textured draw included, even though the download finishes later. Start a load inside
|
|
218
|
+
a second scene's plugin `setup` (or any code running while that scene is set up) and the meshes and the draw belong to
|
|
219
|
+
that scene; start it anywhere else and they belong to the default scene. If the scene is disposed while the load runs,
|
|
220
|
+
the load rejects with a `TypeError` and nothing is left in the default scene. An abort leaves nothing in either scene.
|
|
221
|
+
|
|
222
|
+
### A report without a GPU (`@margoengine/gltf/report`)
|
|
223
|
+
|
|
224
|
+
`reportGLTF(bytes, options)` reads a GLB (or glTF JSON with embedded buffers) in Node or a browser with no GPU and no
|
|
225
|
+
engine, with the loader's own accessor reader: triangles, vertices and primitives the default scene draws (each node
|
|
226
|
+
and `EXT_mesh_gpu_instancing` instance counted), meshes, nodes, materials, textures, images with their sizes from
|
|
227
|
+
their headers (PNG, JPEG, WebP, KTX2), texture pixels and RGBA bytes, world bounds of every drawn vertex, the
|
|
228
|
+
extensions used and required (and which of those Margo's loaders do not read), and `problems`, each with a stable
|
|
229
|
+
`code` and a sentence: `not-gltf`, `json`, `extension`, `external`, `image-format`, `accessor`, `index-range`,
|
|
230
|
+
`not-finite` (a NaN or infinity in an attribute, named with its primitive and attribute; the finite rest is still
|
|
231
|
+
counted), `no-normals`, `no-uvs`, `no-material`, `zero-area`, `inside-out` (a closed primitive whose signed volume is
|
|
232
|
+
negative in its own space: a mirroring node, whose world transform has a negative determinant, turns the front face
|
|
233
|
+
too, glTF 2.0 section 3.7.4, so it never turns a mesh inside out), `decode` and `empty`. `zeroAreaByNode` lists each
|
|
234
|
+
scene node that draws zero-area triangles with its mesh and counts, so a repair knows which meshes to open. It never
|
|
235
|
+
throws on a bad file. With `alpha: true` it also decodes the base colour
|
|
236
|
+
textures of MASK and BLEND primitives and returns `cutouts.bounds`, the bounds of what those cards draw where their
|
|
237
|
+
alpha passes the cutoff, so a tree of leaf cards is framed by its leaves rather than its quads' see-through margins.
|
|
238
|
+
Draco and meshopt geometry is decoded with the built-in decoders, imported only for a file that needs one;
|
|
239
|
+
`decoders` takes your own, as `loadGLTF` does. Draco geometry that cannot be decoded is counted from its accessors'
|
|
240
|
+
declared counts and bounds, with a `decode` problem.
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
import {reportGLTF} from 'margoengine/gltf/report';
|
|
244
|
+
import {readFile} from 'node:fs/promises';
|
|
245
|
+
const report = await reportGLTF(new Uint8Array(await readFile('FourUV.glb')), {alpha: true});
|
|
246
|
+
console.log(report.ok, report.counts.triangles, report.bounds?.size, report.extensions.required);
|
|
247
|
+
for (const problem of report.problems) console.log(problem.code, problem.detail);
|
|
248
|
+
for (const {where, mesh, zeroArea} of report.zeroAreaByNode) console.log(`${where} (mesh ${mesh}): ${zeroArea} zero-area triangles`);
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Drawing a soft body (`@margoengine/gltf/soft-mesh`)
|
|
252
|
+
|
|
253
|
+
`margoengine/gltf/soft-mesh` draws a cloth, a closed surface or a skinned solid of `margoengine/physics/soft` with one call, as a PBR model that follows the body every frame; the cloth examples of other web engines do this by hand (copy the positions, recompute the normals). It reads the body through its public API, so `margoengine/physics` stays an optional peer of this package and the entry carries no physics code.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
import {Engine} from 'margoengine/core';
|
|
257
|
+
import {Physics} from 'margoengine/physics';
|
|
258
|
+
import {SoftBodies, SoftBodyDesc} from 'margoengine/physics/soft';
|
|
259
|
+
import {drawSoftBody} from 'margoengine/gltf/soft-mesh';
|
|
260
|
+
|
|
261
|
+
await Physics.load();
|
|
262
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
263
|
+
const physics = new Physics(engine);
|
|
264
|
+
const soft = await SoftBodies.attach(physics);
|
|
265
|
+
|
|
266
|
+
// A flag of 20 x 12 particles hung by its two top corners.
|
|
267
|
+
const flag = soft.create(SoftBodyDesc.cloth([-1, 3, 0], [0.1, 0, 0], [0, -0.1, 0], 20, 12).setPinnedParticles([0, 228]));
|
|
268
|
+
const mesh = drawSoftBody(engine, flag, {
|
|
269
|
+
material: {pbrMetallicRoughness: {baseColorFactor: [0.8, 0.1, 0.1, 1], roughnessFactor: 0.9}},
|
|
270
|
+
});
|
|
271
|
+
engine.start();
|
|
272
|
+
// mesh.dispose() removes it again; `using mesh = drawSoftBody(...)` does so at the end of the block.
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
- **What follows the body.** Each frame, before the engine draws and after the physics step (the mesh is a `late` plugin, as physics is, so make it after `new Physics(engine)`), the vertices are copied from the particles (from the skin, for a body with `setSkin`), and the normals (the area-weighted sum of the triangles' normals) and tangents (from the UVs, Lengyel 2001) are recomputed; the vertices upload in place, the triangles never change. A sleeping body is not copied. A removed body (or one that split on a tear) stops the mesh at its last pose: draw its pieces from `soft.onTear` with `drawSoftBody` again.
|
|
276
|
+
- **Texture coordinates.** A body built by `cloth`, `clothAnisotropic` or `clothTube` takes its grid: particle (i, j) at (i / (nu - 1), j / (nv - 1)), a tube's seam doubled so u runs from 0 to 1 around it (the two seam vertices share their normal and tangent). Any other body lays its shape at creation flat on the plane of its two largest extents, scaled to 0..1, or takes `uvs` (two numbers a particle, or a skin vertex).
|
|
277
|
+
- **Material.** `material` is a glTF 2.0 material (default `{doubleSided: true, pbrMetallicRoughness: {metallicFactor: 0, roughnessFactor: 0.8}}`, a matte sheet seen from both sides; `doubleSided` stays true unless it says false). Its textures name `images` by index (texture `i` is image `i`, an `ImageBitmap` or `{width, height, data}` RGBA8 pixels), so a fabric map with a normal map is `{images: [colour, normals], material: {pbrMetallicRoughness: {baseColorTexture: {index: 0}}, normalTexture: {index: 1}}}`.
|
|
278
|
+
- **The mesh.** `drawSoftBody(engine, body, options)` returns a `SoftBodyMesh`: `model` (the `PBRModel` it draws with, for visibility, picking and the rest of the model API), `surface`, `sync()` (move it to the body now), `dispose()` and `Symbol.dispose`. `new SoftSurface(body, {uvs})` is the CPU half alone: `vertices` (20 floats a vertex: position and 1, normal and 0, tangent and its handedness, two UV sets, colour), `indices`, `uvs`, `vertexCount` and `update()`, for an app that uploads the vertices itself. `body.particlePositions(target)` fills a `Float32Array` of three numbers a particle without allocating.
|
|
279
|
+
- **Errors.** A body with no triangles (a rope, a bare particle set) throws a `TypeError` naming `@margoengine/lines` for ropes; a removed body throws a `MargoError` with code `state`; `uvs` of the wrong length throws a `RangeError`.
|
|
280
|
+
|
|
281
|
+
## Preview tier contract
|
|
282
|
+
|
|
283
|
+
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.
|
|
284
|
+
|
|
285
|
+
The textured pass uses the same CPU-normalized light direction as constant
|
|
286
|
+
materials. Direction magnitude does not change the lighting; its fourth
|
|
287
|
+
component still controls intensity.
|
|
288
|
+
|
|
289
|
+
## PBR rendering (`@margoengine/gltf/pbr`)
|
|
290
|
+
|
|
291
|
+
Import `margoengine/gltf/pbr` from the `margoengine` package, or `@margoengine/gltf/pbr` from this package alone; the two
|
|
292
|
+
are the same module. Its other entries sit beside it: `/pbr-model` (the model classes without the decoders),
|
|
293
|
+
`/pbr-instancing`, `/extended-materials`, `/texture-coordinates`, `/asset`, `/scene`, `/prepare`, `/progressive`,
|
|
294
|
+
`/worker`, `/splats`, `/lights`, `/physics`, `/interactivity`, `/metadata`, `/material-draw`, `/spec-gloss`, `/dds` and
|
|
295
|
+
`/audio`.
|
|
296
|
+
|
|
297
|
+
Optional WebGPU glTF 2.0 metallic-roughness rendering, separate from the frozen core and stage.
|
|
298
|
+
|
|
299
|
+
Core + stage must remain below **25,000 bytes gzip**; CI rejects 25,000 bytes and above. Optional loaders, decoder code, workers and Wasm stay outside that measurement.
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
import {createStage} from 'margoengine';
|
|
303
|
+
import {loadGLTF, type MaterialExtension} from 'margoengine/gltf/pbr';
|
|
304
|
+
const stage = await createStage('#viewport', {backend:'webgpu'});
|
|
305
|
+
const model = await loadGLTF(stage.engine, '/SciFiHelmet.glb');
|
|
306
|
+
const b = model.bounds;
|
|
307
|
+
stage.engine.camera.fitToBoundingBox([b[0],b[1],b[2]], [b[3],b[4],b[5]]);
|
|
308
|
+
// Call model.destroy() when unloading the model, or stage.dispose() on unmount.
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
A loaded model has `root` (the group every node hangs from), `nodes` (every glTF node, by index), `meshes` (the nodes that draw a triangle primitive, each once, in primitive order) and `primitives`. `@margoengine/gltf`'s `loadGLTF` returns `root`, `nodes` and `meshes` too, so code that loops over `model.meshes` runs on either loader. To cast shadows, `shadows.add(model)` or `shadows.add(model.root)` does the whole model.
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
import { Engine } from 'margoengine/core';
|
|
315
|
+
import { loadGLTF } from 'margoengine/gltf/pbr';
|
|
316
|
+
import { Shadows } from 'margoengine/shadows';
|
|
317
|
+
|
|
318
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
319
|
+
const model = await loadGLTF(engine, '/model.glb');
|
|
320
|
+
console.log(model.meshes.length); // the drawn nodes, as from the light loader
|
|
321
|
+
Shadows.attach(engine).add(model.root); // the root is a group: every node below it casts
|
|
322
|
+
|
|
323
|
+
model.root.setParent(engine.createMesh()); // root and nodes are the public `Mesh`: parent to and from your meshes, no cast
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
The root and every node are also core's public `Mesh`, the type `engine.createMesh()` returns, so a model parents to a
|
|
327
|
+
mesh of yours, or yours to one of its nodes, without a cast:
|
|
328
|
+
|
|
329
|
+
```ts
|
|
330
|
+
import { Engine } from 'margoengine/core';
|
|
331
|
+
import { loadGLTF } from 'margoengine/gltf/pbr';
|
|
332
|
+
|
|
333
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
334
|
+
const model = await loadGLTF(engine, '/model.glb');
|
|
335
|
+
const turntable = engine.createMesh();
|
|
336
|
+
model.root.setParent(turntable); // the whole model turns with it
|
|
337
|
+
turntable.setRotation([0, Math.PI / 4, 0]);
|
|
338
|
+
const marker = engine.createMesh();
|
|
339
|
+
marker.setParent(model.nodes[0]); // and a mesh of yours follows a node of the model
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
`Picking.attach(engine)` from `@margoengine/selection` discovers loader-owned
|
|
343
|
+
primitive nodes automatically. `selection.set([primitive.node])` also discovers
|
|
344
|
+
their model; explicit `add(model)` remains supported and is deduplicated.
|
|
345
|
+
Custom buffer providers still register explicitly. Both consume `model.pickingPrimitives`,
|
|
346
|
+
which borrows the current static or GPU-deformed buffers and alpha metadata.
|
|
347
|
+
Registration changes no beauty shader, vertex layout or material bindings.
|
|
348
|
+
|
|
349
|
+
`model.readPickingGeometry()` returns an asynchronous, independently owned CPU
|
|
350
|
+
snapshot for `Raycaster.intersectModel(model)` in `@margoengine/bvh`. Static
|
|
351
|
+
geometry uses CPU copies; animated geometry is copied from the actual GPU output.
|
|
352
|
+
The optional `prepareDeformation` hook encodes the latest pose before reading,
|
|
353
|
+
without advancing animation time. Snapshots include world matrices, indices,
|
|
354
|
+
material sides and identity (`primitiveIndex` in `model.primitives`, absent for
|
|
355
|
+
point and line primitives, and the glTF `nodeIndex` when it has one) captured
|
|
356
|
+
with the query,
|
|
357
|
+
before any readback. Restoration, disposal or replacement of
|
|
358
|
+
an in-flight deformation output invalidates the result and releases staging
|
|
359
|
+
buffers. Caller-provided deformation buffers need `COPY_SRC` for CPU snapshots.
|
|
360
|
+
|
|
361
|
+
Use `import {GLTFAsset} from '@margoengine/gltf/asset'` for accessor decoding
|
|
362
|
+
without loading PBR rendering or its shaders. The root export retains the same
|
|
363
|
+
constructor; `GLTFDocument` is available as a type from either entry.
|
|
364
|
+
`@margoengine/gltf/splats` exports `gaussianSplats` and `readGaussianSplats` ([below](#gaussian-splats-in-gltf-splats)).
|
|
365
|
+
A node `scale` with a zero axis, and a `matrix` with zero columns, load in both loaders (glTF 2.0 section 3.5.3): the
|
|
366
|
+
node is flattened on that axis, or drawn as nothing when every axis is zero. A matrix whose nonzero columns are
|
|
367
|
+
dependent or not orthogonal still throws (`Singular glTF matrix`, `Sheared matrices are unsupported`).
|
|
368
|
+
|
|
369
|
+
`@margoengine/gltf/texture-coordinates` exports `textureCoordinates` and the `TextureTransform` type (also on the root)
|
|
370
|
+
for material extensions that read texture coordinates without loading the renderer.
|
|
371
|
+
|
|
372
|
+
The native volume tint estimates a slab through `thicknessFactor` in mesh units, times the green channel of
|
|
373
|
+
`thicknessTexture` where the material has one (KHR_materials_volume; the map binds slot 20 of the extended shader, so a
|
|
374
|
+
transmissive material with a thickness map compiles that variant), and
|
|
375
|
+
converts the refracted path to world units before applying Beer-Lambert absorption. A texel of 0 is a thin wall that
|
|
376
|
+
absorbs nothing.
|
|
377
|
+
Node scale, rotation, shear, reflection and `EXT_mesh_gpu_instancing` affect that path;
|
|
378
|
+
`attenuationDistance` stays in world units. This path retains its scalar thickness
|
|
379
|
+
approximation per texel and display-space blend; the optional transmission installation supplies
|
|
380
|
+
screen-space refraction. Default normal textures use exactly
|
|
381
|
+
neutral half-float texels, including when a live shading hook retains fallback bindings.
|
|
382
|
+
Run `npm run test:gpu:native-volume --workspace @margoengine/gltf` after the package
|
|
383
|
+
build for 64 analytic slab pixels on each backend, including transmission animated from zero and a thickness map.
|
|
384
|
+
|
|
385
|
+
#### Animate an opaque material into glass
|
|
386
|
+
|
|
387
|
+
`KHR_materials_transmission` may start at its default factor of `0`. The physical
|
|
388
|
+
parser retains the volume while zero stays on the opaque draw path. Pointer playback
|
|
389
|
+
activates the tint and native background capture when the factor becomes positive;
|
|
390
|
+
seeking back to zero restores the opaque path. This example builds its own triangle
|
|
391
|
+
and animation, with no asset download:
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
import {Engine} from 'margoengine/core';
|
|
395
|
+
import {parseGLTF, type GLTFDocument} from 'margoengine/gltf/pbr';
|
|
396
|
+
import {extendedMaterials} from 'margoengine/gltf/extended-materials';
|
|
397
|
+
import {Animation} from 'margoengine/animation';
|
|
398
|
+
import {pointerChannels} from 'margoengine/animation/pointer';
|
|
399
|
+
|
|
400
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {
|
|
401
|
+
camera: {position: [0, 0, 3], target: [0, 0, 0]},
|
|
402
|
+
});
|
|
403
|
+
const data = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0, 0, 1, 0, 1]);
|
|
404
|
+
const doc: GLTFDocument = {
|
|
405
|
+
asset: {version: '2.0'},
|
|
406
|
+
extensionsUsed: ['KHR_materials_transmission', 'KHR_materials_volume', 'KHR_animation_pointer'],
|
|
407
|
+
buffers: [{byteLength: data.byteLength}],
|
|
408
|
+
bufferViews: [{buffer: 0, byteLength: 36}, {buffer: 0, byteOffset: 36, byteLength: 8},
|
|
409
|
+
{buffer: 0, byteOffset: 44, byteLength: 8}],
|
|
410
|
+
accessors: [{bufferView: 0, componentType: 5126, count: 3, type: 'VEC3'},
|
|
411
|
+
{bufferView: 1, componentType: 5126, count: 2, type: 'SCALAR'},
|
|
412
|
+
{bufferView: 2, componentType: 5126, count: 2, type: 'SCALAR'}],
|
|
413
|
+
materials: [{pbrMetallicRoughness: {metallicFactor: 0}, extensions: {
|
|
414
|
+
KHR_materials_transmission: {transmissionFactor: 0},
|
|
415
|
+
KHR_materials_volume: {thicknessFactor: 1, attenuationColor: [0.25, 0.5, 1], attenuationDistance: 1},
|
|
416
|
+
}}],
|
|
417
|
+
meshes: [{primitives: [{attributes: {POSITION: 0}, material: 0}]}],
|
|
418
|
+
nodes: [{mesh: 0}], scenes: [{nodes: [0]}], scene: 0,
|
|
419
|
+
animations: [{samplers: [{input: 1, output: 2}], channels: [{sampler: 0, target: {
|
|
420
|
+
path: 'pointer', extensions: {KHR_animation_pointer: {
|
|
421
|
+
pointer: '/materials/0/extensions/KHR_materials_transmission/transmissionFactor',
|
|
422
|
+
}},
|
|
423
|
+
}}]}],
|
|
424
|
+
};
|
|
425
|
+
const model = parseGLTF(engine, doc, [data], [], {materials: extendedMaterials});
|
|
426
|
+
const animation = Animation.attach(model, {pointers: pointerChannels, loop: false});
|
|
427
|
+
animation.playing = false;
|
|
428
|
+
animation.seek(1);
|
|
429
|
+
console.log(model.primitives[0].material.tint); // [0.25, 0.5, 1]
|
|
430
|
+
engine.start();
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
`KHR_node_visibility` sets each node's `visible` flag, also when the extension is required. A hidden ancestor hides the meshes and lights below it; transforms, animation, sockets and cameras keep working. Toggle `model.nodes[index].visible` to change it. `model.clusteredLights()` leaves out lights under hidden nodes. After changing visibility, call `applyGLTFLights(model)` again to refresh the imported sun; if the model no longer has a visible sun, the lighting from before goes back, unless the caller changed it since. `@margoengine/animation/pointer` plays animated visibility (`KHR_animation_pointer`).
|
|
434
|
+
|
|
435
|
+
Supports base color/alpha, metallic-roughness (G/B), normal maps, occlusion (R), emissive, vertex colors, UV sets 0 to 3, tangents or derivative tangent frames, alpha masking/blending, double-sided materials, GLB/external buffers/images, normalized and sparse accessors. GGX, Smith, and Schlick implement analytical direct lighting with hemispherical ambient fill. Canvas output uses Khronos PBR Neutral tone mapping and sRGB encoding; HDR captures remain linear. Color/emissive textures decode sRGB; other maps remain linear. Images have generated mip chains (an area filter at odd sizes, so no texel is skipped; colour weighted by alpha for `BLEND` base colour maps, so transparent texels give no dark fringes) and honor glTF filtering and wrapping.
|
|
436
|
+
|
|
437
|
+
The outside-reference test renders all 123 primitives of Khronos MetalRoughSpheresNoTextures with a shared
|
|
438
|
+
camera and sun. Against a Sample Viewer PNG, full-frame RGB byte MAE is 1.7865498860677083 on the recorded
|
|
439
|
+
RTX A6000; the WebGL2 compatibility layer measures 1.7865447998046875. Native WebGL2 rejects PBR with code
|
|
440
|
+
`unsupported`. These are measured error ceilings, not visual parity. The unresolved picture loss, full
|
|
441
|
+
settings, source hashes and coverage are in [reproduction steps](../../docs/whitepaper/reproduce.md#batch-160-metallic-roughness).
|
|
442
|
+
From a built checkout, with the outside reference PNG already captured:
|
|
443
|
+
|
|
444
|
+
```sh
|
|
445
|
+
node scripts/reference-rendering/fetch-assets.mjs
|
|
446
|
+
node scripts/run-with-timeout.mjs --max=5 -- node scripts/reference-rendering/run.mjs
|
|
447
|
+
node scripts/run-with-timeout.mjs --max=5 -- node scripts/reference-rendering/run.mjs --compat
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
Loaded triangle materials expose live `side: 'front' | 'back' | 'double'`, initialized from glTF's `doubleSided`.
|
|
451
|
+
For example, `model.primitives[0].material.side = 'back'` switches to back-only rendering next frame. Mirrored
|
|
452
|
+
nodes and mixed mirrored instances retain local winding. Picking and beauty/auxiliary passes agree on sides;
|
|
453
|
+
points and lines ignore triangle sides. Shadow casters retain their existing two-sided policy. `exportModel`
|
|
454
|
+
in `@margoengine/exporters` bakes back-only winding and normals into glTF-compatible geometry.
|
|
455
|
+
|
|
456
|
+
Set `primitive.material.wireframe = true` to draw triangle edges as one-pixel WebGPU lines. The flag is live,
|
|
457
|
+
defaults to false, and applies to beauty, auxiliary, transparency, capture and shadow passes, including groups,
|
|
458
|
+
instances and deformed vertices. Each edge draws once per primitive, so a shared edge blends like any other on
|
|
459
|
+
transparent surfaces. Points and existing lines keep their topology. Lines ignore triangle face culling and
|
|
460
|
+
polygon bias. Edge index buffers are allocated on first use, reused across toggles, and released on restoration
|
|
461
|
+
or disposal. Picking, CPU snapshots and glTF export retain the original filled triangle geometry; glTF has no
|
|
462
|
+
wireframe material flag. Directional sources registered with `Shadows.add(source, {static: true})` require the
|
|
463
|
+
existing `Shadows.invalidate()` call after a live toggle; automatically cached casters update themselves.
|
|
464
|
+
|
|
465
|
+
Cut-outs keep their density in the distance: the mip chain of a `MASK` base colour map (uncompressed, sampled with
|
|
466
|
+
mips) is built on the GPU so each level passes the material's cutoff for the same share of texels as the full image,
|
|
467
|
+
the nearest share that level's texels allow (Castano, "Computing Alpha Mipmaps", 2010). Colour is averaged in linear
|
|
468
|
+
light weighted by alpha, so transparent texels lend no colour to leaf edges, and every texel of an odd-sized image is
|
|
469
|
+
counted. The chain is fitted to the material's cutoff and base alpha at load; the same image under another cutoff gets
|
|
470
|
+
its own copy. Nothing to set.
|
|
471
|
+
|
|
472
|
+
`primitive.material.renderState` supplies beauty-only blend/depth overrides, polygon bias, stencil face states,
|
|
473
|
+
masks/reference, `colorWrite`, `alphaToCoverage` (MASK materials on a multisampled target: edges cut by sample coverage) and `blendSpace` (`'linear'`: a BLEND material on a display-encoded target mixes in linear light from the native glass snapshot, one pass break and target copy per surface; default `'display'`; KB3148b; a transparency hook with `linearLayers`, such as `@margoengine/oit`'s `OIT`, takes it order-independently, KB3148d). Bias defaults to literal WebGPU values; `depthBiasMode: 'away'` keeps positive
|
|
474
|
+
offsets away from the camera across main reverse-Z and forward-Z device views. `stencilReference` is live per draw
|
|
475
|
+
and reuses pipelines. Native front/back stencil states follow raster winding. Different face operations temporarily
|
|
476
|
+
use the original primitives instead of winding-normalized static batches; symmetric state restores batching.
|
|
477
|
+
Stencil requires a stencil attachment;
|
|
478
|
+
`StencilBuffer` from `@margoengine/materials` supplies one for the scene when needed. Auxiliary/capture replays,
|
|
479
|
+
picking and shadows retain their existing behavior. See the [material controls](../materials/README.md#polygon-offset-and-stencil)
|
|
480
|
+
for constructor options, target boundaries and transmission behavior. glTF export omits these render controls.
|
|
481
|
+
|
|
482
|
+
`loadGLTF` automatically decodes `KHR_draco_mesh_compression` primitives and
|
|
483
|
+
`EXT_meshopt_compression` and `KHR_meshopt_compression` buffer views and `KHR_texture_basisu` textures using `@margoengine/decoders`, installed as
|
|
484
|
+
a dependency. Draco workers and Wasm start only when compressed primitives are
|
|
485
|
+
encountered and are released after decoding, including on failure or cancellation.
|
|
486
|
+
Meshopt decoding is synchronous and cached per buffer view, including views used
|
|
487
|
+
by skin, morph and animation accessors. Unknown required extensions still fail.
|
|
488
|
+
Both meshopt names support marked fallback buffers and URI-less placeholders.
|
|
489
|
+
Marked fallback files are not fetched; compressed views supply their bytes instead.
|
|
490
|
+
An unmarked, absent fallback requires the matching compression extension to be
|
|
491
|
+
required. A buffer or view cannot declare both names. Normal loads need no decoder
|
|
492
|
+
configuration:
|
|
493
|
+
|
|
494
|
+
```ts
|
|
495
|
+
import {Engine} from 'margoengine/core';
|
|
496
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
497
|
+
|
|
498
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
499
|
+
const model = await loadGLTF(engine, '/model.glb');
|
|
500
|
+
console.log(model.primitives.length);
|
|
501
|
+
engine.render();
|
|
502
|
+
model.dispose();
|
|
503
|
+
engine.dispose();
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
For in-memory JSON or GLB bytes, use `await parseGLTFAsync(engine, input)` or pass an options object as the third
|
|
507
|
+
argument, for example `{buffers, signal, draco, ktx2}`. Both forms decode embedded PNG/JPEG and KTX2 images;
|
|
508
|
+
external buffers and images resolve against the `baseURL` option (`{baseURL: 'https://cdn.example.com/models/car.gltf'}`); a file in memory has no location, so without it an external URI is refused with a coded error and nothing is fetched. Passing `undefined` as the third argument alone behaves like
|
|
509
|
+
omitting it. Decoded bitmaps close with the model, or before rejection on decode, size-limit, cancellation or attachment
|
|
510
|
+
failure.
|
|
511
|
+
|
|
512
|
+
The positional `await parseGLTFAsync(engine, input, buffers, images, {signal, draco, ktx2})` overload keeps supplied
|
|
513
|
+
ordinary bitmaps and decodes embedded KTX2 when needed. Passing `undefined` for buffers with a fourth or fifth argument
|
|
514
|
+
retains this positional behavior. Use the no-options/options-object form for automatic ordinary image decoding.
|
|
515
|
+
`@margoengine/gltf/pbr-model` holds `PBRModel`, `PBRDrawRun`, `GLTFAsset`, `parseGLTF`, `parsePreparedPBR`, `closeImages`,
|
|
516
|
+
`textureTransform`, `textureCoordinates` and every type, and reaches no decoder module. A bundler copies the Draco and
|
|
517
|
+
Basis Wasm when it reads a module that names them, used or not, so import from `/model` in code that loads no compressed
|
|
518
|
+
file. Only the package root names them; a Draco or KTX2 file reached any other way is refused with `unsupported`, unless
|
|
519
|
+
`decoders.decoderModule` says where they are:
|
|
520
|
+
|
|
521
|
+
```ts
|
|
522
|
+
import {GLTFAsset} from 'margoengine/gltf/pbr-model';
|
|
523
|
+
const doc = await (await fetch('/model.gltf')).json();
|
|
524
|
+
const bytes = new Uint8Array(await (await fetch('/model.bin')).arrayBuffer());
|
|
525
|
+
const asset = new GLTFAsset(doc, [bytes], undefined, {decoderModule: () => import('margoengine/decoders')});
|
|
526
|
+
await asset.decode();
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
The existing `parseGLTF(engine, input, buffers, images)` remains synchronous for
|
|
530
|
+
uncompressed assets, and for meshopt assets when you pass the decoder as
|
|
531
|
+
`decoders: { meshopt }`; the built-in meshopt decoder loads on demand in
|
|
532
|
+
`loadGLTF`, `parseGLTFAsync` and `asset.decode()`, so an app that never loads a glTF does not bundle it. Draco input directs callers to the async API.
|
|
533
|
+
Both async APIs accept `{signal}`, an optional reusable `draco` decoder with a
|
|
534
|
+
`decode` method, and an optional `ktx2` decoder with a `transcode` method. A supplied decoder stays owned by its caller. The default Draco
|
|
535
|
+
decoder requires browser module workers; server callers can supply a decoder.
|
|
536
|
+
Draco attributes and indices populate the original accessors, preserving skin and
|
|
537
|
+
morph data and leaving attributes outside the compression map on the usual path.
|
|
538
|
+
Normalized integer UVs, colors and extra channels are converted once according to
|
|
539
|
+
their accessor metadata; decoding leaves the caller's glTF document unchanged.
|
|
540
|
+
|
|
541
|
+
KTX2 transcodes are lazy, preserve every mip level, and choose BC7, ASTC, ETC2 or
|
|
542
|
+
RGBA8 from the device's enabled features. Color/emissive roles use sRGB formats;
|
|
543
|
+
data maps use linear formats. Loader-owned workers terminate after decoding,
|
|
544
|
+
including failure and abort. Retained mip bytes support device restoration without
|
|
545
|
+
another transcode. `KHR_texture_basisu.source` takes precedence over a PNG fallback.
|
|
546
|
+
The positional `parseGLTFAsync` overload decodes embedded/data-URI KTX2; use the options-object overload or `loadGLTF`
|
|
547
|
+
for external images.
|
|
548
|
+
Synchronous `parseGLTF` also accepts already decoded `GLTFImage` blueprints.
|
|
549
|
+
|
|
550
|
+
`KHR_texture_transform` supports offset, rotation, scale, and the overriding UV set
|
|
551
|
+
on all five PBR maps. UV0 and UV1 already share the fixed 80-byte vertex layout. A draw fetches only the parts of that vertex its finished shader reads, so a material with no maps
|
|
552
|
+
reads position, normal and, while `vertexColors` is on, colour. An input the shader reads only as `.xyz`, such as
|
|
553
|
+
position and normal, is fetched as three floats on every draw. Instanced draws (`createInstancedMesh`) fetch less again:
|
|
554
|
+
no instance UV row when no map reads it, and no colour when every vertex colour is white (the shader reads the
|
|
555
|
+
constant 1, the same value). Nothing to set.
|
|
556
|
+
Nonidentity transforms append affine rows to group 3 alongside any caller material
|
|
557
|
+
factors. Identity transforms and ordinary UV0 materials retain the exact original
|
|
558
|
+
shader, 400-byte frame, and groups 0/1. Normal maps derive their tangent frame from
|
|
559
|
+
transformed or secondary UVs; alpha-masked directional shadows use the same mapping.
|
|
560
|
+
Optional material maps support the same transform through `materials.install()`.
|
|
561
|
+
`textureCoordinates(info)` exposes the validated UV selection and packed affine rows;
|
|
562
|
+
caller-owned clearcoat/transmission textures accept a glTF-style `transform` option.
|
|
563
|
+
|
|
564
|
+
`KHR_animation_pointer` is accepted when required. gltf/pbr loads the pointer channels as data; `Animation` from
|
|
565
|
+
`@margoengine/animation`, given `pointerChannels` from `@margoengine/animation/pointer`, plays them on the model's live
|
|
566
|
+
values (node transforms and weights, material factors and
|
|
567
|
+
texture transforms, `model.lights`, `model.cameras`, node visibility) and lists the pointers it skips in
|
|
568
|
+
`animation.warnings`. Lights and cameras are data: hand them on after each update.
|
|
569
|
+
|
|
570
|
+
Copy the included [pointer-show.glb](test/fixtures/pointer-show.glb) into your app's public folder to run
|
|
571
|
+
this example. It contains a triangle, perspective camera and directional sun, all animated by pointers.
|
|
572
|
+
|
|
573
|
+
```ts
|
|
574
|
+
import {createStage} from 'margoengine';
|
|
575
|
+
import {applyGLTFLights, loadGLTF, viewGLTFCamera} from 'margoengine/gltf/pbr';
|
|
576
|
+
import {Animation} from 'margoengine/animation';
|
|
577
|
+
import {pointerChannels} from 'margoengine/animation/pointer';
|
|
578
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
579
|
+
const model = await loadGLTF(stage.engine, '/pointer-show.glb'); // extensionsRequired: ['KHR_animation_pointer']
|
|
580
|
+
const animation = Animation.attach(model, {pointers: pointerChannels});
|
|
581
|
+
animation.playing = false;
|
|
582
|
+
animation.seek(0.5); // writes material factors, light and camera values
|
|
583
|
+
viewGLTFCamera(model, 0); // the animated yfov
|
|
584
|
+
applyGLTFLights(model); // the animated sun; pass {clustered} for point and spot lights
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
`loadGLTF` and `parseGLTFAsync` shade a file that uses clearcoat, transmission, IOR, volume, dispersion, sheen, specular, iridescence, anisotropy, diffuse transmission, volume scatter or a bump map with the physical renderer by default: they import `extendedMaterials` from `@margoengine/gltf/extended-materials` on first need, so an app whose files never use those extensions ships none of its WGSL. Pass `{decoders: {materials: false}}` to keep the base shader (the extensions are then ignored, as glTF allows), or your own `extendedMaterials`. For synchronous parsing, pass `{materials: extendedMaterials}` as `parseGLTF`'s fifth argument. The imported metadata also stays available for explicit `@margoengine/materials` installation, whose lobes replace the physical renderer for the materials they cover. Constructed `@margoengine/materials` meshes retain their live material and UV-transform layout automatically.
|
|
588
|
+
|
|
589
|
+
`KHR_materials_dispersion` is accepted when required. Its factor is validated and
|
|
590
|
+
retained as `primitive.material.dispersion` even without a materials decoder;
|
|
591
|
+
it defaults to 0 and accepts finite non-negative values, including values above 1.
|
|
592
|
+
With `extendedMaterials`, declaring the extension reserves the physical frame even
|
|
593
|
+
at 0. Chromatic refraction is visible through `@margoengine/materials/transmission`
|
|
594
|
+
when transmission and volume thickness are positive. Dispersion alone does not
|
|
595
|
+
reserve transmission. The factor remains live, and 0 preserves the existing
|
|
596
|
+
refraction output. Native transmission's volume tint reads
|
|
597
|
+
`KHR_materials_volume.thicknessTexture` (green channel) with `thicknessFactor`; the explicit
|
|
598
|
+
`@margoengine/materials` installation route samples it for refraction too.
|
|
599
|
+
|
|
600
|
+
`loadGLTF(engine, url, {optimize: true})` runs the import step of `@margoengine/geometry/optimize` on each opaque primitive
|
|
601
|
+
as it packs: the same triangles in the order the vertex cache and early depth test read fastest, with `BLEND` primitives
|
|
602
|
+
left in the file's order. It needs `@margoengine/geometry`, takes load time, and keeps a load on the main thread. A
|
|
603
|
+
file built with `margo-convert` is already in this order, so leave it off there.
|
|
604
|
+
|
|
605
|
+
The optional `/worker` entry exposes `loadGLTFInWorker` and `parseGLTFInWorker`. Ordinary assets parse and pack in a worker. Automatic Draco/KTX2 inputs transfer their source buffers back before codec work, then decode on the GPU-owning thread; custom decoders or `fetch` keep the entire load there. The `/progressive` loader exposes `ready` and `complete`; compressed assets use the normal async loader before publishing a model, and its `textures` option streams KTX2 mip levels ("Texture mip streaming" below). `maxDownloadBytes`, `maxNodes`, allowed resource URLs and abort signals remain enforced; `maxDownloadBytes` counts the root JSON/GLB file together with its fetched and data-URI resources.
|
|
606
|
+
|
|
607
|
+
In a multi-view frame, a model draws only the nodes in the view's layers, and each view keeps its own camera uniforms
|
|
608
|
+
even when one command encoder records several views or probe faces. Buffers released mid-draw (a callback that
|
|
609
|
+
disposes the model) stay valid until the frame is submitted.
|
|
610
|
+
|
|
611
|
+
The loader passes declared vertex/index counts (up to 16,777,216 vertices a primitive, loaded as parts like any
|
|
612
|
+
other), accessor widths and the remaining decoded-data budget (4x `maxDownloadBytes`, whose default is 512 MiB) into
|
|
613
|
+
Draco; `@margoengine/decoders` outputs at most 256 MiB per decode. The default decoder rejects oversized
|
|
614
|
+
actual geometry before allocating output arrays, including topology without an
|
|
615
|
+
index accessor. It still needs to decode internal Wasm geometry before reading
|
|
616
|
+
those counts. Custom `draco.decode` hooks should honor the supplied `limits`;
|
|
617
|
+
the loader also validates returned data before constructing GPU resources.
|
|
618
|
+
|
|
619
|
+
`parsePreparedPBR(engine, document, geometry, images)` accepts a static glTF-style scene/material document and per-mesh arrays of `PreparedGeometry` (`vertices: Float32Array`, `indices: Uint32Array`). Vertices use the existing 80-byte layout: position4, normal4, tangent4, UV0+UV1, color4. Arrays are validated and retained without repacking; keep them immutable until destruction, or replace them with `model.writeGeometry(geometry, range?)`. This path has no accessors, skins or animations and is used by the separate `@margoengine/blender` loader. Existing glTF loading and animation APIs are unchanged.
|
|
620
|
+
|
|
621
|
+
`model.writeGeometry(geometry)` takes one `PreparedGeometry` per entry of `model.primitives` and swaps them in place: GPU buffers are rewritten while the new data fits and reallocated at twice their size otherwise. With `range` (`{start, count}` in vertices) only those vertices changed: vertex and index counts stay and only that range uploads (pass new array objects when positions moved, so BVH and selection caches keyed on them refresh). Nodes, materials and plugin registrations stay; static batches are retired and edited primitives cast dynamic shadows. Skinned, morphed and `shareBuffers` primitives are refused, and `createRenderer` replicas keep their original geometry. `@margoengine/materials` meshes wrap it as `mesh.setGeometry`.
|
|
622
|
+
|
|
623
|
+
Transmissive materials honour their maps on the default path too: a black half of a `transmissionTexture` hides the light behind it, and `metallicRoughnessTexture`, base colour, sheen, clearcoat and iridescence all change how much passes. That takes a second textured draw per glass surface; [docs/limits.md](../../docs/limits.md) has the measured cost.
|
|
624
|
+
|
|
625
|
+
### Sky light by default
|
|
626
|
+
|
|
627
|
+
A model in a scene with a `Sky` from `@margoengine/sky` that lights the scene (`lighting.ambient`, or `environment`) takes
|
|
628
|
+
that sky's image-based light by itself, as core meshes do: diffuse light and reflections blurred by each material's
|
|
629
|
+
roughness. It joins on its next draw and leaves when the sky goes or the model is disposed; `sky.add(model)` is no longer
|
|
630
|
+
needed. An ambient given to the model itself (`environment.add(model)`, `probes.add(model)`, or `sky.add(model)` with
|
|
631
|
+
another sky) takes the sky's place, one ambient per shader as on core meshes. `model.sceneSky = false` keeps the built-in
|
|
632
|
+
ambient (a fixed sky and ground gradient). Default true.
|
|
633
|
+
|
|
634
|
+
```ts
|
|
635
|
+
import { Engine } from '@margoengine/core';
|
|
636
|
+
import { Sky } from '@margoengine/sky';
|
|
637
|
+
import { dayPreset } from '@margoengine/sky/day-presets';
|
|
638
|
+
import { loadGLTF } from '@margoengine/gltf/pbr';
|
|
639
|
+
|
|
640
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
641
|
+
Sky.attach(engine, dayPreset('overcast'));
|
|
642
|
+
const lantern = await loadGLTF(engine, '/examples/assets/khronos/Lantern/Lantern.glb');
|
|
643
|
+
// Lit by the overcast sky from its first frame. To leave it with the built-in ambient instead:
|
|
644
|
+
// lantern.sceneSky = false;
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
`KHR_materials_specular` and `KHR_materials_ior` reach every light: direct, `Clustered` local lights, `EnvironmentLighting`, `LightProbes` and sky ambient. A lighting hook reads them as `s.f0` and `s.sw`; on shaders without those fields `lightPBR` writes 0.04 and 1 in their place.
|
|
648
|
+
|
|
649
|
+
Attach animation with the separate animation package. Register this model with `ssao.add(model)` to include its mapped normals and ambient lighting in SSAO. Neither extension is imported by this package. Disposal and device restoration retain CPU asset blueprints.
|
|
650
|
+
|
|
651
|
+
Optional consumers use one weak triangle-source registry across separately bundled packages. Inspector and line helpers use bind-pose positions/normals with current transforms; static spatial queries and shadow mesh registrations also retain loader-owned primitives. `mesh.geometry` remains null, so core does not receive a second drawable. Physics fits static primitive nodes or a geometry-free model root's descendants without changing the hierarchy; skinned or morphed meshes require explicit colliders. glTF export retains supported skin/morph attributes. Disposal clears registry entries, and reused mesh slots cannot inherit them.
|
|
652
|
+
|
|
653
|
+
`model.raw` borrows one live GPU record per primitive (`vertex`, `index`, `count`,
|
|
654
|
+
`stride: 80`, node and alpha metadata), including current deformation. `bounds`
|
|
655
|
+
scans bind-pose CPU positions through current node matrices. Fit these bounds
|
|
656
|
+
through `camera.fitToBoundingBox`; the frozen stage's `fit(meshes)` and internal
|
|
657
|
+
raw adapter continue to support core geometry only. Active deformation requires
|
|
658
|
+
the asynchronous pose snapshot for accurate CPU raycasts.
|
|
659
|
+
|
|
660
|
+
#### Drawing a model into your own render pass (`createRenderer`)
|
|
661
|
+
|
|
662
|
+
`model.createRenderer(device)` returns a `PBRDeviceRenderer` that appends the model's PBR draws to a render pass you
|
|
663
|
+
already opened (a stereo eye, another device, your own target). `draw(context, pass, view, options)` returns the pass
|
|
664
|
+
that is open afterwards; keep recording on it. Glass (`KHR_materials_transmission`) on a display-encoded target (any
|
|
665
|
+
format but `rgba16float`) needs the light behind each surface in linear values, and only you can end and reopen your
|
|
666
|
+
pass, so lend it `options.snapshot`: end the pass, write the colour drawn so far into `target` (same size and format,
|
|
667
|
+
single-sample; resolve a multisampled pass first) and return the pass reopened with `loadOp: 'load'`. Without it glass
|
|
668
|
+
multiplies and adds in the stored values, exact only on an `rgba16float` target; a bright highlight over a bright
|
|
669
|
+
background then comes out too bright (KB2281: 197 of 255 against 143). Default: unset.
|
|
670
|
+
|
|
671
|
+
```ts
|
|
672
|
+
import {Engine} from 'margoengine/core';
|
|
673
|
+
import {parseGLTF, type GLTFDocument} from 'margoengine/gltf/pbr';
|
|
674
|
+
import {extendedMaterials} from 'margoengine/gltf/extended-materials';
|
|
675
|
+
|
|
676
|
+
const engine = await Engine.create(document.querySelector('canvas')!, {
|
|
677
|
+
camera: {position: [0, 0, 1], target: [0, 0, 0]},
|
|
678
|
+
});
|
|
679
|
+
const data = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0]);
|
|
680
|
+
const doc: GLTFDocument = {
|
|
681
|
+
asset: {version: '2.0'},
|
|
682
|
+
extensionsUsed: ['KHR_materials_transmission'],
|
|
683
|
+
buffers: [{byteLength: data.byteLength}],
|
|
684
|
+
bufferViews: [{buffer: 0, byteLength: 36}],
|
|
685
|
+
accessors: [{bufferView: 0, componentType: 5126, count: 3, type: 'VEC3'}],
|
|
686
|
+
materials: [{emissiveFactor: [0.1, 0.15, 0.2], extensions: {KHR_materials_transmission: {transmissionFactor: 1}}}],
|
|
687
|
+
meshes: [{primitives: [{attributes: {POSITION: 0}, material: 0}]}],
|
|
688
|
+
nodes: [{mesh: 0}], scenes: [{nodes: [0]}], scene: 0,
|
|
689
|
+
};
|
|
690
|
+
const model = parseGLTF(engine, doc, [new Uint8Array(data.buffer)], [], {materials: extendedMaterials});
|
|
691
|
+
engine.render();
|
|
692
|
+
|
|
693
|
+
const device = engine.gpu!, format: GPUTextureFormat = 'rgba8unorm', size: [number, number] = [256, 256];
|
|
694
|
+
const color = device.createTexture({size, format,
|
|
695
|
+
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC | GPUTextureUsage.TEXTURE_BINDING});
|
|
696
|
+
const depth = device.createTexture({size, format: 'depth32float', usage: GPUTextureUsage.RENDER_ATTACHMENT});
|
|
697
|
+
const renderer = model.createRenderer(device);
|
|
698
|
+
const encoder = device.createCommandEncoder();
|
|
699
|
+
const context = {
|
|
700
|
+
backend: 'webgpu' as const, device, encoder, format, width: size[0], height: size[1], camera: engine.camera,
|
|
701
|
+
color: color.createView(), depth: depth.createView(), bindings: [], shader: '', indirect: false, delta: 0,
|
|
702
|
+
descriptor: {layout: 'auto', vertex: {module: device.createShaderModule({code: ''})},
|
|
703
|
+
depthStencil: {format: 'depth32float', depthWriteEnabled: true, depthCompare: 'less-equal'},
|
|
704
|
+
multisample: {count: 1}} as GPURenderPipelineDescriptor,
|
|
705
|
+
draw() {},
|
|
706
|
+
};
|
|
707
|
+
const open = (first: boolean) => encoder.beginRenderPass({
|
|
708
|
+
colorAttachments: [{view: context.color, loadOp: first ? 'clear' : 'load', clearValue: [0.5, 0.5, 0.5, 1],
|
|
709
|
+
storeOp: 'store'}],
|
|
710
|
+
depthStencilAttachment: {view: context.depth, depthLoadOp: first ? 'clear' : 'load', depthClearValue: 1,
|
|
711
|
+
depthStoreOp: 'store'},
|
|
712
|
+
});
|
|
713
|
+
// The view matrix of a camera at z = 1 looking at the origin.
|
|
714
|
+
const view = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -1, 1];
|
|
715
|
+
renderer.prepare(context);
|
|
716
|
+
const pass = renderer.draw(context, open(true), view, {
|
|
717
|
+
snapshot(current, target) {
|
|
718
|
+
current.end();
|
|
719
|
+
encoder.copyTextureToTexture({texture: color}, {texture: target}, size);
|
|
720
|
+
return open(false);
|
|
721
|
+
},
|
|
722
|
+
});
|
|
723
|
+
pass.end();
|
|
724
|
+
device.queue.submit([encoder.finish()]);
|
|
725
|
+
renderer.dispose();
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
#### Mixed core/PBR scene helpers
|
|
729
|
+
|
|
730
|
+
Import the optional `@margoengine/gltf/scene` entry for camera fitting and
|
|
731
|
+
raw GPU records across core geometry and loaded glTF/FBX models:
|
|
732
|
+
|
|
733
|
+
```ts
|
|
734
|
+
import {createStage} from 'margoengine';
|
|
735
|
+
import {box} from 'margoengine/core';
|
|
736
|
+
import {loadGLTF, type MaterialExtension} from 'margoengine/gltf/pbr';
|
|
737
|
+
import {getSceneBounds, fitScene, gatherSceneBuffers} from 'margoengine/gltf/scene';
|
|
738
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
739
|
+
const model = await loadGLTF(stage.engine, '/SciFiHelmet.glb');
|
|
740
|
+
const coreMesh = stage.engine.createMesh().setGeometry(box());
|
|
741
|
+
const roots = [model.root, coreMesh];
|
|
742
|
+
fitScene(stage.engine, roots, {duration: 0.3, padding: 1.1});
|
|
743
|
+
const bounds = getSceneBounds(stage.engine, roots);
|
|
744
|
+
const buffers = gatherSceneBuffers(stage.engine, roots);
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
Each selected root includes its descendants. Overlapping selections visit each
|
|
748
|
+
node once. Hidden meshes and meshes under hidden ancestors are excluded by
|
|
749
|
+
default; `{visibleOnly: false}` includes them. Frustum culling does not affect
|
|
750
|
+
selection. Bounds scan actual CPU positions under current world transforms;
|
|
751
|
+
skinned/morphed positions remain the bind pose. Empty bounds throw `No geometry`.
|
|
752
|
+
`fitScene` returns the bounds used and accepts `aspect`, `duration`, and `padding`;
|
|
753
|
+
aspect defaults to the displayed canvas dimensions, falling back to its size.
|
|
754
|
+
|
|
755
|
+
`gatherSceneBuffers` returns one record per core node or PBR primitive, preserving
|
|
756
|
+
distinct nodes/primitives even when they share GPU buffers. Records include
|
|
757
|
+
`kind`, `node`, a borrowed world `matrix`, `vertex`, `index`, index `count`, and
|
|
758
|
+
`indexFormat: 'uint32'`. Core records have `stride: 24`, `geometry`, and the shared
|
|
759
|
+
batch `instance` buffer. That instance buffer reflects the last render and does
|
|
760
|
+
not provide a stable instance offset for an individual node. PBR records have
|
|
761
|
+
`stride: 80`, primitive identity, and alpha/UV metadata.
|
|
762
|
+
|
|
763
|
+
These records borrow existing resources: do not destroy their buffers or modify
|
|
764
|
+
their matrices. Requery after animation or device restoration to obtain current
|
|
765
|
+
buffers; gathering does not encode animation, upload geometry, or read back the
|
|
766
|
+
GPU. An empty selection returns `[]`; WebGL2 returns `null`. Foreign/disposed
|
|
767
|
+
roots and unavailable GPU resources report errors. The frozen `Stage.fit` and
|
|
768
|
+
internal facade adapter retain their original contracts.
|
|
769
|
+
|
|
770
|
+
`model.lods` lists a file's `MSFT_lod` objects (`node`, `levels`, `screenCoverage`): the level nodes load though no scene names them, under the first level's parent, hidden, until `LOD.fromModel` from `margoengine/lod` drives them.
|
|
771
|
+
|
|
772
|
+
Register with `shadows.add(model)` and `clustered.add(model)` for optional directional shadows and local PBR lights, including the current skinned vertex buffer. `addLighting()` accepts an optional shader/binding hook without importing these packages. `shadowPrimitives` exposes current opaque/masked GPU geometry to depth consumers; blended materials are omitted. A material's `displacement` (materials' `displacementMap`: its feature uniform, view and sampler) is passed on with each of its primitives so depth passes displace them as the beauty pass does (`shared/displacement.js`).
|
|
773
|
+
|
|
774
|
+
`primitive.material.shading` accepts one `LightingEffect` for that material's
|
|
775
|
+
surface shader and group 2 bindings. Constructed materials use it so geometry
|
|
776
|
+
groups can share a model while retaining separate textures and shading. It
|
|
777
|
+
composes before `addLighting()` effects and applies to beauty, g-buffer,
|
|
778
|
+
ambient and capture draws; its resources must remain in the selected entry
|
|
779
|
+
point's static resource interface. `extension.lighting: false` suppresses
|
|
780
|
+
scene lighting while retaining the material's own shading. Callbacks own their
|
|
781
|
+
resources and must recreate them after device restoration. Cross-device
|
|
782
|
+
renderers reject local shading until the caller recreates it for that device;
|
|
783
|
+
same-device renderers can reuse it. Its optional `lit(code)` rewrites the shader
|
|
784
|
+
after the `addLighting()` effects are composed in (materials' Lambert and Phong
|
|
785
|
+
put their own BRDF in clustered's light loop there); returning `code` changes
|
|
786
|
+
nothing.
|
|
787
|
+
|
|
788
|
+
`model.selectVariant(index)` picks a `KHR_materials_variants` look, and `model.selectedVariant` reads it back (`undefined` for the file's default). `model.ownedMeshes` is every mesh the model built, with its root and nodes; a mesh you parented to a node is yours and is not in it.
|
|
789
|
+
|
|
790
|
+
#### Primitives of any size (scans)
|
|
791
|
+
|
|
792
|
+
A primitive with more vertices than `maxPartVertices` (default 262,144: 20 MiB of 80-byte vertices, inside every
|
|
793
|
+
device's storage binding, the WebGL2 layer's included) loads as several parts of its node, up to 16,777,216 vertices a
|
|
794
|
+
primitive. Triangles go in Morton order of their centres, so each part is a compact piece of the surface with tight
|
|
795
|
+
bounds, and are cut greedily: shared vertices stay shared inside a part, and only those on a cut are copied (0.37% on
|
|
796
|
+
a 1,001,000-vertex grid). Blended primitives keep the file's triangle order. Each part is an ordinary `PBRPrimitive`
|
|
797
|
+
with the same node, material and `definition`, and `part` says which it is; drawing, frustum culling, picking,
|
|
798
|
+
`@margoengine/exporters` (one primitive per part, same material) and `@margoengine/lod` levels (simplified as one
|
|
799
|
+
surface, then split again) work part by part. Skinned and morphed primitives split the same way (strand hair on a
|
|
800
|
+
rigged character, a dense scanned body): skinning and morphing are per vertex (glTF 2.0 sections 3.7.3 and 3.7.2.2), so
|
|
801
|
+
each part reads `JOINTS_n`, `WEIGHTS_n` and its morph target deltas at the file vertices `part.vertexMap` names, keeps
|
|
802
|
+
the node's skin, morph weights and material, and `@margoengine/animation` deforms it exactly as it deforms the same mesh
|
|
803
|
+
split by hand into one primitive per part, and as the whole primitive at those vertices (`npm run
|
|
804
|
+
test:gpu:skinned-parts`, natively and on the WebGL2 layer). Code that reads a definition's per-vertex accessors itself
|
|
805
|
+
reads them through `part.vertexMap`, as the example below shows.
|
|
806
|
+
|
|
807
|
+
`loadGLTFProgressive` spends `frameBudget` milliseconds a frame on uploads, so a slower machine finishes fewer steps a frame (KB-FILM-CLOCK1). For a film pass `maxJobs`, a count of upload steps a frame that replaces the budget (1 or more, `Infinity` for every waiting step), and `clock` for a simulation clock; the finished model after `await load.complete` is the same whatever the budget. `loadGLTFProgressive` takes `maxPartVertices` too and streams a split primitive part by part: the worker packs one part
|
|
808
|
+
at a time, the first replaces the placeholder box and each later one is drawn as it arrives, so a scan fills in while it
|
|
809
|
+
loads; once `complete` resolves the model equals a `loadGLTF` of the same file. Packed geometry still counts toward the
|
|
810
|
+
decoded budget, 4x `maxDownloadBytes`. A 9,999,392-triangle height field in one primitive (a 240 MB GLB) loads with no
|
|
811
|
+
options as 20 parts and draws exactly what the same field pre-split at export into the same 20 parts draws, natively
|
|
812
|
+
and on the WebGL2 layer; close up, `CulledModels` draws 9 parts and 4,683,190 triangles (`npm run test:gpu:parts`).
|
|
813
|
+
`maxPartVertices` takes 1,024 to 1,048,576: 65,536 draws 12 parts and 1,550,309 triangles in that view, 1,048,576
|
|
814
|
+
draws 4 parts and 8,363,067.
|
|
815
|
+
|
|
816
|
+
Every frame each primitive drawn by the standard vertex stage is tested against the camera frustum on the CPU by its
|
|
817
|
+
bounding sphere (one test per primitive, the sphere measured once per vertex array), so a part out of view costs no
|
|
818
|
+
draw with no culling package attached. Instanced, skinned, morphed or deformed primitives, and materials with their own
|
|
819
|
+
shader or a displacement map, are not tested, as their vertices may move past the stored ones; `CulledModels` culls
|
|
820
|
+
those on the GPU, with its `padding` for displaced ones. Shadow casters, picking and export still see every part.
|
|
821
|
+
|
|
822
|
+
```ts
|
|
823
|
+
import {parseGLTFAsync} from 'margoengine/gltf/pbr';
|
|
824
|
+
import {Engine} from 'margoengine/core';
|
|
825
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
826
|
+
// A 100 x 100 vertex grid, two triangles a cell, as one glTF primitive.
|
|
827
|
+
const positions = new Float32Array(100 * 100 * 3), indices = new Uint32Array(99 * 99 * 6);
|
|
828
|
+
for (let i = 0; i < 100 * 100; i++) positions.set([(i % 100) / 50 - 1, Math.floor(i / 100) / 50 - 1, 0], i * 3);
|
|
829
|
+
for (let y = 0, o = 0; y < 99; y++)
|
|
830
|
+
for (let x = 0; x < 99; x++, o += 6) {
|
|
831
|
+
const i = y * 100 + x;
|
|
832
|
+
indices.set([i, i + 1, i + 100, i + 1, i + 101, i + 100], o);
|
|
833
|
+
}
|
|
834
|
+
const bin = new Uint8Array(positions.byteLength + indices.byteLength);
|
|
835
|
+
bin.set(new Uint8Array(positions.buffer));
|
|
836
|
+
bin.set(new Uint8Array(indices.buffer), positions.byteLength);
|
|
837
|
+
const doc = {
|
|
838
|
+
asset: {version: '2.0'}, scene: 0, scenes: [{nodes: [0]}], nodes: [{mesh: 0}],
|
|
839
|
+
meshes: [{primitives: [{attributes: {POSITION: 0}, indices: 1}]}],
|
|
840
|
+
buffers: [{byteLength: bin.byteLength}],
|
|
841
|
+
bufferViews: [
|
|
842
|
+
{buffer: 0, byteLength: positions.byteLength},
|
|
843
|
+
{buffer: 0, byteOffset: positions.byteLength, byteLength: indices.byteLength},
|
|
844
|
+
],
|
|
845
|
+
accessors: [
|
|
846
|
+
{bufferView: 0, componentType: 5126, type: 'VEC3', count: 10000, min: [-1, -1, 0], max: [0.98, 0.98, 0]},
|
|
847
|
+
{bufferView: 1, componentType: 5125, type: 'SCALAR', count: indices.length},
|
|
848
|
+
],
|
|
849
|
+
};
|
|
850
|
+
// 10,000 vertices in parts of at most 4,096 (the default 262,144 keeps this one whole).
|
|
851
|
+
const model = await parseGLTFAsync(engine, doc, [bin.buffer], [], {maxPartVertices: 4096});
|
|
852
|
+
for (const p of model.primitives) console.log(p.part?.index, p.part?.count, p.vertices.length / 20);
|
|
853
|
+
// A part's vertex k is the file's vertex part.vertexMap[k]: read JOINTS_n, WEIGHTS_n or morph deltas there.
|
|
854
|
+
const positions0 = model.asset.accessor(doc.meshes[0].primitives[0].attributes.POSITION, 'VEC3'),
|
|
855
|
+
last = model.primitives.at(-1)!,
|
|
856
|
+
file = last.part!.vertexMap[0];
|
|
857
|
+
console.log(positions0.subarray(file * 3, file * 3 + 3), last.vertices.subarray(0, 3));
|
|
858
|
+
```
|
|
859
|
+
|
|
860
|
+
#### More than two UV sets
|
|
861
|
+
|
|
862
|
+
A texture may read `TEXCOORD_0` to `TEXCOORD_3`, as Blender writes them for a material on its third or fourth UV map. Only a primitive whose material (or a `KHR_materials_variants` mapping) reads set 2 or 3 pays: it gets a second vertex buffer, `primitive.uvs`, four floats a vertex, and its own shader. A file that merely carries those attributes loads as before. The 80-byte vertex stays as it is.
|
|
863
|
+
|
|
864
|
+
```ts
|
|
865
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
866
|
+
import {Engine} from 'margoengine/core';
|
|
867
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
868
|
+
const model = await loadGLTF(engine, '/models/FourUV.glb');
|
|
869
|
+
// TEXCOORD_2 then TEXCOORD_3 of each vertex, present only when a material reads either.
|
|
870
|
+
console.log(model.primitives[0].uvs);
|
|
871
|
+
```
|
|
872
|
+
|
|
873
|
+
`loadGLTFInWorker`, `loadGLTFProgressive`, Draco, `EXT_mesh_gpu_instancing`, `@margoengine/lod` levels and far meshes, and `@margoengine/exporters` all keep the later sets. `writeGeometry` keeps them too: a write that changes the vertex count passes its own `uvs`. Such primitives stay out of static batches. A `MASK` or `BLEND` base map on set 2 or 3 casts and picks uncut, as the depth passes read the first two sets only, and a `.margo` file holds two sets. A fifth set is refused by name.
|
|
874
|
+
|
|
875
|
+
#### Rough diffuse surfaces (`KHR_materials_diffuse_roughness`, draft)
|
|
876
|
+
|
|
877
|
+
`loadGLTF` and `parseGLTFAsync` read `KHR_materials_diffuse_roughness` by themselves through `@margoengine/gltf/extended-materials`, so sandstone, plaster, clay and cloth look flat and back-scattering. `diffuseRoughnessFactor` (default `0`, Lambert, from 0 to 1) times the red channel of `diffuseRoughnessTexture` (linear, with its UV set and `KHR_texture_transform`) roughens the diffuse lobe; specular roughness is separate. A material without the extension, or with factor 0, keeps its shader and buffers. As the extension requires, unlit and specular-glossiness materials ignore it.
|
|
878
|
+
|
|
879
|
+
```ts
|
|
880
|
+
import {parseGLTFAsync} from 'margoengine/gltf/pbr';
|
|
881
|
+
import {Engine} from 'margoengine/core';
|
|
882
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
883
|
+
// One clay triangle.
|
|
884
|
+
const positions = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0]);
|
|
885
|
+
const model = await parseGLTFAsync(engine, {
|
|
886
|
+
asset: {version: '2.0'},
|
|
887
|
+
extensionsUsed: ['KHR_materials_diffuse_roughness'],
|
|
888
|
+
buffers: [{byteLength: 36}],
|
|
889
|
+
bufferViews: [{buffer: 0, byteLength: 36}],
|
|
890
|
+
accessors: [{bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [-1, -1, 0], max: [1, 1, 0]}],
|
|
891
|
+
materials: [{
|
|
892
|
+
pbrMetallicRoughness: {baseColorFactor: [0.6, 0.3, 0.2, 1], metallicFactor: 0},
|
|
893
|
+
extensions: {KHR_materials_diffuse_roughness: {diffuseRoughnessFactor: 0.9}},
|
|
894
|
+
}],
|
|
895
|
+
meshes: [{primitives: [{attributes: {POSITION: 0}, material: 0}]}],
|
|
896
|
+
nodes: [{mesh: 0}],
|
|
897
|
+
}, [positions.buffer]);
|
|
898
|
+
console.log(model.primitives[0].material.extended?.diffuseRoughness); // true
|
|
899
|
+
engine.start();
|
|
900
|
+
```
|
|
901
|
+
|
|
902
|
+
The lobe is the energy-preserving Oren-Nayar (EON) model that OpenPBR names (Portsmouth, Kutz and Hill, "EON: A practical energy-preserving rough diffuse BRDF", JCGT 14(1), 2025, <https://arxiv.org/abs/2410.18026>): a white surface reflects all light at every roughness, and a coloured one saturates slightly as it roughens. The sun and local lights shade it through the same direct term, the back side of `KHR_materials_diffuse_transmission` included. The ambient, light-probe and image-based terms take the lobe's directional albedo at the view angle in place of the base colour (exact under uniform light), which costs two more evaluations of the ambient hook per pixel. Transmission, sheen and clearcoat layer over it as over Lambert. Real-GPU check on both backends: `npm run test:gpu:diffuse-roughness -w @margoengine/gltf`.
|
|
903
|
+
|
|
904
|
+
#### Scattering in glTF volumes (`KHR_materials_volume_scatter`, draft)
|
|
905
|
+
|
|
906
|
+
A material with `KHR_materials_diffuse_transmission` glows from behind under shadows too: its lighting hook's `direct(direct, normal)` gets the side facing the light, so the surface does not shadow its own back. Its shadow casters carry `transmits`, the factor times the colour factor, for `transmission` of `@margoengine/shadows/transmission`.
|
|
907
|
+
|
|
908
|
+
`loadGLTF` and `parseGLTFAsync` read `KHR_materials_volume_scatter` by themselves through `@margoengine/gltf/extended-materials`, so milky glass, jade and wax look solid where the light has far to go and clear where it has not. It needs `KHR_materials_volume` with a thickness and an `attenuationDistance`, and light that enters: `KHR_materials_transmission` or `KHR_materials_diffuse_transmission`. Otherwise it does nothing, as the spec has it. `multiscatterColorFactor` (default `[0, 0, 0]`) times `multiscatterColorTexture` (sRGB) is the multi-scatter colour; `scatterAnisotropy` (default `0`, from -1 to 1) moves scattering forward or back.
|
|
909
|
+
|
|
910
|
+
```ts
|
|
911
|
+
import {parseGLTF} from 'margoengine/gltf/pbr';
|
|
912
|
+
import {extendedMaterials} from 'margoengine/gltf/extended-materials';
|
|
913
|
+
import {Engine} from 'margoengine/core';
|
|
914
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
915
|
+
const doc = await (await fetch('/model.gltf')).json();
|
|
916
|
+
const buffers = [new Uint8Array(await (await fetch('/model.bin')).arrayBuffer())];
|
|
917
|
+
// The default loaders need none of this; the synchronous parser takes the decoder by hand.
|
|
918
|
+
const model = parseGLTF(engine, doc, buffers, [], {materials: extendedMaterials});
|
|
919
|
+
console.log(model.primitives[0].material.extended?.scatter);
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
This is a rasterizer's reading, with no light walked through the medium. Over the depth x, which is `thicknessFactor` times the green channel of `thicknessTexture` along the surface normal, a share 1 - exp(-sigma_s (1 - g) x) of the entering light scatters and comes back as a diffuse lobe of the multi-scatter colour, with sigma_s from the spec's albedo mapping. A dense medium therefore matches a diffuse surface of that colour, the comparison the spec itself draws. Light does not spread sideways under the surface, so edges stay sharp. Specular transmission keeps its Beer-Lambert term, which already counts what scattered out of the straight path. Diffuse transmission had none, so it is scaled by what crosses the depth. For the view through the glass to refract, and for `KHR_materials_volume` thickness maps on that view, use `install(model)` from `@margoengine/materials`, which reads this extension too.
|
|
923
|
+
|
|
924
|
+
The text read is the draft of Khronos glTF pull request 2453 (Status "Draft") as of 2026-11-06: it can still change, and pull request 2579 proposes `KHR_materials_scatter` in its place. The multi-scatter colour and thickness maps count toward the eight extension textures of an extended material. Phase function detail beyond the 1 - g scale is not drawn.
|
|
925
|
+
|
|
926
|
+
#### Bump maps in glTF (`EXT_materials_bump`, draft)
|
|
927
|
+
|
|
928
|
+
`loadGLTF` and `parseGLTFAsync` read `EXT_materials_bump` by themselves through `@margoengine/gltf/extended-materials`: the red channel of `bumpTexture`, read as linear data, times `bumpFactor` is a height, and the surface normal becomes `normalize(n - grad d)`. It tilts the normal a normal map has already tilted, so a file can hold large forms in the normal map and fine detail in the bump map. `heightSpace: 'object'` scales the height with the node, along the surface normal, so uneven scale works too; `'world'` keeps it in metres. Without `heightSpace` the draft leaves the strength to the renderer: Margo reads it as `'world'`.
|
|
929
|
+
|
|
930
|
+
```ts
|
|
931
|
+
import {parseGLTF} from 'margoengine/gltf/pbr';
|
|
932
|
+
import {extendedMaterials} from 'margoengine/gltf/extended-materials';
|
|
933
|
+
import {Engine} from 'margoengine/core';
|
|
934
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
935
|
+
const doc = await (await fetch('/model.gltf')).json();
|
|
936
|
+
const buffers = [new Uint8Array(await (await fetch('/model.bin')).arrayBuffer())];
|
|
937
|
+
// The default loaders need none of this; the synchronous parser takes the decoder by hand.
|
|
938
|
+
const model = parseGLTF(engine, doc, buffers, [], {materials: extendedMaterials});
|
|
939
|
+
console.log(model.primitives[0].material.extended?.bump);
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
This follows the draft of Khronos glTF pull request 2339 as it stood on 2026-11-04, Status "Draft": it can still change. The height has one row in the extended uniform and the map is one of the eight extension textures of an extended material, so a ninth loses its bump.
|
|
943
|
+
|
|
944
|
+
#### Gaussian splats in glTF (`/splats`)
|
|
945
|
+
|
|
946
|
+
A file with `KHR_gaussian_splatting` primitives loads through plain `loadGLTF` or `parseGLTFAsync`: the meshes draw as usual, and the splats go to `@margoengine/splats`, so a captured scene and modelled objects share one file, one loader and one depth buffer. Nothing to pass: `@margoengine/gltf/splats` and `@margoengine/splats` load only for a file that holds splats, and the worker loaders read such a file on the page's thread. `@margoengine/splats` is an optional peer dependency; a splat file without it stops with an error that names it.
|
|
947
|
+
|
|
948
|
+
```ts
|
|
949
|
+
import {createStage} from 'margoengine';
|
|
950
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
951
|
+
import {type MaterialExtension} from 'margoengine/gltf/pbr';
|
|
952
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
953
|
+
const model = await loadGLTF(stage.engine, '/capture.glb', {maxDownloadBytes: 2 ** 28});
|
|
954
|
+
const b = model.bounds; // takes in the splat centres
|
|
955
|
+
stage.engine.camera.fitToBoundingBox([b[0], b[1], b[2]], [b[3], b[4], b[5]]);
|
|
956
|
+
console.log(model.splats.map(({cloud}) => cloud.count));
|
|
957
|
+
// model.dispose() disposes the clouds too.
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
Read against the extension's README (Complete, Ratified by the Khronos Group, as of 2026-11-06) and the draft `KHR_gaussian_splatting_compression_spz_2` (Draft, pull request 2531, as of the same day). Every attribute type of the `ellipse` kernel reads, with spherical harmonics up to degree 3, both colour spaces (`srgb_rec709_display`, `lin_rec709_display`), and the draft's SPZ payload through `parseSpz`. A file written against the draft may leave `kernel` and `colorSpace` out; they then take `ellipse` and `srgb_rec709_display`. A file that breaks the extension's rules, such as a band of harmonics with a coefficient missing, is refused with the fault named. An unknown kernel or colour space is refused too.
|
|
961
|
+
|
|
962
|
+
- `model.splats` holds `{cloud, bounds}` per cloud. Each primitive is placed by its node's world matrix (centres, shapes and harmonics), then the file's primitives merge into one cloud, so they sort together. Splats past 3,000,000 start another cloud.
|
|
963
|
+
- `{decoders: {splats: false}}` keeps the extension's fallback: the primitive draws as plain points, or a file that requires the extension is refused. Synchronous `parseGLTF` does the same.
|
|
964
|
+
- `readGaussianSplats(asset, primitive, {signal})` from `@margoengine/gltf/splats` returns one primitive's `SplatData` in local space with no GPU, for `cropSplats` and the other `@margoengine/splats/data` tools.
|
|
965
|
+
|
|
966
|
+
Limits are in [docs/limits.md](../../docs/limits.md): the clouds do not follow later node moves or visibility changes.
|
|
967
|
+
|
|
968
|
+
#### IES fixtures and image-based lights in glTF (`/lights`)
|
|
969
|
+
|
|
970
|
+
`EXT_lights_ies` puts measured light fixtures on a file's nodes and `EXT_lights_image_based` gives a scene its environment. Every loader reads a file that uses them, even as required extensions, and keeps them as data; `applyGLTFLightExtensions` turns them into lights, loading `@margoengine/clustered` and `@margoengine/environment` only when the file has that light.
|
|
971
|
+
|
|
972
|
+
```ts
|
|
973
|
+
import {createStage} from 'margoengine';
|
|
974
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
975
|
+
import {applyGLTFLightExtensions} from 'margoengine/gltf/lights';
|
|
976
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
977
|
+
const model = await loadGLTF(stage.engine, '/lobby.gltf');
|
|
978
|
+
const lights = await applyGLTFLightExtensions(model, {exposure: 0.01, background: true});
|
|
979
|
+
console.log(lights.iesLights.map(({profile}) => profile.peak), lights.imageLight?.intensity);
|
|
980
|
+
// lights.dispose() removes all of it.
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
| Option | Default | Meaning |
|
|
984
|
+
| --- | --- | --- |
|
|
985
|
+
| `exposure` | `1` | Scales every fixture's candela: IES files are in real candela, which is far brighter than a scene's sun of 1. |
|
|
986
|
+
| `background` | `false` | Draws the image-based light's cube behind the scene. |
|
|
987
|
+
| `clustered` | one attached here | The `Clustered` to add to; the file's `KHR_lights_punctual` point and spot lights join the same list. |
|
|
988
|
+
| `scene` | the file's `scene`, else 0 | The scene whose image-based light to use. |
|
|
989
|
+
| `baseURL`, `fetch`, `signal` | where `loadGLTF` read the file, `globalThis.fetch`, none | How `.ies` and image files are read. |
|
|
990
|
+
|
|
991
|
+
Read against the two extensions' READMEs on the Khronos glTF repository as of 2026-11-06: `EXT_lights_ies` (Vendor extension, status Complete) and `EXT_lights_image_based` (Multi-Vendor extension). Neither is a draft.
|
|
992
|
+
|
|
993
|
+
- A fixture is a clustered point light with its profile resampled for its node, so it can aim anywhere, uplights included. The beam runs down the node's -Z. `multiplier` and `color` scale it as the extension says; `color` clamps to 0 to 1.
|
|
994
|
+
- `.ies` files read through `parseIES`: types B and C, as the extension requires. Type A, which it leaves optional, is refused.
|
|
995
|
+
- A cube face reads as the sRGB decode of rgb / alpha with its rows swapped, which is how the one real file reads: projected onto spherical harmonics, only that reading gives every l = 1 and l = 2 coefficient the file states its sign (the extension's "flipped about its vertical axis" would get six or more wrong). `Environment` prefilters its own mips from mip 0, so the file's lower mips are not read, and its own irradiance comes from the same cube: `irradianceCoefficients` stays in `lights.imageLight` as data.
|
|
996
|
+
- `gltfIESLights(model)` and `gltfImageLight(model)` return the data without a GPU; `orientIES`, `placeIESLights` (the fixtures and aimed profiles for a list of lights, given each node's world matrix) and `rotateCube` are the steps between. Fixtures share an aimed profile only when they use the same parsed profile and point the same way (two unnamed profiles of one LM-63 format once shared the first one's beam).
|
|
997
|
+
|
|
998
|
+
Limits are in [docs/limits.md](../../docs/limits.md): lights stay where their nodes were when applied, and at most 16 fixtures differ in profile or aim.
|
|
999
|
+
|
|
1000
|
+
#### Rigid bodies in glTF (`/physics`, draft)
|
|
1001
|
+
|
|
1002
|
+
`KHR_physics_rigid_bodies` carries colliders, mass, joints and trigger volumes on a file's nodes, and `KHR_implicit_shapes` its boxes, spheres, cylinders, capsules and planes. Every loader reads a file that uses them, even as required extensions, and keeps them as data; `applyGLTFPhysics` builds them in `@margoengine/physics`, which it loads on first use, so authored physics survives export.
|
|
1003
|
+
|
|
1004
|
+
```ts
|
|
1005
|
+
import {createStage} from 'margoengine';
|
|
1006
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
1007
|
+
import {applyGLTFPhysics} from 'margoengine/gltf/physics';
|
|
1008
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
1009
|
+
const model = await loadGLTF(stage.engine, '/door.gltf');
|
|
1010
|
+
const world = await applyGLTFPhysics(model);
|
|
1011
|
+
world.onTrigger(({entered, nodeIndex, motionNodeIndex}) => console.log(entered, nodeIndex, motionNodeIndex));
|
|
1012
|
+
console.log(world.bodies.size, world.joints.size, world.notes);
|
|
1013
|
+
// world.dispose() removes all of it.
|
|
1014
|
+
```
|
|
1015
|
+
|
|
1016
|
+
| Option | Default | Meaning |
|
|
1017
|
+
| --- | --- | --- |
|
|
1018
|
+
| `physics` | one attached here, after `Physics.load()` | The `Physics` world to add to. |
|
|
1019
|
+
|
|
1020
|
+
Read against pull request 2424 (`KHR_physics_rigid_bodies`, status Draft) and pull request 2370 (`KHR_implicit_shapes`, status Release Candidate) on the Khronos glTF repository as of 2026-11-06. Both can still change.
|
|
1021
|
+
|
|
1022
|
+
- A node with a `motion` is a body that moves it, with the colliders of its descendants on it; a descendant with its own `motion` is its own body. A collider with no `motion` above it is fixed. A `mass` or `inertiaDiagonal` of 0 is infinite, as the draft says, and values the file leaves out come from the colliders.
|
|
1023
|
+
- A node the file animates is kinematic and follows its animation, its scale included. `KHR_animation_pointer` channels on joint drives play on the world's clock from when `applyGLTFPhysics` ran, looping.
|
|
1024
|
+
- A joint is a `generic` joint of `@margoengine/physics` between the two attachment frames. Limits and drives are measured from the joint node to `connectedNode`, so a drive with a target of 0.7 puts the connected node at +0.7 in the joint node's frame. A body on a joint with a drive never sleeps, because a slow body would stop short of its target.
|
|
1025
|
+
- Collision filters compare whole filters pair by pair, each side having to let the other in.
|
|
1026
|
+
- The world it makes joins the model's scene, so a model in a second scene gets its world there whichever scene is active when the solver has loaded; pass `physics` to add to a world of your own.
|
|
1027
|
+
- `geometry.node` reads that node's mesh and its children's, and `geometry.mesh`, which the extension's own sample files write in place of `node`, reads that mesh.
|
|
1028
|
+
- `world.bodyOf(node)` finds the body that moves a node. `world.setPointer(pointer, value)` writes a joint drive's `maxForce`, `positionTarget`, `velocityTarget`, `stiffness` or `damping`, or a motion's `linearVelocity`, `angularVelocity` or `gravityFactor`, and returns false for anything else.
|
|
1029
|
+
- `world.notes` lists what this file asks for that the world holds only approximately, by node. Empty means the file is represented as written.
|
|
1030
|
+
|
|
1031
|
+
Limits are in [docs/limits.md](../../docs/limits.md): the solver's order of combine rules differs from the draft's, soft limits are held hard, ranges on several axes are boxes, finite planes are thin boxes, and a file can have 15 distinct collision filters.
|
|
1032
|
+
|
|
1033
|
+
#### Behaviour graphs in glTF (`/interactivity`)
|
|
1034
|
+
|
|
1035
|
+
`KHR_interactivity` carries a behaviour graph in the file: on a click, play an animation, change a material, wait, count. `KHR_node_selectability` and `KHR_node_hoverability` say which nodes take a click or a hover. Every loader reads such a file, even with these as required extensions. To run the graph on a rendered model, attach it with `@margoengine/animation/interactivity`, which [its README](../animation/README.md#behaviour-graphs-margoengineanimationinteractivity) covers. This entry is the graph alone: it needs no engine, and time moves only through `tick`, so a server or a test can run a file.
|
|
1036
|
+
|
|
1037
|
+
```ts
|
|
1038
|
+
import {GLTFAsset} from 'margoengine/gltf/pbr';
|
|
1039
|
+
import {loadBehaviorGraph} from 'margoengine/gltf/interactivity';
|
|
1040
|
+
|
|
1041
|
+
const doc = {
|
|
1042
|
+
asset: {version: '2.0'},
|
|
1043
|
+
extensions: {
|
|
1044
|
+
KHR_interactivity: {
|
|
1045
|
+
graphs: [{
|
|
1046
|
+
events: [{id: 'ready'}],
|
|
1047
|
+
declarations: [{op: 'event/onStart'}, {op: 'event/send'}],
|
|
1048
|
+
nodes: [
|
|
1049
|
+
{declaration: 0, flows: {out: {node: 1, socket: 'in'}}},
|
|
1050
|
+
{declaration: 1, configuration: {event: {value: [0]}}},
|
|
1051
|
+
],
|
|
1052
|
+
}],
|
|
1053
|
+
},
|
|
1054
|
+
},
|
|
1055
|
+
};
|
|
1056
|
+
const {graph, rejected} = loadBehaviorGraph(new GLTFAsset(doc, []));
|
|
1057
|
+
if (rejected) console.warn(rejected);
|
|
1058
|
+
graph?.on('ready', () => console.log('the file is running'));
|
|
1059
|
+
graph?.tick(1 / 60);
|
|
1060
|
+
```
|
|
1061
|
+
|
|
1062
|
+
| Option of `loadBehaviorGraph` | Default | Meaning |
|
|
1063
|
+
| --- | --- | --- |
|
|
1064
|
+
| `live` | none | Called with each written property's pointer and value. |
|
|
1065
|
+
| `camera` | none | Returns the viewer's camera for `activeCamera`; without it those pointers read as NaN. |
|
|
1066
|
+
| `sample` | none | Samples a clip's channel. `sampleChannel` of `@margoengine/animation/interactivity`. Without it `animation/start` takes its `err` flow. |
|
|
1067
|
+
| `physics` | none | Runs `rigid_body/*` operations. |
|
|
1068
|
+
| `log` | none | Receives `debug/log` text. |
|
|
1069
|
+
| `maxActivations` | 1,000,000 | Node activations one step may run before the graph halts. A graph can loop forever, and a file is untrusted. |
|
|
1070
|
+
| `maxEventsPerTick` | 10,000 | Custom events one tick delivers; the rest wait for the next tick. |
|
|
1071
|
+
| `supported` | none | More extension names for a graph to see as enabled. |
|
|
1072
|
+
|
|
1073
|
+
`graph` has `tick(seconds)`, `on(id, listener)`, `send(id, values)`, `variable(idOrName)`, `select(node, info)`, `hover(node)`, `link(otherGraph)` for files that share events, and `halted`, the reason a graph stopped. A graph the specification rejects comes back as `rejected` and the model stays valid.
|
|
1074
|
+
|
|
1075
|
+
Read against the specification on Khronos main at commit a7963af6dc (2026-10-19), status "Complete, Ratified by the Khronos Group". On the published conformance suite this entry passes 1,155 of 1,156 sub-tests and rejects 187 of 187 invalid graphs. The one failure is a disagreement between that suite and the glTF Object Model, described with the other limits in [docs/limits.md](../../docs/limits.md).
|
|
1076
|
+
|
|
1077
|
+
#### Author, licence and copyright in glTF (`/metadata`)
|
|
1078
|
+
|
|
1079
|
+
`KHR_xmp_json_ld` carries XMP metadata in the file: who made it, under what licence, and which object each statement is about. Every loader keeps it as plain data, so it costs nothing until you import the entry, and a file that lists the extension as required still loads. `readGLTFMetadata` takes a loaded model, a `GLTFAsset` or a glTF document.
|
|
1080
|
+
|
|
1081
|
+
```ts
|
|
1082
|
+
import {GLTFAsset} from 'margoengine/gltf/pbr';
|
|
1083
|
+
import {readGLTFMetadata} from 'margoengine/gltf/metadata';
|
|
1084
|
+
|
|
1085
|
+
const doc = {
|
|
1086
|
+
asset: {version: '2.0', copyright: '2026 Ana Silva', extensions: {KHR_xmp_json_ld: {packet: 0}}},
|
|
1087
|
+
meshes: [{name: 'Chair', primitives: [], extensions: {KHR_xmp_json_ld: {packet: 1}}}],
|
|
1088
|
+
extensions: {
|
|
1089
|
+
KHR_xmp_json_ld: {
|
|
1090
|
+
packets: [
|
|
1091
|
+
{
|
|
1092
|
+
'@context': {dc: 'http://purl.org/dc/elements/1.1/'},
|
|
1093
|
+
'dc:creator': {'@list': ['Ana Silva']},
|
|
1094
|
+
'dc:rights': 'CC-BY-4.0',
|
|
1095
|
+
},
|
|
1096
|
+
{
|
|
1097
|
+
'@context': {dc: 'http://purl.org/dc/elements/1.1/', rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'},
|
|
1098
|
+
'dc:title': {
|
|
1099
|
+
'@type': 'rdf:Alt',
|
|
1100
|
+
'rdf:_1': {'@language': 'en-us', '@value': 'Chair'},
|
|
1101
|
+
'rdf:_2': {'@language': 'it-it', '@value': 'Sedia'},
|
|
1102
|
+
},
|
|
1103
|
+
},
|
|
1104
|
+
],
|
|
1105
|
+
},
|
|
1106
|
+
},
|
|
1107
|
+
};
|
|
1108
|
+
const metadata = readGLTFMetadata(new GLTFAsset(doc, []), {language: 'it'});
|
|
1109
|
+
console.log(metadata.asset.authors, metadata.asset.license, metadata.asset.copyright);
|
|
1110
|
+
console.log(metadata.fieldsOf('mesh', 0).title, metadata.fieldsOf('mesh', 0).authors); // Sedia, and the file's author
|
|
1111
|
+
for (const packet of metadata.packets) console.log(packet.fields.title, packet.fields.license); // every credit in the file
|
|
1112
|
+
```
|
|
1113
|
+
|
|
1114
|
+
| Field | Read from |
|
|
1115
|
+
| --- | --- |
|
|
1116
|
+
| `title`, `description`, `date`, `source` | `dc:title`, `dc:description`, the first `dc:date`, `dc:source` |
|
|
1117
|
+
| `authors`, `contributors`, `publishers` | `dc:creator`, `dc:contributor`, `dc:publisher`, always arrays |
|
|
1118
|
+
| `tool` | `xmp:CreatorTool`; for the whole file, else glTF `asset.generator` |
|
|
1119
|
+
| `rights` | `dc:rights` as written |
|
|
1120
|
+
| `license` | `cc:license`, else `xmpRights:UsageTerms`, else `xmpRights:WebStatement`, else `rights` |
|
|
1121
|
+
| `copyright` | For the whole file glTF `asset.copyright`, else `rights`; for an object its own `rights`, else the whole file's |
|
|
1122
|
+
|
|
1123
|
+
| Member of the result | Meaning |
|
|
1124
|
+
| --- | --- |
|
|
1125
|
+
| `asset` | The fields for the whole file. A file without the extension still gives `asset.copyright` and `asset.generator`. |
|
|
1126
|
+
| `objects` | Each scene, node, mesh, material, image and animation with its own packet. |
|
|
1127
|
+
| `fieldsOf(kind, index)` | The fields for one object: its packet over `asset`, property by property, as the extension gives objects precedence. |
|
|
1128
|
+
| `packets` | Every packet, referenced or not, with `fields`, `properties`, `raw` and `get(namespace, name)` for any other XMP property. `xmpNamespaces` holds the URIs of `dc`, `xmp`, `xmpRights`, `cc` and `rdf`. |
|
|
1129
|
+
|
|
1130
|
+
| Option of `readGLTFMetadata` | Default | Meaning |
|
|
1131
|
+
| --- | --- | --- |
|
|
1132
|
+
| `language` | none | BCP 47 tag to prefer among language alternatives: the exact tag, then the same language in another region. With none, or no match, `x-default`, then the first listed. |
|
|
1133
|
+
|
|
1134
|
+
Properties resolve by namespace URI, so `dc11:creator` reads as an author when `dc11` names Dublin Core, and `dc:creator` does not when a packet points `dc` elsewhere. A prefix a packet leaves out of `@context` keeps its usual meaning, because a real exporter writes `xmp:CreatorTool` that way. A bad packet list or `packet` reference throws a `TypeError` here and never at load. Limits are in [docs/limits.md](../../docs/limits.md).
|
|
1135
|
+
|
|
1136
|
+
#### Texture mip streaming (`textures` of `/progressive`)
|
|
1137
|
+
|
|
1138
|
+
KTX 2.0 keeps the smallest mip first, so a texture can start from a small read of the head of its file. With `textures` set, `loadGLTFProgressive` opens each KTX2 image from those smallest levels and loads finer ones only as the texture's size on screen calls for them, inside a memory budget. Levels nothing needs leave when the budget runs out. It reuses `KTX2Streamer` of `@margoengine/decoders/ktx2-stream`, loaded only with this option.
|
|
1139
|
+
|
|
1140
|
+
```ts
|
|
1141
|
+
import {createStage} from 'margoengine';
|
|
1142
|
+
import {loadGLTFProgressive} from 'margoengine/gltf/progressive';
|
|
1143
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
1144
|
+
const load = loadGLTFProgressive(stage.engine, '/city.gltf', {textures: {budgetBytes: 128 * 1024 * 1024}});
|
|
1145
|
+
const model = await load.complete;
|
|
1146
|
+
const textures = await load.textures;
|
|
1147
|
+
console.log(model.primitives.length, textures?.usedBytes, textures?.textures);
|
|
1148
|
+
```
|
|
1149
|
+
|
|
1150
|
+
| Option of `textures` (or `true`) | Default | Meaning |
|
|
1151
|
+
| --- | --- | --- |
|
|
1152
|
+
| `budgetBytes` | 256 MiB | Most GPU memory the load's textures may hold. A stream always keeps its coarsest levels, whatever the budget. Change it later through `load.textures`. |
|
|
1153
|
+
| `concurrency` | `2` | Levels loading at once. |
|
|
1154
|
+
| `headBytes` | 64 KiB | Bytes of an image's first Range read. |
|
|
1155
|
+
| `decoder`, `hdrDecoder` | made on first use | Level decoders, as `KTX2Streamer`. |
|
|
1156
|
+
| `onError` | `console.error` | Called when a finer level fails; the texture keeps the levels it has. |
|
|
1157
|
+
|
|
1158
|
+
`load.textures` is a promise of the live stream: `usedBytes`, `budgetBytes` (settable), `textures` (each one's size, finest level held, level count and size on screen) and `update()`. It runs by itself about five times a second for as long as the model lives; disposing the model frees it.
|
|
1159
|
+
|
|
1160
|
+
A texture's size on screen is the square root of its primitive's surface area over its UV area, which is the length one whole texture covers, times the pixels one world unit covers at the nearest point of the primitive's bounding sphere, on the nearest camera that sees it. Tiling, atlases and `KHR_texture_transform` scale need no special case. An image inside a GLB or a `.bin` streams too, by Range reads at its offset, and those bytes stay out of the buffers; on a server without Range the file comes once and the texture streams from memory. A file `loadGLTFProgressive` takes whole (Draco, meshopt, or a `fetch` option) still streams its KTX2 images. `complete` means every primitive is loaded and every texture is drawing from at least its coarsest levels.
|
|
1161
|
+
|
|
1162
|
+
PNG, JPEG, WebP and AVIF files hold no mips, so they load whole, and a KTX2 file stored with one level has nothing to stream. `model.uploadImage` refuses a streamed image, and a replica on another device refuses a streamed model. Off WebGPU the option has no effect. See `docs/limits.md`.
|
|
1163
|
+
|
|
1164
|
+
#### Optional material extension slot
|
|
1165
|
+
|
|
1166
|
+
Attach a `MaterialExtension` to `primitive.extension`, or to the shared
|
|
1167
|
+
`primitive.material.extension`, after `parseGLTF` or `loadGLTF` returns. The
|
|
1168
|
+
primitive slot takes precedence. No material package is imported or discovered
|
|
1169
|
+
by the loader. `parseGLTF` stays synchronous; `loadGLTF` retains its existing
|
|
1170
|
+
Promise-based loading API.
|
|
1171
|
+
|
|
1172
|
+
```ts
|
|
1173
|
+
import {type MaterialExtension, type PBRModel} from 'margoengine/gltf/pbr';
|
|
1174
|
+
import {Engine} from 'margoengine/core';
|
|
1175
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
1176
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1177
|
+
const model = await loadGLTF(engine, '/model.glb');
|
|
1178
|
+
const tint: MaterialExtension = {
|
|
1179
|
+
factors: new Float32Array([1, 0.5, 0.25, 1]),
|
|
1180
|
+
wgsl: 's.base *= materialFactors[0];'
|
|
1181
|
+
};
|
|
1182
|
+
model.primitives[0].extension = tint;
|
|
1183
|
+
```
|
|
1184
|
+
|
|
1185
|
+
Bind groups are permanently allocated as follows: group 0 is the original
|
|
1186
|
+
400-byte frame buffer, group 1 is the original five texture/sampler pairs,
|
|
1187
|
+
group 2 is lighting and local material shading, and **group 3 is the optional material extension**.
|
|
1188
|
+
Unextended primitives use exactly the original shader, pipeline descriptors,
|
|
1189
|
+
uniform uploads and bindings. Extension GPU resources are created lazily during
|
|
1190
|
+
`draw()`, including when an extension is attached after model setup.
|
|
1191
|
+
|
|
1192
|
+
`factors` is an optional, nonempty `Float32Array` of finite values whose length
|
|
1193
|
+
is a multiple of four. It becomes `materialFactors: array<vec4f, N>` at group 3,
|
|
1194
|
+
binding 0. Mutations upload on the next visible draw; changing its length
|
|
1195
|
+
reallocates only the secondary buffer. `textures` optionally supplies
|
|
1196
|
+
`{view, sampler?}` entries for filterable 2D textures; each is a `GPUTextureView` or `GPUSampler`, or
|
|
1197
|
+
`(device) => object`, called once per device and again after a device restore (`view: (device) => makeView(device)`).
|
|
1198
|
+
Entry N exposes `materialTextureN` at binding `1 + 2*N` and, if supplied,
|
|
1199
|
+
`materialSamplerN` at binding `2 + 2*N`. Missing factors, textures and samplers
|
|
1200
|
+
allocate no corresponding resources. Texture views and samplers stay owned by
|
|
1201
|
+
the caller. A plain view or sampler belongs to the device that made it: after a device restore it is dropped and
|
|
1202
|
+
reported once through `engine.onError` (`'state'`, help `borrowed-lost`), the surface reads a 1 x 1 white texture and a
|
|
1203
|
+
linear sampler in its place, and giving the material a new `MaterialExtension` brings it back. The function form needs
|
|
1204
|
+
no replacement, and is the one `createRenderer(device)` accepts for another device.
|
|
1205
|
+
|
|
1206
|
+
`wgsl` contains statements inserted immediately after `surface(i, front)` in
|
|
1207
|
+
beauty, g-buffer and ambient fragment entry points. It can mutate `s: Surface`
|
|
1208
|
+
and read `i`, `front`, the original frame `f`, and the generated extension
|
|
1209
|
+
resources. `declarations` optionally supplies module-scope WGSL helpers. Callers
|
|
1210
|
+
must supply valid WGSL for all three entry points and leave bind group allocation
|
|
1211
|
+
to the slot. Generated phony assignments retain declared resources in each
|
|
1212
|
+
entry point's interface without sampling them. A resource-bearing extension
|
|
1213
|
+
without lighting also binds the empty group 2 required by the pipeline layout.
|
|
1214
|
+
|
|
1215
|
+
`direct` optionally supplies beauty-only statements after the directional
|
|
1216
|
+
lighting calculation. It may update `direct` before the existing lighting effects
|
|
1217
|
+
apply, so additional lobes share directional shadow visibility. It does not run
|
|
1218
|
+
in g-buffer or ambient entry points. Unextended shader strings stay unchanged.
|
|
1219
|
+
A second model of the same asset can hold this model's decoded images, and then shares the GPU textures made from
|
|
1220
|
+
them instead of uploading and mipping its own. Each image and texture goes with its last holder, in any disposal order
|
|
1221
|
+
(`cloneModel` from `@margoengine/animation/skeleton-utils` does this for you):
|
|
1222
|
+
|
|
1223
|
+
```ts
|
|
1224
|
+
import {PBRModel, loadGLTF} from 'margoengine/gltf/pbr';
|
|
1225
|
+
import {Engine} from 'margoengine/core';
|
|
1226
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1227
|
+
|
|
1228
|
+
const first = await loadGLTF(engine, 'robot.glb');
|
|
1229
|
+
const second = new PBRModel(engine, first.asset, first.shareImages());
|
|
1230
|
+
engine.use(second);
|
|
1231
|
+
```
|
|
1232
|
+
|
|
1233
|
+
`shareImages()` counts the new holder at once: pass the images to `closeImages(images)` if no model ends up holding
|
|
1234
|
+
them.
|
|
1235
|
+
|
|
1236
|
+
`second.adoptStaticBatches(first)`, called before `engine.use(second)`, takes `first`'s baked static batches so
|
|
1237
|
+
`second` skips baking and the engine-wide tick baking needs. `second` must be a fresh model of the same asset in the
|
|
1238
|
+
same local pose, and `first` must be set up and unparented. It returns false, changing nothing, when the batches do not
|
|
1239
|
+
fit, and `second` then bakes for itself. Either way draws are right. `cloneModel` in `@margoengine/animation` calls it.
|
|
1240
|
+
|
|
1241
|
+
`model.compile()` compiles the model's render pipelines without blocking, so its first frame does not wait for them.
|
|
1242
|
+
Call it once the scene's lights and effects are set: anything that changes a shader afterwards compiles on the draw as
|
|
1243
|
+
before, so it is never needed for correctness. Start it early and await it late, so the compile overlaps other work. The
|
|
1244
|
+
wait moves rather than disappears: `p-morph`'s first frame fell by 83 ms and its build grew by 54 to 72.
|
|
1245
|
+
|
|
1246
|
+
```ts
|
|
1247
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
1248
|
+
import {Engine} from 'margoengine/core';
|
|
1249
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1250
|
+
|
|
1251
|
+
const model = await loadGLTF(engine, 'robot.glb');
|
|
1252
|
+
const compiled = model.compile();
|
|
1253
|
+
// ...build the rest of the scene...
|
|
1254
|
+
await compiled;
|
|
1255
|
+
```
|
|
1256
|
+
|
|
1257
|
+
It does nothing off WebGPU, leaves batched textureless meshes to their first draw, and rejects with the GPU's error if
|
|
1258
|
+
a pipeline fails. Copies of a model share pipelines, so one call serves them all.
|
|
1259
|
+
|
|
1260
|
+
Optional material packages can borrow decoded images with `model.image(index)`;
|
|
1261
|
+
the model retains ownership and closes them when disposed.
|
|
1262
|
+
|
|
1263
|
+
`output` optionally supplies beauty-only WGSL immediately before the final
|
|
1264
|
+
return, after tone mapping/output encoding. `lighting: false` omits optional
|
|
1265
|
+
lighting shaders and bindings for a caller-managed surface. The material package
|
|
1266
|
+
uses these hooks for transmission while retaining the baseline factor-zero path.
|
|
1267
|
+
`transmission` (a WGSL weight, kept in `s.tr`) scales diffuse and ambient light by
|
|
1268
|
+
1 minus it, and `ior` (a WGSL index of refraction, kept as `s.f0`) sets the
|
|
1269
|
+
dielectric F0 of direct and ambient light to ((ior - 1) / (ior + 1))^2 in place of
|
|
1270
|
+
0.04, as the native physical path does; without `ior` the F0 stays 0.04.
|
|
1271
|
+
The optional `coat` layer goes over all the surface's light, as
|
|
1272
|
+
`KHR_materials_clearcoat` defines it: direct, local, ambient and emitted light keep
|
|
1273
|
+
the share `keep`, the layer's `direct` light adds on top with the same shadow
|
|
1274
|
+
visibility, and `(1 - keep) * margoCoatAmbient(s, v)` adds its ambient light. `normal`
|
|
1275
|
+
and `roughness` land in `s.cn` and `s.cr`, which an environment's `coat` hook reads.
|
|
1276
|
+
`direct` hooks of lighting effects must scale the light they wrap, since a coated
|
|
1277
|
+
shader evaluates them once on `vec3f(1)` and multiplies every sun lobe by the result.
|
|
1278
|
+
Native physical materials do the same for their clearcoat and sheen lobes, so a
|
|
1279
|
+
shadow removes those highlights with the base's; fragments where nothing is lit
|
|
1280
|
+
stay zero, so `Shadows` still skips them. An effect with only a raw `shader` edit of
|
|
1281
|
+
`direct+ambient(s)` reaches the base's light and misses these lobes, so a shadowing
|
|
1282
|
+
effect uses the `direct` hook. All four fields are WGSL expressions
|
|
1283
|
+
evaluated after `wgsl`:
|
|
1284
|
+
|
|
1285
|
+
```ts
|
|
1286
|
+
import {type MaterialExtension} from 'margoengine/gltf/pbr';
|
|
1287
|
+
|
|
1288
|
+
const varnish: MaterialExtension = {
|
|
1289
|
+
wgsl: 'let varnishKeep=0.9;',
|
|
1290
|
+
coat: {keep: 'varnishKeep', direct: 'vec3f(0)', normal: 's.n', roughness: '0.1'},
|
|
1291
|
+
};
|
|
1292
|
+
```
|
|
1293
|
+
|
|
1294
|
+
The optional `ambient` statements can mutate `materialAmbient` after hemisphere
|
|
1295
|
+
lighting in beauty and ambient-only passes. They are applied after lighting
|
|
1296
|
+
effects have matched the standard PBR source. Materials uses this hook for sheen,
|
|
1297
|
+
specular color and thin-film reflection; primitives without a hook retain their
|
|
1298
|
+
original shader and bindings.
|
|
1299
|
+
`PBRModel.beginOpaquePass(context)` defers blended beauty draws across models;
|
|
1300
|
+
`PBRModel.endOpaquePass(context)` flushes them after a caller-owned scene copy,
|
|
1301
|
+
and `cancelOpaquePass(context)` releases an interrupted phase. Calls to `draw()`
|
|
1302
|
+
with an explicit `opaque` or `blend` phase participate in the same deferral:
|
|
1303
|
+
opaque primitives draw immediately and blended primitives flush once per model.
|
|
1304
|
+
Calls outside that optional phase retain their existing order and bindings.
|
|
1305
|
+
An extension with `afterOpaque: true` (materials transmission sets it) also flushes with the blended draws, after the
|
|
1306
|
+
opaque capture, but keeps its authored alpha mode, blending and depth writes; such primitives cast no opaque shadows.
|
|
1307
|
+
|
|
1308
|
+
A package whose frame-graph pass draws one run and nothing else can declare `joins` on its pass: the run's render pass then takes core's clear and resolves the frame ([core README](../core/README.md#viewport-and-scissor-per-core-draw)), one render pass for the whole frame.
|
|
1309
|
+
|
|
1310
|
+
A package that draws many models itself passes a `PBRDrawRun` as the last argument of `draw()`. Every `draw()` of the
|
|
1311
|
+
run continues one render pass instead of beginning its own, which saves a store and a reload of the multisampled colour
|
|
1312
|
+
and depth per model (10,000 meshes of `@margoengine/materials` cost 168 ms of CPU a frame with a pass each). Blended
|
|
1313
|
+
draws continue it too; a blended primitive drawn without a run ends the pass around itself. Within a run:
|
|
1314
|
+
|
|
1315
|
+
- draws of one material record derive its shader, pipeline and lighting bind group once per frame, not once per draw;
|
|
1316
|
+
- the run sets a pipeline, bind group or buffer only when it changes;
|
|
1317
|
+
- opaque draws that differ only in their node matrix (same material record, same geometry arrays, no instances,
|
|
1318
|
+
deformation, material extension, transmission or wireframe) draw as one instanced draw at `run.end()` or before the
|
|
1319
|
+
run's next other draw, with their world matrices as instance rows; a moved mesh uploads its own 96-byte row. Opaque
|
|
1320
|
+
draws may therefore reorder between such batches (as engines sort opaque draws by material); each batch keeps its
|
|
1321
|
+
meshes in draw order, and a mesh alone draws exactly as without a run.
|
|
1322
|
+
|
|
1323
|
+
Every draw's camera, light and target rows come from one 192-byte view block that the draws of a view share, so a
|
|
1324
|
+
moving camera uploads 192 bytes, not every draw's uniform. Call `run.end()` after the last draw; a run can carry the
|
|
1325
|
+
next frame's draws after that:
|
|
1326
|
+
|
|
1327
|
+
```ts
|
|
1328
|
+
import {PBRDrawRun, type PBRModel} from '@margoengine/gltf/pbr';
|
|
1329
|
+
export function drawAll(models: PBRModel[], c: Parameters<PBRModel['draw']>[0]) {
|
|
1330
|
+
const run = new PBRDrawRun();
|
|
1331
|
+
try {
|
|
1332
|
+
for (const model of models) model.draw(c, 'beauty', c.color, c.depth, 'all', undefined, run);
|
|
1333
|
+
} finally {
|
|
1334
|
+
run.end();
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
```
|
|
1338
|
+
|
|
1339
|
+
Full generated WGSL, including the injection and resource layout, distinguishes
|
|
1340
|
+
pipeline cache entries. Even an empty extension cannot share the baseline
|
|
1341
|
+
pipeline. Removing an extension releases its secondary buffer on the next
|
|
1342
|
+
visible draw and restores the baseline path. Model disposal and device
|
|
1343
|
+
restoration release all owned secondary buffers. Extensions that require
|
|
1344
|
+
blending use the existing `material.settings[0] = 2` path. This slot adds no new
|
|
1345
|
+
material lobes, passes or attributes.
|
|
1346
|
+
|
|
1347
|
+
Run `node scripts/material-extension-tests.js` for the material slot's WebGPU
|
|
1348
|
+
checks, also included in `npm run modern:test:extensions`.
|
|
1349
|
+
|
|
1350
|
+
Limits: triangle primitives; at most eight skin influences in the animation package; UV sets 0 to 3. Unknown required extensions still reject. Ambient fill uses fixed sky/ground colors unless the scene has a lighting `Sky` (`sceneSky`, above) or the model is given an environment; image-based lighting is a separate optional package. Bounds describe the bind pose with current node transforms; GPU picking requires the optional selection package.
|
|
1351
|
+
|
|
1352
|
+
`npm run modern:test:gltf-parity` checks texture-coordinate and alpha-shadow pixel
|
|
1353
|
+
parity, KTX2 mip upload and worker disposal in a production Vite build, complete
|
|
1354
|
+
Khronos assets, and eight-influence character deformation against a CPU reference.
|
|
1355
|
+
These checks are also part of `npm run modern:test:extensions`.
|
|
1356
|
+
|
|
1357
|
+
The demo at `/examples/flight-helmet.html` loads the [Khronos FlightHelmet](https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/FlightHelmet) (CC0 1.0). Asset credits are in [THIRD-PARTY-NOTICES.md](../../THIRD-PARTY-NOTICES.md).
|
|
1358
|
+
|
|
1359
|
+
#### Absent physical maps on limited devices
|
|
1360
|
+
|
|
1361
|
+
Native glTF physical materials bind only authored extension maps. Absent maps use their existing
|
|
1362
|
+
constant fallback in the shader, leaving texture units available for image lighting and shadows.
|
|
1363
|
+
The five core map bindings stay stable. Fallback views remain available if a material hook is added
|
|
1364
|
+
or removed live; its full resource interface is retained. This fixes the viewer's
|
|
1365
|
+
transmission lens plus IBL and shadows on a 16-unit WebGL2 compatibility device. Authored maps
|
|
1366
|
+
are retained; a material that really exceeds hardware limits still has that limit.
|
|
1367
|
+
|
|
1368
|
+
Extension maps that point at one glTF texture (the same image and sampler) bind it once; each slot keeps its own UV
|
|
1369
|
+
set and transform. Slots share only within one colour space, except that a slot reading only alpha (sheen roughness,
|
|
1370
|
+
specular) also reads an sRGB view, where alpha stays linear. So clearcoat R + roughness G, sheen colour RGB + roughness
|
|
1371
|
+
A and specular A + colour RGB, packed as the extensions suggest, bind 5 extension textures in place of 8. Clearcoat
|
|
1372
|
+
(linear) and sheen colour (sRGB) in one texture keep two views. Extended materials (`extendedMaterials`) follow the
|
|
1373
|
+
same rule over all their slots, so their eight extension textures count one binding per texture and colour space, and
|
|
1374
|
+
specular colour packed with specular decodes as sRGB there too. Nothing to set: the same glTF file draws with fewer
|
|
1375
|
+
texture units. `node packages/gltf/scripts/test-extended-colour-space-browser.mjs` checks it on WebGPU, and with
|
|
1376
|
+
`--compat` on the WebGL2 compatibility layer.
|
|
1377
|
+
|
|
1378
|
+
If a physical or extended material still composes a shader past the device's limit (WebGPU's sampled textures or
|
|
1379
|
+
samplers per stage, or the texture units the WebGL2 compatibility layer counts before linking), its five base maps
|
|
1380
|
+
pack into one texture array, four texture units fewer, and the shader is composed again. The choice is made per
|
|
1381
|
+
material and device at its first pipeline and kept; a material that fits keeps its separate base maps, and the array
|
|
1382
|
+
is made only when a packed pipeline first binds it. A material past the limit even packed still gets the existing
|
|
1383
|
+
`RangeError` (WebGPU) or the layer's coded `unsupported` ([errors#texture-units](https://margoengine.com/errors#texture-units)).
|
|
1384
|
+
Nothing to set: the same `loadGLTF` call draws on a 16-unit device where it would have been refused.
|
|
1385
|
+
|
|
1386
|
+
The existing loadGLTF examples apply unchanged. Run scripts/stage-viewer-gpu-check.js with --compat
|
|
1387
|
+
for the licensed FlightHelmet integration regression, including cascaded
|
|
1388
|
+
shadows, IBL, visible product, turntable radius, failed-load rollback and disposal. No speed claim.
|
|
1389
|
+
|
|
1390
|
+
#### Required outside GPU samples
|
|
1391
|
+
|
|
1392
|
+
The extension GPU harness resolves FlightHelmet, EnvironmentTest, ScatteringSkull and the large
|
|
1393
|
+
tower capture through the same external cache as verify. Every case validates its files and
|
|
1394
|
+
companions by hash. Missing files fail with the existing fetch-skip-assets recovery command; an
|
|
1395
|
+
unset MARGO_SPLAT_SAMPLES uses the normal shared cache. No case reports success without its input.
|
|
1396
|
+
|
|
1397
|
+
#### GLB padding
|
|
1398
|
+
|
|
1399
|
+
A GLB's BIN chunk may be up to 3 bytes longer than buffer 0's `byteLength`, to pad it to 4 bytes (glTF 2.0 section
|
|
1400
|
+
4.4.3.3). `parseGLTF`, `parseGLTFAsync`, `loadGLTF`, the worker loaders and `loadGLTFProgressive` (main thread and worker) refuse a longer chunk, as the Khronos glTF Validator does, with a `MargoError` (code `failed`)
|
|
1401
|
+
that gives both lengths and links to https://margoengine.com/errors#failed. Export the file again.
|
|
1402
|
+
|
|
1403
|
+
#### Git LFS pointer files
|
|
1404
|
+
|
|
1405
|
+
A repository cloned without Git LFS serves small pointer files (text starting
|
|
1406
|
+
`version https://git-lfs`) in place of its models. `loadGLTF` and `parseGLTFAsync` check the first
|
|
1407
|
+
bytes of every .gltf, .glb, external .bin and image they fetch (the streaming loader checks its .gltf
|
|
1408
|
+
root), and refuse a pointer with a `MargoError` (code `failed`) that names the URL and links to
|
|
1409
|
+
https://margoengine.com/errors#git-lfs. Run `git lfs pull` where the files are served, then reload.
|
|
1410
|
+
|
|
1411
|
+
```ts
|
|
1412
|
+
import { loadGLTF } from '@margoengine/gltf/pbr';
|
|
1413
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
1414
|
+
|
|
1415
|
+
export async function load(engine: EngineKernel) {
|
|
1416
|
+
try {
|
|
1417
|
+
return await loadGLTF(engine, '/models/robot.glb');
|
|
1418
|
+
} catch (error) {
|
|
1419
|
+
// A pointer file reads: "... is a Git LFS pointer file, not the asset; run git lfs pull ..."
|
|
1420
|
+
if (error instanceof Error && error.message.includes('Git LFS pointer')) console.error(error.message);
|
|
1421
|
+
throw error;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
```
|
|
1425
|
+
|
|
1426
|
+
### Loading into a second scene
|
|
1427
|
+
|
|
1428
|
+
`loadGLTF`, `parseGLTFAsync`, `loadGLTFProgressive`, `loadGLTFInWorker` and `parseGLTFInWorker` remember the scene that is
|
|
1429
|
+
active when you call them, before their first await, and attach the model there (and its Gaussian splat clouds, and
|
|
1430
|
+
the progressive loader's texture stream). Start a load inside a second scene's plugin `setup` and the model belongs
|
|
1431
|
+
to that scene; start it anywhere else and it belongs to the default scene. If that scene is disposed while the load
|
|
1432
|
+
runs, the load rejects with a `TypeError`. An abort leaves nothing in either scene.
|
|
1433
|
+
|
|
1434
|
+
### Preview tier contract
|
|
1435
|
+
|
|
1436
|
+
The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
|
|
1437
|
+
|
|
1438
|
+
`PBRModel` already refused the preview during setup. The tier regression loads an HTTP glTF fixture, checks direct refusal and automatic escalation, then verifies model and selection pixels on both complete tiers.
|