@margoengine/core 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +503 -459
- package/dist/camera.js +1 -1
- package/dist/clear-color-ziMPCpSz.js +4 -0
- package/dist/engine.d.ts +4 -1
- package/dist/engine.js +1 -1
- package/dist/{errors-B6KSysyy.js → errors-D0VAEAiW.js} +1 -1
- package/dist/extension.d.ts +4 -1
- package/dist/extension.js +1 -1
- package/dist/geometry.js +1 -1
- package/dist/{hypot-Bouwbr1T.js → hypot-B7a6-Lk8.js} +1 -1
- package/dist/kernel.js +1 -1
- package/dist/plugin.d.ts +17 -0
- package/dist/plugin.js +1 -1
- package/dist/renderer.d.ts +10 -1
- package/dist/renderer.js +2 -2
- package/dist/shared/errors.d.ts +16 -0
- package/dist/shared/hypot.d.ts +12 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/{view-rect-DBHPjboz.js → view-rect-DJ1fxok2.js} +1 -1
- package/package.json +48 -48
- package/dist/clear-color-jWdkJ0Fa.js +0 -4
package/README.md
CHANGED
|
@@ -1,459 +1,503 @@
|
|
|
1
|
-
# @margoengine/core
|
|
2
|
-
|
|
3
|
-
Import `margoengine/core` from the `margoengine` package, or `@margoengine/core` 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
|
-
WebGPU rendering (WebGL2 fallback via the optional `@margoengine/webgl2-compat/preview`), a deterministic Rust/Wasm transform kernel, instanced drawing of one directional GGX light on position and normal, reversed float depth and picking. Materials are color, roughness, and metalness.
|
|
6
|
-
|
|
7
|
-
Desktop scenes use 4× MSAA with a canvas DPR cap of 1; phones use single-sample rendering with a DPR cap of 2. For slower desktop GPUs, set `globalThis.margoLow` to a pixel ratio (for example `1` or `1.5`) before creating the engine: scenes then render single-sampled with the DPR capped at that value, which on an Intel Arc 140V laptop cut the island demo's GPU frame from about 20 to 10 ms (particles off) compared with 4× MSAA. The site demos choose this light tier by measuring the GPU rather than guessing from the device. Color and depth targets follow canvas resize. Optional scene captures retain that sampling policy and expose single-sample resolved textures. CSS layout and HTML text retain native density.
|
|
8
|
-
|
|
9
|
-
`engine.pick(x, y)` updates scene state without forcing a color frame. One readback runs at a time and overlapping calls wait their turn, so a loop of picks costs one readback a point. A pick asked for during a frame starts after it, and one asked for inside a pick (a plugin's `onPreUpdate` picking for a hover) waits behind it instead of nesting. Meshes created or removed elsewhere during a readback leave its answer standing; only a mesh created after the pick started (one that took the hit slot) is answered as null; `pickMany` of `@margoengine/selection` answers many points from one. For cached forward-pass IDs, instance culling in a 3×3 micro frustum and neighbor resolution, attach the optional `Picking` plugin from `@margoengine/selection`. On a canvas without client size (an `OffscreenCanvas` in a worker) pick coordinates are canvas pixels.
|
|
10
|
-
|
|
11
|
-
Static scenes cost little per frame: the kernel recomputes only entities whose position, rotation, scale, parent, bounds or visibility changed (and their descendants); the engine reuses last frame's instance list unless the mesh set, a geometry or material assignment, a material's values or the layers changed; a mesh that culling or `visible` shows or hides moves one row of its batch (shown: the batch's next row; hidden: the batch's last row takes its place), a moved mesh rewrites its own row, and the WebGPU renderer uploads only the changed rows, one `writeBuffer` for each run of neighbouring rows. On an Intel Arc 140V laptop the kernel part made the kernel 2.6-4x cheaper and let 50,000 CAD parts orbit at 92 FPS instead of 49 (CAD measurements, before the row change). An orbiting camera no longer re-collects every frame: with 50,000 boxes and 500 culling flips a frame, the frame does 50,000 byte compares, 1,000 map lookups, 12,000 float copies and uploads 48 KB in at most 500 writes, where it did 100,000 lookups, 1.2 million float copies and a 4.8 MB upload (counted in `tests/core-instance-cache.test.js`; not timed yet). Several cameras on one scene flip most rows, and then cost what a full collection costs. Draw order among the instances of one geometry follows these row moves, so it changes after a flip; opaque pixels are the same except for two core meshes at exactly the same depth. Contract for `@margoengine/core/extension` users: the per-geometry instance buffers (`engine.geometryBuffers(geometry).instance`) belong to core and are read-only for packages (bind them, never write them, except a package that claims a batch and uploads its changed rows with `uploadRows`, see "Bulk poses and instance rows"; use your own buffer, as `@margoengine/selection`'s micro pick pass does), and `store.matrices` is kernel output (change transforms through the mesh, never by writing world matrices). GPU culling of core meshes (`@margoengine/culling`'s `CulledMeshes`) uses one hook: passes see the frame's batches as `context.batches`, and a package may set `batch.redirect = {instances, args}` for the frame; every core draw of that batch (main pass and replays) then reads the package's compacted instance records and `drawIndexedIndirect` arguments instead of core's buffer and count. Core still uploads into its own instance buffer, which stays the read-only source the package culls from. `engine.start({culling: false})` skips core's CPU frustum test in the built-in loop (as `render({culling: false})` does for one frame) when a package culls on the GPU.
|
|
12
|
-
|
|
13
|
-
Entity capacity grows on demand: `Engine.create(canvas, {capacity})` sets the initial number of slots (default 1,024) and `createMesh` doubles the transform store when it is full, up to 8,388,608 (2^23). Growing re-creates the kernel at the same Wasm address, re-binds every `store` view and `mesh.matrix`, and recomputes every entity once on the next tick; a growth that cannot allocate throws and leaves the store unchanged. Store views and `mesh.matrix` taken before a `createMesh` may be stale afterwards (detached, or aliasing the new layout): re-read them, never keep them. Memory per slot: 344 B of kernel columns plus 7 B of flags (351 B; 352 MB of Wasm memory at 1,048,576 slots) and 5 B in the engine; each drawn instance adds 96 B on the CPU and 96 B on the GPU.
|
|
14
|
-
|
|
15
|
-
Mesh `position`, `rotation` and `scale` are retained live refs. Replacing one throws
|
|
16
|
-
`TypeError` with code `transform`: `Retained vector: use a transform setter`, followed by the help link.
|
|
17
|
-
Use `.set(x, y, z)`, `.setAll(value)`, individual components, or the mesh setters:
|
|
18
|
-
|
|
19
|
-
```ts
|
|
20
|
-
import { Engine } from '@margoengine/core';
|
|
21
|
-
|
|
22
|
-
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
23
|
-
const mesh = engine.createMesh();
|
|
24
|
-
mesh.position.set(1, 2, 3);
|
|
25
|
-
mesh.setRotation([0, Math.PI / 2, 0]);
|
|
26
|
-
mesh.scale.setAll(2);
|
|
27
|
-
engine.render();
|
|
28
|
-
engine.dispose();
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
Camera `position`, `target` and `up` are tuple values and remain assignable.
|
|
32
|
-
|
|
33
|
-
Camera controls are not in core: `CADCameraControls` is in `@margoengine/stage` (since 2026-11-07), and `@margoengine/controls` has orbit, map, fly and the rest.
|
|
34
|
-
|
|
35
|
-
Package name: `@margoengine/core`, version `
|
|
36
|
-
|
|
37
|
-
```ts
|
|
38
|
-
import { Camera, Engine, box, PbrMaterial } from 'margoengine/core';
|
|
39
|
-
|
|
40
|
-
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
41
|
-
const engine = await Engine.create(canvas, { backend: 'auto' });
|
|
42
|
-
const mesh = engine.createMesh()
|
|
43
|
-
.setGeometry(box())
|
|
44
|
-
.setMaterial(new PbrMaterial({ color: '#84d6bd', roughness: 0.3 }));
|
|
45
|
-
engine.onFrame((_, delta) => { mesh.rotation.y += delta; });
|
|
46
|
-
engine.start();
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
`Engine.create(canvas, options)` options (all optional, all part of the v1.0.0 API):
|
|
50
|
-
|
|
51
|
-
| Option | Default | Meaning |
|
|
52
|
-
| --- | --- | --- |
|
|
53
|
-
| `capacity` | `1024` | Initial mesh slots, 1 to 8,388,608; the store doubles when full. |
|
|
54
|
-
| `backend` | `'auto'` | `'auto'` tries WebGPU, then `fallback`; `'webgpu'` fails without WebGPU; `'webgl2'` uses `fallback`. |
|
|
55
|
-
| `camera` | `Camera` defaults | Initial camera settings (`position`, `target`, `fov`, ...). |
|
|
56
|
-
| `fallback` | none | Builds the non-WebGPU renderer, for example `webglRenderer` from `@margoengine/webgl2-compat/preview`. |
|
|
57
|
-
| `features` | `[]` | Extra WebGPU features to request when the adapter offers them, such as `['timestamp-query']`. |
|
|
58
|
-
| `exactSize` | `false` | `[width, height]` or `true`: pixel-exact backbuffer with no pixel-ratio scaling and no MSAA ([Pixel-perfect rendering](#pixel-perfect-rendering)). |
|
|
59
|
-
| `antialias` | `true`, `false` with `exactSize` | MSAA of the scene: `true` is the quality tier's samples (4 on desktop, 1 on phones and the light tier), `false` 1. With `exactSize` it gives a fixed-size frame with MSAA ([Fixed-size frames with MSAA](#fixed-size-frames-with-msaa)). |
|
|
60
|
-
| `signal` | none | An `AbortSignal` that cancels creation; it rejects with the signal's reason and never falls back ([Startup that never finishes](#startup-that-never-finishes)). |
|
|
61
|
-
| `startupWarning` | `8000` | Milliseconds a startup step may take before one `console.warn` names it. |
|
|
62
|
-
| `startupTimeout` | `30000` | Milliseconds before a startup step that never settles rejects with a `timeout` error. |
|
|
63
|
-
| `powerPreference` | unset | `'low-power'` or `'high-performance'`; unset asks for `'high-performance'`, and for nothing on Windows ([Choosing the GPU](#choosing-the-gpu)). |
|
|
64
|
-
|
|
65
|
-
`delta` is in seconds. The built-in loop clamps a long frame to `engine.maxDelta` (default `0.1`; keep it at 1 or less, since `render` rejects a larger delta with a RangeError), and when the page becomes visible again after a background tab its first frame steps `0`, so animation and physics resume where they paused instead of jumping.
|
|
66
|
-
|
|
67
|
-
Materials are live: `material.set({ color: '#ff8800', roughness: 0.2, metalness: 1, doubleSided: false })` changes the given values in place (omitted ones keep theirs; invalid input throws and changes nothing). Every mesh using the material shows it on the next frame with no new pipeline or bind group. A value change re-collects the frame's instances, so each drawn geometry's whole instance range is uploaded once on that frame (only changed ranges after that); for per-frame recolouring of one part among many thousands, give that part its own material or use `@margoengine/materials`. Core materials are opaque (no `opacity`).
|
|
68
|
-
|
|
69
|
-
Back faces of single-sided materials (`doubleSided: false`) are culled by the GPU: core draws a geometry batch with a second, back-culled pipeline whose shader has no `discard` (so early depth testing stays on) when every drawn instance of that geometry is single-sided and not mirrored (negative-determinant transform). One double-sided or mirrored instance puts the whole batch on the cull-none pipeline, which drops back faces in the shader as before; pixels are the same either way. Flipping `doubleSided` with `material.set`, assigning a material, or mirroring a mesh takes effect on the next frame; un-mirroring a moved mesh moves its batch back to the culled pipeline at the next full re-collection. Passes that replace core's shader text (fog, clipping, clustered lights...) or draw with extra bindings keep the cull-none pipeline. Instance records carry `Batch.mask` for packages: nonzero when the batch needs back faces.
|
|
70
|
-
|
|
71
|
-
`mesh.receiveShadow = false` (default true) keeps a mesh's direct light unshadowed by `@margoengine/shadows` and clustered local shadows while it still casts; the next frame re-collects instances. Core marks it by adding 0.25 to the instance's doubleSided factor (float 22), so every `< 0.5` single-sided test reads it unchanged; the shadow packages patch core's shader for it only while some mesh opts out.
|
|
72
|
-
|
|
73
|
-
The canvas is opaque. For a transparent canvas over HTML and CSS, attach `TransparentCanvas` from `@margoengine/environment`; core needs no option.
|
|
74
|
-
|
|
75
|
-
## When an allocation fails
|
|
76
|
-
|
|
77
|
-
`mesh.setGeometry()` allocates a geometry's GPU buffers the first time a mesh uses it, and larger instance storage as more
|
|
78
|
-
meshes share it. If that throws, for example `GPU buffer limit` from a geometry bigger than `maxBufferSize`, nothing has
|
|
79
|
-
changed: the error reaches you, the mesh keeps the geometry it had and keeps drawing it, every other mesh draws as before,
|
|
80
|
-
and calling again once there is room works. `engine.createMesh()` does the same when the transform store cannot grow.
|
|
81
|
-
|
|
82
|
-
Core asks the adapter for its own `maxBufferSize` and `maxStorageBufferBindingSize` (at creation and on every device
|
|
83
|
-
restore), not WebGPU's 256 MiB and 128 MiB defaults, so a desktop GPU's larger buffers are there for big meshes and
|
|
84
|
-
instance counts. Read `engine.gpu.limits` for what this device allows.
|
|
85
|
-
|
|
86
|
-
A `Geometry` holds up to 11,184,810 vertices: the most 24-byte vertices (position and normal) one buffer of WebGPU's
|
|
87
|
-
default 256 MiB `maxBufferSize` holds, so a geometry that loads draws on every device. Its index buffer must fit the
|
|
88
|
-
device's `maxBufferSize` too (67,108,864 indices on a default device).
|
|
89
|
-
|
|
90
|
-
Growing keeps the old buffers until the new ones exist, so for that moment a batch holds both. A `Renderer` passed as
|
|
91
|
-
`fallback` must do the same: `add` on a geometry it already holds replaces the storage, new first, and a throw keeps the
|
|
92
|
-
old one. WebGPU reports a real out-of-memory later, as a device error on the next frame, not as a throw from this call.
|
|
93
|
-
|
|
94
|
-
`scene.dispose()` and `engine.dispose()` finish even when a plugin's `dispose` throws, then throw the first error.
|
|
95
|
-
`rebootDevice()` tells every plugin through `onDeviceRestored` the same way.
|
|
96
|
-
|
|
97
|
-
A `rebootDevice()` that fails leaves the engine and the canvas on the device they had, so on a healthy device the page
|
|
98
|
-
keeps drawing and you can try again. The canvas moves to the new device only once every geometry is rebuilt on it.
|
|
99
|
-
`engine.dispose()` ends a restore in flight at its next startup step: `rebootDevice()` rejects with `MargoError` code
|
|
100
|
-
`disposed`, the device it asked for is destroyed, and an automatic restore stops without a report.
|
|
101
|
-
|
|
102
|
-
Core restores a lost device by itself at most 3 times in a row. A fourth loss before 120 frames have drawn since the
|
|
103
|
-
last one reports `MargoError` code `failed` (`GPU lost 4 times; reload the page`) through `engine.onError` once, and
|
|
104
|
-
core asks for no new device after that, so a driver that keeps resetting cannot hold the page in a restore loop. 120
|
|
105
|
-
drawn frames after a restore give the 3 restores back.
|
|
106
|
-
|
|
107
|
-
A camera update that throws (a field of view or clip planes that give no finite float32 frustum) keeps the matrix
|
|
108
|
-
and planes of the last good update, so the next frame still culls and draws with a valid camera.
|
|
109
|
-
|
|
110
|
-
## Camera for one render
|
|
111
|
-
|
|
112
|
-
`engine.render({camera: anotherCamera, delta: 0})` draws the implicit scene through that camera. The camera supplied to `Engine.create` remains `engine.camera`; its fit animation does not advance during the alternate render. Before returning, core restores the primary camera's frustum, visible instances and batches, including when a pass throws. `engine.stats` keeps the counts of the frame it drew: an app that passes its own camera every frame reads what is on screen, package draws included. A pick changes neither count. Plugins receive one pre-update callback per call. A later ordinary render or pick uses the primary camera.
|
|
113
|
-
|
|
114
|
-
Alternate renders must be sequential, outside a running frame pass. For several cameras in one frame use views (below). Camera-dependent plugins that read `engine.camera` in their update callbacks still follow the primary camera. Use `delta: 0` for additional views so simulation is not advanced again. Projection aspect follows the canvas; an offscreen capture with another aspect needs an explicit `Camera.project` override.
|
|
115
|
-
|
|
116
|
-
## Views and scenes
|
|
117
|
-
|
|
118
|
-
Several cameras in one frame: split screen, a four-view layout, a minimap. Each view is a camera and a rectangle,
|
|
119
|
-
fractions of the canvas by default (`pixels: true` for drawing-buffer pixels); the camera aspect follows the rectangle.
|
|
120
|
-
|
|
121
|
-
```ts
|
|
122
|
-
const top = new Camera({ position: [0, 20, 0], target: [0, 0, 0] });
|
|
123
|
-
top.up = [0, 0, -1]; // straight down needs another screen-up
|
|
124
|
-
const front = new Camera({ position: [0, 0, 20] });
|
|
125
|
-
const side = new Camera({ position: [20, 0, 0] });
|
|
126
|
-
engine.views = [
|
|
127
|
-
{ camera: top, viewport: [0, 0, 0.5, 0.5], clear: { color: '#20242a' } },
|
|
128
|
-
{ camera: front, viewport: [0.5, 0, 0.5, 0.5] },
|
|
129
|
-
{ camera: side, viewport: [0, 0.5, 0.5, 0.5] },
|
|
130
|
-
{ camera: engine.camera, viewport: [0.5, 0.5, 0.5, 0.5] },
|
|
131
|
-
]; // the frame loop draws these instead of the full-canvas view
|
|
132
|
-
engine.render({ views: engine.views, delta: 0 }); // or draw them yourself
|
|
133
|
-
const hit = await engine.pick(400, 300); // CSS pixel; picks through the view under it
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
- Views draw in order; the first clears colour, later ones keep it (`clear: {color, depth}` per view). Plugins update
|
|
137
|
-
once per scene and each camera advances once per frame. Partial rectangles clear with a draw inside the rectangle.
|
|
138
|
-
- `PassContext.view` (`id`, `camera`, `viewport`, `scissor`, `index`, `count`, `clear`, `layers`) tells passes which
|
|
139
|
-
view they draw; `draw()` uses its rectangles by default and effects key per-view history on `id`.
|
|
140
|
-
- `target: {color, depth?}` draws a view into textures (sized by the texture) instead of the canvas. `color` is
|
|
141
|
-
1-sample; `depth`, if given, has the scene's depth format and sample count (core draws into it; another format throws).
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
`
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
`
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
```
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
```
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
```
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
```
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
depth.
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
const engine = await Engine.create(
|
|
452
|
-
|
|
453
|
-
engine
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
1
|
+
# @margoengine/core
|
|
2
|
+
|
|
3
|
+
Import `margoengine/core` from the `margoengine` package, or `@margoengine/core` 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
|
+
WebGPU rendering (WebGL2 fallback via the optional `@margoengine/webgl2-compat/preview`), a deterministic Rust/Wasm transform kernel, instanced drawing of one directional GGX light on position and normal, reversed float depth and picking. Materials are color, roughness, and metalness.
|
|
6
|
+
|
|
7
|
+
Desktop scenes use 4× MSAA with a canvas DPR cap of 1; phones use single-sample rendering with a DPR cap of 2. For slower desktop GPUs, set `globalThis.margoLow` to a pixel ratio (for example `1` or `1.5`) before creating the engine: scenes then render single-sampled with the DPR capped at that value, which on an Intel Arc 140V laptop cut the island demo's GPU frame from about 20 to 10 ms (particles off) compared with 4× MSAA. The site demos choose this light tier by measuring the GPU rather than guessing from the device. Color and depth targets follow canvas resize. Optional scene captures retain that sampling policy and expose single-sample resolved textures. CSS layout and HTML text retain native density.
|
|
8
|
+
|
|
9
|
+
`engine.pick(x, y)` updates scene state without forcing a color frame. One readback runs at a time and overlapping calls wait their turn, so a loop of picks costs one readback a point. A pick asked for during a frame starts after it, and one asked for inside a pick (a plugin's `onPreUpdate` picking for a hover) waits behind it instead of nesting. Meshes created or removed elsewhere during a readback leave its answer standing; only a mesh created after the pick started (one that took the hit slot) is answered as null; `pickMany` of `@margoengine/selection` answers many points from one. For cached forward-pass IDs, instance culling in a 3×3 micro frustum and neighbor resolution, attach the optional `Picking` plugin from `@margoengine/selection`. On a canvas without client size (an `OffscreenCanvas` in a worker) pick coordinates are canvas pixels.
|
|
10
|
+
|
|
11
|
+
Static scenes cost little per frame: the kernel recomputes only entities whose position, rotation, scale, parent, bounds or visibility changed (and their descendants); the engine reuses last frame's instance list unless the mesh set, a geometry or material assignment, a material's values or the layers changed; a mesh that culling or `visible` shows or hides moves one row of its batch (shown: the batch's next row; hidden: the batch's last row takes its place), a moved mesh rewrites its own row, and the WebGPU renderer uploads only the changed rows, one `writeBuffer` for each run of neighbouring rows. On an Intel Arc 140V laptop the kernel part made the kernel 2.6-4x cheaper and let 50,000 CAD parts orbit at 92 FPS instead of 49 (CAD measurements, before the row change). An orbiting camera no longer re-collects every frame: with 50,000 boxes and 500 culling flips a frame, the frame does 50,000 byte compares, 1,000 map lookups, 12,000 float copies and uploads 48 KB in at most 500 writes, where it did 100,000 lookups, 1.2 million float copies and a 4.8 MB upload (counted in `tests/core-instance-cache.test.js`; not timed yet). Several cameras on one scene flip most rows, and then cost what a full collection costs. Draw order among the instances of one geometry follows these row moves, so it changes after a flip; opaque pixels are the same except for two core meshes at exactly the same depth. Contract for `@margoengine/core/extension` users: the per-geometry instance buffers (`engine.geometryBuffers(geometry).instance`) belong to core and are read-only for packages (bind them, never write them, except a package that claims a batch and uploads its changed rows with `uploadRows`, see "Bulk poses and instance rows"; use your own buffer, as `@margoengine/selection`'s micro pick pass does), and `store.matrices` is kernel output (change transforms through the mesh, never by writing world matrices). GPU culling of core meshes (`@margoengine/culling`'s `CulledMeshes`) uses one hook: passes see the frame's batches as `context.batches`, and a package may set `batch.redirect = {instances, args}` for the frame; every core draw of that batch (main pass and replays) then reads the package's compacted instance records and `drawIndexedIndirect` arguments instead of core's buffer and count. Core still uploads into its own instance buffer, which stays the read-only source the package culls from. `engine.start({culling: false})` skips core's CPU frustum test in the built-in loop (as `render({culling: false})` does for one frame) when a package culls on the GPU.
|
|
12
|
+
|
|
13
|
+
Entity capacity grows on demand: `Engine.create(canvas, {capacity})` sets the initial number of slots (default 1,024) and `createMesh` doubles the transform store when it is full, up to 8,388,608 (2^23). Growing re-creates the kernel at the same Wasm address, re-binds every `store` view and `mesh.matrix`, and recomputes every entity once on the next tick; a growth that cannot allocate throws and leaves the store unchanged. Store views and `mesh.matrix` taken before a `createMesh` may be stale afterwards (detached, or aliasing the new layout): re-read them, never keep them. Memory per slot: 344 B of kernel columns plus 7 B of flags (351 B; 352 MB of Wasm memory at 1,048,576 slots) and 5 B in the engine; each drawn instance adds 96 B on the CPU and 96 B on the GPU.
|
|
14
|
+
|
|
15
|
+
Mesh `position`, `rotation` and `scale` are retained live refs. Replacing one throws
|
|
16
|
+
`TypeError` with code `transform`: `Retained vector: use a transform setter`, followed by the help link.
|
|
17
|
+
Use `.set(x, y, z)`, `.setAll(value)`, individual components, or the mesh setters:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { Engine } from '@margoengine/core';
|
|
21
|
+
|
|
22
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
23
|
+
const mesh = engine.createMesh();
|
|
24
|
+
mesh.position.set(1, 2, 3);
|
|
25
|
+
mesh.setRotation([0, Math.PI / 2, 0]);
|
|
26
|
+
mesh.scale.setAll(2);
|
|
27
|
+
engine.render();
|
|
28
|
+
engine.dispose();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Camera `position`, `target` and `up` are tuple values and remain assignable.
|
|
32
|
+
|
|
33
|
+
Camera controls are not in core: `CADCameraControls` is in `@margoengine/stage` (since 2026-11-07), and `@margoengine/controls` has orbit, map, fly and the rest.
|
|
34
|
+
|
|
35
|
+
Package name: `@margoengine/core`, version `1.0.0`. Build from source or install a local tarball until the package is published.
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { Camera, Engine, box, PbrMaterial } from 'margoengine/core';
|
|
39
|
+
|
|
40
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
41
|
+
const engine = await Engine.create(canvas, { backend: 'auto' });
|
|
42
|
+
const mesh = engine.createMesh()
|
|
43
|
+
.setGeometry(box())
|
|
44
|
+
.setMaterial(new PbrMaterial({ color: '#84d6bd', roughness: 0.3 }));
|
|
45
|
+
engine.onFrame((_, delta) => { mesh.rotation.y += delta; });
|
|
46
|
+
engine.start();
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`Engine.create(canvas, options)` options (all optional, all part of the v1.0.0 API):
|
|
50
|
+
|
|
51
|
+
| Option | Default | Meaning |
|
|
52
|
+
| --- | --- | --- |
|
|
53
|
+
| `capacity` | `1024` | Initial mesh slots, 1 to 8,388,608; the store doubles when full. |
|
|
54
|
+
| `backend` | `'auto'` | `'auto'` tries WebGPU, then `fallback`; `'webgpu'` fails without WebGPU; `'webgl2'` uses `fallback`. |
|
|
55
|
+
| `camera` | `Camera` defaults | Initial camera settings (`position`, `target`, `fov`, ...). |
|
|
56
|
+
| `fallback` | none | Builds the non-WebGPU renderer, for example `webglRenderer` from `@margoengine/webgl2-compat/preview`. |
|
|
57
|
+
| `features` | `[]` | Extra WebGPU features to request when the adapter offers them, such as `['timestamp-query']`. |
|
|
58
|
+
| `exactSize` | `false` | `[width, height]` or `true`: pixel-exact backbuffer with no pixel-ratio scaling and no MSAA ([Pixel-perfect rendering](#pixel-perfect-rendering)). |
|
|
59
|
+
| `antialias` | `true`, `false` with `exactSize` | MSAA of the scene: `true` is the quality tier's samples (4 on desktop, 1 on phones and the light tier), `false` 1. With `exactSize` it gives a fixed-size frame with MSAA ([Fixed-size frames with MSAA](#fixed-size-frames-with-msaa)). |
|
|
60
|
+
| `signal` | none | An `AbortSignal` that cancels creation; it rejects with the signal's reason and never falls back ([Startup that never finishes](#startup-that-never-finishes)). |
|
|
61
|
+
| `startupWarning` | `8000` | Milliseconds a startup step may take before one `console.warn` names it. |
|
|
62
|
+
| `startupTimeout` | `30000` | Milliseconds before a startup step that never settles rejects with a `timeout` error. |
|
|
63
|
+
| `powerPreference` | unset | `'low-power'` or `'high-performance'`; unset asks for `'high-performance'`, and for nothing on Windows ([Choosing the GPU](#choosing-the-gpu)). |
|
|
64
|
+
|
|
65
|
+
`delta` is in seconds. The built-in loop clamps a long frame to `engine.maxDelta` (default `0.1`; keep it at 1 or less, since `render` rejects a larger delta with a RangeError), and when the page becomes visible again after a background tab its first frame steps `0`, so animation and physics resume where they paused instead of jumping.
|
|
66
|
+
|
|
67
|
+
Materials are live: `material.set({ color: '#ff8800', roughness: 0.2, metalness: 1, doubleSided: false })` changes the given values in place (omitted ones keep theirs; invalid input throws and changes nothing). Every mesh using the material shows it on the next frame with no new pipeline or bind group. A value change re-collects the frame's instances, so each drawn geometry's whole instance range is uploaded once on that frame (only changed ranges after that); for per-frame recolouring of one part among many thousands, give that part its own material or use `@margoengine/materials`. Core materials are opaque (no `opacity`).
|
|
68
|
+
|
|
69
|
+
Back faces of single-sided materials (`doubleSided: false`) are culled by the GPU: core draws a geometry batch with a second, back-culled pipeline whose shader has no `discard` (so early depth testing stays on) when every drawn instance of that geometry is single-sided and not mirrored (negative-determinant transform). One double-sided or mirrored instance puts the whole batch on the cull-none pipeline, which drops back faces in the shader as before; pixels are the same either way. Flipping `doubleSided` with `material.set`, assigning a material, or mirroring a mesh takes effect on the next frame; un-mirroring a moved mesh moves its batch back to the culled pipeline at the next full re-collection. Passes that replace core's shader text (fog, clipping, clustered lights...) or draw with extra bindings keep the cull-none pipeline. Instance records carry `Batch.mask` for packages: nonzero when the batch needs back faces.
|
|
70
|
+
|
|
71
|
+
`mesh.receiveShadow = false` (default true) keeps a mesh's direct light unshadowed by `@margoengine/shadows` and clustered local shadows while it still casts; the next frame re-collects instances. Core marks it by adding 0.25 to the instance's doubleSided factor (float 22), so every `< 0.5` single-sided test reads it unchanged; the shadow packages patch core's shader for it only while some mesh opts out.
|
|
72
|
+
|
|
73
|
+
The canvas is opaque. For a transparent canvas over HTML and CSS, attach `TransparentCanvas` from `@margoengine/environment`; core needs no option.
|
|
74
|
+
|
|
75
|
+
## When an allocation fails
|
|
76
|
+
|
|
77
|
+
`mesh.setGeometry()` allocates a geometry's GPU buffers the first time a mesh uses it, and larger instance storage as more
|
|
78
|
+
meshes share it. If that throws, for example `GPU buffer limit` from a geometry bigger than `maxBufferSize`, nothing has
|
|
79
|
+
changed: the error reaches you, the mesh keeps the geometry it had and keeps drawing it, every other mesh draws as before,
|
|
80
|
+
and calling again once there is room works. `engine.createMesh()` does the same when the transform store cannot grow.
|
|
81
|
+
|
|
82
|
+
Core asks the adapter for its own `maxBufferSize` and `maxStorageBufferBindingSize` (at creation and on every device
|
|
83
|
+
restore), not WebGPU's 256 MiB and 128 MiB defaults, so a desktop GPU's larger buffers are there for big meshes and
|
|
84
|
+
instance counts. Read `engine.gpu.limits` for what this device allows.
|
|
85
|
+
|
|
86
|
+
A `Geometry` holds up to 11,184,810 vertices: the most 24-byte vertices (position and normal) one buffer of WebGPU's
|
|
87
|
+
default 256 MiB `maxBufferSize` holds, so a geometry that loads draws on every device. Its index buffer must fit the
|
|
88
|
+
device's `maxBufferSize` too (67,108,864 indices on a default device).
|
|
89
|
+
|
|
90
|
+
Growing keeps the old buffers until the new ones exist, so for that moment a batch holds both. A `Renderer` passed as
|
|
91
|
+
`fallback` must do the same: `add` on a geometry it already holds replaces the storage, new first, and a throw keeps the
|
|
92
|
+
old one. WebGPU reports a real out-of-memory later, as a device error on the next frame, not as a throw from this call.
|
|
93
|
+
|
|
94
|
+
`scene.dispose()` and `engine.dispose()` finish even when a plugin's `dispose` throws, then throw the first error.
|
|
95
|
+
`rebootDevice()` tells every plugin through `onDeviceRestored` the same way.
|
|
96
|
+
|
|
97
|
+
A `rebootDevice()` that fails leaves the engine and the canvas on the device they had, so on a healthy device the page
|
|
98
|
+
keeps drawing and you can try again. The canvas moves to the new device only once every geometry is rebuilt on it.
|
|
99
|
+
`engine.dispose()` ends a restore in flight at its next startup step: `rebootDevice()` rejects with `MargoError` code
|
|
100
|
+
`disposed`, the device it asked for is destroyed, and an automatic restore stops without a report.
|
|
101
|
+
|
|
102
|
+
Core restores a lost device by itself at most 3 times in a row. A fourth loss before 120 frames have drawn since the
|
|
103
|
+
last one reports `MargoError` code `failed` (`GPU lost 4 times; reload the page`) through `engine.onError` once, and
|
|
104
|
+
core asks for no new device after that, so a driver that keeps resetting cannot hold the page in a restore loop. 120
|
|
105
|
+
drawn frames after a restore give the 3 restores back.
|
|
106
|
+
|
|
107
|
+
A camera update that throws (a field of view or clip planes that give no finite float32 frustum) keeps the matrix
|
|
108
|
+
and planes of the last good update, so the next frame still culls and draws with a valid camera.
|
|
109
|
+
|
|
110
|
+
## Camera for one render
|
|
111
|
+
|
|
112
|
+
`engine.render({camera: anotherCamera, delta: 0})` draws the implicit scene through that camera. The camera supplied to `Engine.create` remains `engine.camera`; its fit animation does not advance during the alternate render. Before returning, core restores the primary camera's frustum, visible instances and batches, including when a pass throws. `engine.stats` keeps the counts of the frame it drew: an app that passes its own camera every frame reads what is on screen, package draws included. A pick changes neither count. Plugins receive one pre-update callback per call. A later ordinary render or pick uses the primary camera.
|
|
113
|
+
|
|
114
|
+
Alternate renders must be sequential, outside a running frame pass. For several cameras in one frame use views (below). Camera-dependent plugins that read `engine.camera` in their update callbacks still follow the primary camera. Use `delta: 0` for additional views so simulation is not advanced again. Projection aspect follows the canvas; an offscreen capture with another aspect needs an explicit `Camera.project` override.
|
|
115
|
+
|
|
116
|
+
## Views and scenes
|
|
117
|
+
|
|
118
|
+
Several cameras in one frame: split screen, a four-view layout, a minimap. Each view is a camera and a rectangle,
|
|
119
|
+
fractions of the canvas by default (`pixels: true` for drawing-buffer pixels); the camera aspect follows the rectangle.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const top = new Camera({ position: [0, 20, 0], target: [0, 0, 0] });
|
|
123
|
+
top.up = [0, 0, -1]; // straight down needs another screen-up
|
|
124
|
+
const front = new Camera({ position: [0, 0, 20] });
|
|
125
|
+
const side = new Camera({ position: [20, 0, 0] });
|
|
126
|
+
engine.views = [
|
|
127
|
+
{ camera: top, viewport: [0, 0, 0.5, 0.5], clear: { color: '#20242a' } },
|
|
128
|
+
{ camera: front, viewport: [0.5, 0, 0.5, 0.5] },
|
|
129
|
+
{ camera: side, viewport: [0, 0.5, 0.5, 0.5] },
|
|
130
|
+
{ camera: engine.camera, viewport: [0.5, 0.5, 0.5, 0.5] },
|
|
131
|
+
]; // the frame loop draws these instead of the full-canvas view
|
|
132
|
+
engine.render({ views: engine.views, delta: 0 }); // or draw them yourself
|
|
133
|
+
const hit = await engine.pick(400, 300); // CSS pixel; picks through the view under it
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- Views draw in order; the first clears colour, later ones keep it (`clear: {color, depth}` per view). Plugins update
|
|
137
|
+
once per scene and each camera advances once per frame. Partial rectangles clear with a draw inside the rectangle.
|
|
138
|
+
- `PassContext.view` (`id`, `camera`, `viewport`, `scissor`, `index`, `count`, `clear`, `layers`) tells passes which
|
|
139
|
+
view they draw; `draw()` uses its rectangles by default and effects key per-view history on `id`.
|
|
140
|
+
- `target: {color, depth?}` draws a view into textures (sized by the texture) instead of the canvas. `color` is
|
|
141
|
+
1-sample; `depth`, if given, has the scene's depth format and sample count (core draws into it; another format throws).
|
|
142
|
+
The texture holds display colour, as the canvas does. An `-srgb` colour texture names its non-srgb twin in
|
|
143
|
+
`viewFormats` (`device.createTexture({format: 'rgba8unorm-srgb', viewFormats: ['rgba8unorm'], ...})`): core draws
|
|
144
|
+
through a view in that format, so the colour is encoded once and sampling the texture returns linear light.
|
|
145
|
+
- `layers` draws only the meshes whose render layers (`@margoengine/cameras/layers`) share a bit; default the camera's.
|
|
146
|
+
- Scenes: `engine.createScene()` makes a scene with its own meshes (`scene.createMesh()`), lighting, `background` and
|
|
147
|
+
plugins (`scene.use(plugin)`); a view draws it with `scene`. `engine.scene` is the default scene; while a scene is
|
|
148
|
+
drawn or set up, `engine.lighting`, `plugins`, `stats` and `createMesh` are that scene's. `scene.dispose()` removes it.
|
|
149
|
+
A `background` is an sRGB colour (`#rgb` or `#rrggbb`); any other value, such as an `[r, g, b]` array or a number,
|
|
150
|
+
makes the next render throw a `RangeError`. The canvas shows it as given. Under a post effect that
|
|
151
|
+
captures the scene in linear light (tone mapping, bloom) it is light in the scene, tone-mapped with the meshes:
|
|
152
|
+
`#808080` shows as 116 under the default tone map.
|
|
153
|
+
With no `background` core clears to its own dark colour (5,6,9 on the canvas), which takes the same path: 0,1,4
|
|
154
|
+
under the default tone map, as a `#050609` background.
|
|
155
|
+
- Which packages are view-aware: [multi-view-roadmap.md](../../docs/multi-view-roadmap.md).
|
|
156
|
+
|
|
157
|
+
## Camera, geometry, materials and picking
|
|
158
|
+
|
|
159
|
+
Every setting has a default, so `new Camera()`, `box()` and `new PbrMaterial()` are valid as they stand.
|
|
160
|
+
|
|
161
|
+
| Call | Settings and defaults |
|
|
162
|
+
| --- | --- |
|
|
163
|
+
| `new Camera(options)` or the `camera` engine option | `fov` 60 (degrees), `position` `[0, 2, 5]`, `target` `[0, 0, 0]`, `near` 0.1, `far` 1000. `up` defaults to `[0, 1, 0]`. |
|
|
164
|
+
| `box(width, height, depth)` | 1 world unit each, centred on the origin; a size that is not finite and positive throws `RangeError`. |
|
|
165
|
+
| `new PbrMaterial(options)` | `color` `'#4f46e5'`, `roughness` 0.5, `metalness` 0, `doubleSided` true. |
|
|
166
|
+
| `engine.pick(x, y)` | CSS pixels; resolves to the mesh under that point, or `null`. |
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { Camera, Engine, PbrMaterial, box } from '@margoengine/core';
|
|
170
|
+
|
|
171
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
172
|
+
const engine = await Engine.create(canvas, {
|
|
173
|
+
camera: { fov: 50, position: [0, 3, 8], target: [0, 1, 0], near: 0.1, far: 200 },
|
|
174
|
+
});
|
|
175
|
+
const crate = engine.createMesh()
|
|
176
|
+
.setGeometry(box(2, 1, 1))
|
|
177
|
+
.setMaterial(new PbrMaterial({ color: '#c0792b', roughness: 0.8, metalness: 0, doubleSided: false }));
|
|
178
|
+
crate.position.set(0, 0.5, 0);
|
|
179
|
+
engine.render();
|
|
180
|
+
const hit = await engine.pick(canvas.clientWidth / 2, canvas.clientHeight / 2); // a Mesh or null
|
|
181
|
+
console.log(hit === crate, engine.camera instanceof Camera);
|
|
182
|
+
engine.dispose();
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
A scale of 0 on an axis is valid (glTF 2.0 section 3.5.3): `mesh.setScale([1, 0, 1])` flattens the mesh onto a plane
|
|
186
|
+
that is lit like its surviving normal axis, and `setScale([0, 0, 0])` draws nothing, for example to hide a node or to
|
|
187
|
+
start a pop-in animation. Normals stay finite; a value that is not finite as float32 still throws `RangeError`.
|
|
188
|
+
|
|
189
|
+
## Bulk poses and instance rows (extension)
|
|
190
|
+
|
|
191
|
+
`engine.writePoses(ids, poses, count?)` sets the position and rotation of many meshes in one call: row k of `poses`
|
|
192
|
+
holds `x y z qx qy qz qw` for mesh `ids[k]`, relative to its parent as `setPosition` is, and every value lands with the
|
|
193
|
+
bits `setPosition` and `setQuaternion` would give it, Euler angles included (the quaternion is normalised). It checks
|
|
194
|
+
every row before it writes any: `Error: Mesh disposed` for an id with no live mesh, `RangeError: Invalid transform: k`
|
|
195
|
+
for a value that is not finite as float32 and `RangeError: Quaternion nonzero: k` for four zeros. It looks no mesh up,
|
|
196
|
+
so drop the ids of meshes you dispose (a freed id goes to the next new mesh). `count` defaults to `ids.length`. A
|
|
197
|
+
`Float64Array` keeps the bits of numbers you computed in doubles; `@margoengine/physics` writes its awake bodies this way.
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
import { Engine, box } from '@margoengine/core/extension';
|
|
201
|
+
|
|
202
|
+
const canvas = document.querySelector('canvas')!;
|
|
203
|
+
const engine = await Engine.create(canvas);
|
|
204
|
+
const meshes = Array.from({ length: 100 }, () => engine.createMesh().setGeometry(box(0.2)));
|
|
205
|
+
const ids = Int32Array.from(meshes, (mesh) => mesh.id);
|
|
206
|
+
const poses = new Float64Array(meshes.length * 7);
|
|
207
|
+
const clock = new Float64Array(1);
|
|
208
|
+
engine.onFrame((_, delta) => {
|
|
209
|
+
clock[0] += delta;
|
|
210
|
+
for (let k = 0; k < meshes.length; k++) {
|
|
211
|
+
const angle = clock[0] + k * 0.1;
|
|
212
|
+
poses[k * 7] = Math.cos(angle) * 3; // x y z
|
|
213
|
+
poses[k * 7 + 1] = (k - 50) * 0.05;
|
|
214
|
+
poses[k * 7 + 2] = Math.sin(angle) * 3;
|
|
215
|
+
poses[k * 7 + 4] = Math.sin(angle / 2); // qx qy qz qw: a turn about y
|
|
216
|
+
poses[k * 7 + 6] = Math.cos(angle / 2);
|
|
217
|
+
}
|
|
218
|
+
engine.writePoses(ids, poses);
|
|
219
|
+
});
|
|
220
|
+
engine.start();
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Each batch keeps the rows it changed since its last upload: bit r of `batch.rows` is set for row r, and `batch.dirty`
|
|
224
|
+
counts them (-1: every row). `uploadRows(queue, buffer, batch, all?)` writes those rows into a GPU buffer, one
|
|
225
|
+
`writeBuffer` for each run of neighbouring rows up to `batch.count`, and clears them. Core calls it for the batches it
|
|
226
|
+
draws; a package that sets `batch.claimed` and draws a batch itself calls it into core's instance buffer, with `all`
|
|
227
|
+
the first time and after a device restore:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
import { Engine, box, uploadRows } from '@margoengine/core/extension';
|
|
231
|
+
|
|
232
|
+
const canvas = document.querySelector('canvas')!;
|
|
233
|
+
const engine = await Engine.create(canvas);
|
|
234
|
+
const geometry = box();
|
|
235
|
+
engine.createMesh().setGeometry(geometry);
|
|
236
|
+
let sent = false;
|
|
237
|
+
engine.use({
|
|
238
|
+
name: 'own-draw',
|
|
239
|
+
setup() {},
|
|
240
|
+
onDeviceRestored() {
|
|
241
|
+
sent = false;
|
|
242
|
+
},
|
|
243
|
+
registerPasses(graph) {
|
|
244
|
+
graph.add({
|
|
245
|
+
name: 'own-draw:claim',
|
|
246
|
+
order: -1,
|
|
247
|
+
execute(context) {
|
|
248
|
+
if (context.backend !== 'webgpu') return;
|
|
249
|
+
const batch = context.batches?.find((b) => b.geometry === geometry);
|
|
250
|
+
if (!batch) return;
|
|
251
|
+
batch.claimed = true; // core no longer draws it, or uploads it
|
|
252
|
+
uploadRows(context.device.queue, engine.geometryBuffers(geometry)!.instance, batch, !sent);
|
|
253
|
+
sent = true;
|
|
254
|
+
// Draw batch.count instances from that buffer in a pass of your own here.
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
engine.start();
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
## Pixel-perfect rendering
|
|
263
|
+
|
|
264
|
+
By default the backbuffer follows the canvas's CSS size times the device pixel ratio (at most 2, and at most the device's
|
|
265
|
+
`maxTextureDimension2D` per side, 8192 on a default WebGPU device and 4096 for a fallback renderer, both sides scaled
|
|
266
|
+
together so the aspect ratio holds) and desktop scenes use 4x MSAA. Pixel art and pixel-perfect 2D need the opposite, so `exactSize` turns both off:
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
import { Engine } from '@margoengine/core';
|
|
270
|
+
|
|
271
|
+
const canvas = document.querySelector('canvas')!;
|
|
272
|
+
const engine = await Engine.create(canvas, { exactSize: [320, 180] }); // or `true`: keep canvas.width / height
|
|
273
|
+
canvas.style.width = `${320 * 4}px`; // integer zoom
|
|
274
|
+
canvas.style.height = `${180 * 4}px`;
|
|
275
|
+
canvas.style.imageRendering = 'pixelated'; // nearest-neighbour scaling, no blur
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
- The backbuffer is exactly the requested size, with no pixel-ratio scaling; change `canvas.width` and `canvas.height`
|
|
279
|
+
to resize it.
|
|
280
|
+
- Scenes are single-sampled (no MSAA). Packages that build their own pipelines read `sceneSamples(engine)`, so they
|
|
281
|
+
match.
|
|
282
|
+
- `engine.pick(x, y)` still takes CSS pixels and maps them to backbuffer pixels.
|
|
283
|
+
- The WebGL2 fallback keeps its own context antialiasing; pass `exactSize` to WebGPU engines.
|
|
284
|
+
|
|
285
|
+
## Fixed-size frames with MSAA
|
|
286
|
+
|
|
287
|
+
A film or capture at an exact resolution wants the fixed backbuffer of `exactSize` but antialiased edges. Add
|
|
288
|
+
`antialias: true`: the backbuffer stays the requested size and the scene draws with the quality tier's 4x MSAA.
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
import { Engine } from '@margoengine/core';
|
|
292
|
+
|
|
293
|
+
const canvas = document.querySelector('canvas')!;
|
|
294
|
+
const engine = await Engine.create(canvas, { exactSize: [1920, 1080], antialias: true });
|
|
295
|
+
canvas.style.width = '100%'; // the CSS size never changes the 1920 x 1080 backbuffer
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
- `sceneSamples(engine)` is 4 on desktop, so packages with their own pipelines match; phones and the light tier stay
|
|
299
|
+
at 1 sample.
|
|
300
|
+
- `antialias: false` without `exactSize` draws single-sampled at the normal CSS-times-pixel-ratio size; with one sample
|
|
301
|
+
the pixel ratio may go up to 2 on desktop too.
|
|
302
|
+
|
|
303
|
+
## Startup that never finishes
|
|
304
|
+
|
|
305
|
+
`Engine.create` waits for the browser at four steps: `requestAdapter`, `requestDevice` and two pipeline compiles. Some
|
|
306
|
+
drivers never answer one of them: on an Intel Arc 140V, with 3 or 4 WebGPU pages alive at once in one browser process,
|
|
307
|
+
each new page got slower to get a device and the 4th never did, with no error. So each step has a time limit:
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
import { Engine } from '@margoengine/core';
|
|
311
|
+
|
|
312
|
+
const canvas = document.querySelector('canvas')!;
|
|
313
|
+
const engine = await Engine.create(canvas, {
|
|
314
|
+
signal: AbortSignal.timeout(60_000), // cancel creation yourself (here after 60 s); rejects with the signal's reason
|
|
315
|
+
startupWarning: 8000, // one console.warn naming the step still pending after 8 s (the default)
|
|
316
|
+
startupTimeout: 30_000, // then reject with MargoError code 'timeout' naming the step (the default)
|
|
317
|
+
}).catch((error) => {
|
|
318
|
+
if (error.code === 'timeout') console.error('The GPU did not answer; close other 3D tabs and reload');
|
|
319
|
+
throw error;
|
|
320
|
+
});
|
|
321
|
+
engine.start();
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
- With `backend: 'auto'` (the default) and a `fallback` (`webglRenderer` from `@margoengine/webgl2-compat/preview`), a `timeout`
|
|
325
|
+
falls back to WebGL2 like any other WebGPU failure; `engine.fallbackReason` says why. An abort never falls back.
|
|
326
|
+
- A device that arrives after the limit is destroyed, not leaked; the warning is printed at most once per step.
|
|
327
|
+
- The cause is the driver, not the page. A page that shows many engines (a gallery) should start them one at a time,
|
|
328
|
+
each after the previous has drawn, and dispose engines that leave the screen.
|
|
329
|
+
|
|
330
|
+
## Choosing the GPU
|
|
331
|
+
|
|
332
|
+
On a laptop with an integrated and a discrete GPU, `powerPreference` picks one: `'low-power'` saves battery,
|
|
333
|
+
`'high-performance'` asks for the discrete GPU. It is asked again when the device is restored.
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
import { Engine } from '@margoengine/core';
|
|
337
|
+
|
|
338
|
+
const canvas = document.querySelector('canvas')!;
|
|
339
|
+
const engine = await Engine.create(canvas, { powerPreference: 'low-power' });
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
- Default: unset. Core then asks for `'high-performance'`, except on Windows, where it asks for nothing.
|
|
343
|
+
- Chrome and Edge on Windows ignore a set value and log a console warning; choose the GPU per browser in Windows
|
|
344
|
+
Settings > System > Display > Graphics there.
|
|
345
|
+
|
|
346
|
+
## Compiling pipelines early
|
|
347
|
+
|
|
348
|
+
`engine.renderTarget` names what a render pipeline must match to draw in the canvas pass: the colour format, the depth
|
|
349
|
+
format and the sample count. An optional package reads it to compile its pipelines before the first frame, as
|
|
350
|
+
`PBRModel.compile()` in `@margoengine/gltf/pbr` does. It is `null` off WebGPU, and it follows a restored device.
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
import { Engine } from '@margoengine/core';
|
|
354
|
+
|
|
355
|
+
const canvas = document.querySelector('canvas')!;
|
|
356
|
+
const engine = await Engine.create(canvas);
|
|
357
|
+
const target = engine.renderTarget; // { format, depthFormat, samples }, or null on the WebGL2 preview
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
## Ambient RGB
|
|
361
|
+
|
|
362
|
+
Extension users can tint core's diffuse ambient independently of the directional light:
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { Engine } from 'margoengine/core';
|
|
366
|
+
import { engineRuntime } from 'margoengine/core/extension';
|
|
367
|
+
|
|
368
|
+
const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
|
|
369
|
+
const engine = await Engine.create(canvas);
|
|
370
|
+
const lighting = engineRuntime(engine).lighting;
|
|
371
|
+
lighting.radiance[3] = 0.2; // existing ambient intensity
|
|
372
|
+
lighting.ambient.set([0.4, 0.6, 1]); // linear RGB multiplier; white by default
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
The three components must be finite and nonnegative; values above one are allowed. Core meshes and packages drawing core's shader use this color. Independent material shaders, including glTF PBR's hemisphere model, retain their existing lighting APIs. Environment IBL replaces core ambient; Sky's explicit ambient color supplies its own absolute floor. This is a flat RGB hook, not a HemisphereLight.
|
|
376
|
+
|
|
377
|
+
Core's display curve is Khronos PBR Neutral, then the exact sRGB encoding: base colours under neutral light come out as authored, and highlights roll off to white. glTF PBR, terrain, sky, water, scatter, foliage and the post effects end with the same curve, so one colour looks the same whichever package draws it; `@margoengine/tonemap` defaults to it and adds AgX, ACES and LUT grading.
|
|
378
|
+
|
|
379
|
+
For packages supplying `Lighting` directly to a renderer, omitted `ambient` means white. The canonical WGSL `Frame` is now 128 bytes: its original 112-byte prefix is unchanged and an `ambient:vec4f` follows it (RGB at floats 28-30). Packages allocating that uniform must supply the full layout; append their own fields after it.
|
|
380
|
+
|
|
381
|
+
## Viewport and scissor per core draw
|
|
382
|
+
|
|
383
|
+
Inside a frame pass, `context.draw` accepts independent rectangles:
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
import type { FramePass } from 'margoengine/core/extension';
|
|
387
|
+
|
|
388
|
+
const leftView: FramePass = {
|
|
389
|
+
name: 'left-view',
|
|
390
|
+
order: 1,
|
|
391
|
+
execute: (context) =>
|
|
392
|
+
context.draw({
|
|
393
|
+
viewport: [0, 0, 160, 240],
|
|
394
|
+
scissor: [0, 0, 160, 240],
|
|
395
|
+
clear: false,
|
|
396
|
+
}),
|
|
397
|
+
};
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Both tuples use top-left drawing-buffer pixels, with nonnegative integer origins and positive integer sizes. Invalid or out-of-bounds rectangles throw before drawing. Custom target owners must set the context dimensions to match their active attachments. Omitted rectangles use the full target and do not retain the preceding draw's state.
|
|
401
|
+
|
|
402
|
+
A pass that opens its own render passes on `color` and `depth` can declare `joins`, and the frame then needs no render pass of core's. Set the attachments to `load` and `store` each frame and call `attach` just before each `beginRenderPass`; `true` means no render pass on them follows in this pass. The first call takes core's clear when core has nothing to draw, and in the graph's last pass the attachments resolve the frame. A pass that draws nothing need do nothing: core clears and resolves as usual.
|
|
403
|
+
|
|
404
|
+
```ts
|
|
405
|
+
import type { FramePass } from 'margoengine/core/extension';
|
|
406
|
+
|
|
407
|
+
const color: GPURenderPassColorAttachment = { view: undefined!, loadOp: 'load', storeOp: 'store' };
|
|
408
|
+
const depth: GPURenderPassDepthStencilAttachment = { view: undefined!, depthLoadOp: 'load', depthStoreOp: 'store' };
|
|
409
|
+
const ownPass: FramePass = {
|
|
410
|
+
name: 'own-pass',
|
|
411
|
+
order: 1,
|
|
412
|
+
joins: true,
|
|
413
|
+
execute(context) {
|
|
414
|
+
if (context.backend !== 'webgpu') return;
|
|
415
|
+
color.view = context.color;
|
|
416
|
+
depth.view = context.depth;
|
|
417
|
+
color.resolveTarget = undefined;
|
|
418
|
+
color.loadOp = depth.depthLoadOp = 'load';
|
|
419
|
+
color.storeOp = depth.depthStoreOp = 'store';
|
|
420
|
+
const stencil = context.descriptor.depthStencil!.format.includes('stencil');
|
|
421
|
+
depth.stencilLoadOp = stencil ? 'load' : undefined;
|
|
422
|
+
depth.stencilStoreOp = stencil ? 'store' : undefined;
|
|
423
|
+
context.attach?.(color, depth, true);
|
|
424
|
+
context.encoder.beginRenderPass({ colorAttachments: [color], depthStencilAttachment: depth }).end();
|
|
425
|
+
},
|
|
426
|
+
};
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
Clearing still clears the whole attachment, regardless of either rectangle. Use `clear:false` for later subviews that must retain color and depth. Rectangles do not change camera aspect or culling, the coordinates used by `engine.pick`, or optional packages that open their own native render passes. WebGL's core-mesh preview supports the same rectangles and clear/load behavior.
|
|
430
|
+
|
|
431
|
+
Call `engine.dispose()` when the canvas is removed, or let `using engine = await Engine.create(canvas)` (and `using mesh = engine.createMesh()`, `using scene = engine.createScene()`) dispose at the end of the block: `[Symbol.dispose]` is `dispose()` where the runtime has the symbol. Disposing twice is harmless.
|
|
432
|
+
|
|
433
|
+
Errors are a `MargoError` with a `code` (or a `TypeError` / `RangeError`) whose short message links to its entry on [margoengine.com/errors](https://margoengine.com/errors).
|
|
434
|
+
|
|
435
|
+
Core geometry holds positions and normals only. For a second UV set (lightmaps, ambient occlusion), vertex colours or tangents on CPU geometry, use `createMesh(engine, {positions, normals, uvs, uvs1, ...}, material)` from `@margoengine/materials`; glTF files keep `TEXCOORD_1` through `@margoengine/gltf/pbr`. For points (point clouds and sprites), use `PointCloud` and `PointsPlugin` from `@margoengine/points`.
|
|
436
|
+
|
|
437
|
+
Wasm is embedded; no Rust toolchain or Wasm bundler plugin is required. The public API is exported from `@margoengine/core`; raw GPU/Wasm access uses the explicit `@margoengine/core/extension` entry. Both entries include TypeScript declarations.
|
|
438
|
+
|
|
439
|
+
TypeScript 7+ with DOM types, Wasm SIMD and DecompressionStream gzip support are required. WebGPU requires HTTPS or localhost. See the API and lifecycle guide and committed measurements and how to reproduce them.
|
|
440
|
+
|
|
441
|
+
Apache-2.0 licensed.
|
|
442
|
+
|
|
443
|
+
## One core per engine: version checks (extension)
|
|
444
|
+
|
|
445
|
+
Every Margo package that reaches into an engine's internals checks first that it was built for the core the engine runs on. Two copies of core in one page (two installs, or one bundled twice) or a package built for another core version would otherwise share an engine whose internals they read differently. The check runs when a package attaches, never on import, and keeps no global state: each engine carries its own record.
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
import {CORE_VERSION, Engine, assertCore, box, coreRequirement, engineRuntime} from 'margoengine/core/extension';
|
|
449
|
+
const canvas = document.createElement('canvas');
|
|
450
|
+
document.body.append(canvas);
|
|
451
|
+
const engine = await Engine.create(canvas);
|
|
452
|
+
console.log(CORE_VERSION, engine.coreRequirement.runtime.version); // 1.0.0 1.0.0
|
|
453
|
+
const runtime = engineRuntime(engine); // the same engine object, checked
|
|
454
|
+
runtime.createMesh().setGeometry(box());
|
|
455
|
+
try {
|
|
456
|
+
assertCore(engine, coreRequirement('0.9.0', 'https://example.test/old-package.js'));
|
|
457
|
+
} catch (error) {
|
|
458
|
+
console.log((error as {code?: string}).code); // version
|
|
459
|
+
}
|
|
460
|
+
engine.use({name: 'tint', coreRequirement: coreRequirement(), setup() {}}); // checked before setup runs
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
- **What is compared.** `CORE_VERSION` is this core's exact version (also exported from `margoengine/core`). Each
|
|
464
|
+
engine records the core module that made it in `engine.coreRequirement.runtime` (`{version, source}`, the module's
|
|
465
|
+
URL). A requirement is `{version, source, runtime}`: the version a package was built for, the package's URL, and the
|
|
466
|
+
core module the package itself loaded. `assertCore(engine, requirement)` passes only when all three versions agree
|
|
467
|
+
and the package's core module is the very object that made the engine, so two installs of the same version are
|
|
468
|
+
caught too. With no requirement it checks against the core you imported it from.
|
|
469
|
+
- **On failure** it throws MargoError `'version'` naming both cores and the package, with the help link
|
|
470
|
+
https://margoengine.com/errors#version. The cure is one core: dedupe or rebuild the packages against the same core
|
|
471
|
+
build (`npm ls @margoengine/core` shows the copies). Do not catch and continue; the check guards the engine's memory
|
|
472
|
+
layout.
|
|
473
|
+
- **Where it runs.** `engineRuntime(engine)` checks and returns the engine itself, typed as the runtime `Engine`;
|
|
474
|
+
`engine.use(plugin)` checks a plugin's `coreRequirement` before its `setup`. Each package build stamps its own core
|
|
475
|
+
version and URL into its `engineRuntime` calls and into each plugin class or object with a `setup`
|
|
476
|
+
(`scripts/core-requirements.mjs`), so packages need no code for it; your own plugins and extensions can pass
|
|
477
|
+
`coreRequirement()` as above.
|
|
478
|
+
- **Stand-ins.** An `EngineKernel` without `coreRequirement` (a test double or a custom engine) passes unchecked, as
|
|
479
|
+
there is no core registry to conflict with.
|
|
480
|
+
|
|
481
|
+
## Content Security Policy
|
|
482
|
+
|
|
483
|
+
Creating the engine compiles core's embedded Rust transform kernel, so restricted pages need `'wasm-unsafe-eval'` in `script-src`. A stage creates that same engine. Every Margo engine page under a strict CSP needs this permission. A blocked compile or instantiate rejects with MargoError code `failed`, its original cause and a link to the CSP docs. Imports alone do not compile Wasm. See [the exact header and package requirements](../../docs/csp.md).
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
`new Geometry([], [], [])` is a valid empty mesh with bounds [0,0,0,0]. It creates
|
|
487
|
+
no renderer buffers or batches and draws nothing, including when several scene
|
|
488
|
+
nodes share it. Replace its geometry normally after refilling an editor model;
|
|
489
|
+
node identity, transform and material survive. All three input arrays must be
|
|
490
|
+
empty together. Partial inputs keep the existing argument errors. An empty
|
|
491
|
+
geometry has no GPU buffers, so extension `geometryBuffers(empty)` returns null.
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
import {Engine, Geometry, box} from '@margoengine/core';
|
|
495
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
496
|
+
const mesh = engine.createMesh().setGeometry(new Geometry([], [], []));
|
|
497
|
+
engine.render();
|
|
498
|
+
mesh.setGeometry(box());
|
|
499
|
+
engine.render();
|
|
500
|
+
mesh.setGeometry(new Geometry([], [], []));
|
|
501
|
+
engine.render();
|
|
502
|
+
mesh.dispose(); engine.dispose();
|
|
503
|
+
```
|