@margoengine/animation 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 +1054 -3
- package/dist/batch.d.ts +155 -0
- package/dist/clip-utils.d.ts +50 -0
- package/dist/clip-utils.js +1 -0
- package/dist/clone.d.ts +15 -0
- package/dist/deform-readers-DmYAkvBK.js +1 -0
- package/dist/deform-readers.d.ts +5 -0
- package/dist/deformed-points.d.ts +87 -0
- package/dist/deformed-points.js +17 -0
- package/dist/discrete-tracks.d.ts +102 -0
- package/dist/discrete-tracks.js +1 -0
- package/dist/dqs.d.ts +41 -0
- package/dist/dqs.js +29 -0
- package/dist/errors-t1ewumJS.js +1 -0
- package/dist/geometry-cache.d.ts +208 -0
- package/dist/geometry-cache.js +4 -0
- package/dist/gltf-C2HVNxzB.js +1 -0
- package/dist/gltf.d.ts +63 -0
- package/dist/group.d.ts +97 -0
- package/dist/hdr-format-cmvLFubB.js +1 -0
- package/dist/index.d.ts +201 -0
- package/dist/index.js +1 -0
- package/dist/instanced-morph.d.ts +82 -0
- package/dist/instanced-morph.js +13 -0
- package/dist/instanced-skin.d.ts +82 -0
- package/dist/instanced-skin.js +43 -0
- package/dist/interactivity.d.ts +71 -0
- package/dist/interactivity.js +4 -0
- package/dist/key-cursor.d.ts +23 -0
- package/dist/keyframes-BO50xipp.js +4 -0
- package/dist/keyframes.d.ts +204 -0
- package/dist/lod.d.ts +87 -0
- package/dist/lod.js +4 -0
- package/dist/material-animation.d.ts +29 -0
- package/dist/mixer.d.ts +226 -0
- package/dist/mixer.js +4 -0
- package/dist/morph-gpu.d.ts +76 -0
- package/dist/morph-gpu.js +48 -0
- package/dist/playback.d.ts +94 -0
- package/dist/playback.js +4 -0
- package/dist/point-cache.d.ts +28 -0
- package/dist/point-cache.js +1 -0
- package/dist/pointer-BOFnz0gk.js +1 -0
- package/dist/pointer.d.ts +43 -0
- package/dist/pointer.js +1 -0
- package/dist/pose-source-MuCl8VDd.js +1 -0
- package/dist/pose.d.ts +7 -0
- package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
- package/dist/retarget.d.ts +107 -0
- package/dist/rigid.d.ts +42 -0
- package/dist/sampling-DjDWYqt2.js +1 -0
- package/dist/sampling.d.ts +112 -0
- package/dist/sampling.js +1 -0
- package/dist/shader-CgAVFeOl.js +66 -0
- package/dist/shader.d.ts +30 -0
- package/dist/skeleton-utils.d.ts +2 -0
- package/dist/skeleton-utils.js +4 -0
- package/dist/skin.d.ts +163 -0
- package/dist/src-WGCsukxV.js +4 -0
- package/dist/vat-mWaj5B5R.js +50 -0
- package/dist/vat.d.ts +178 -0
- package/dist/vat.js +1 -0
- package/dist/vertex-map-BC_WH7ER.js +1 -0
- package/dist/weight-buffer.d.ts +1 -0
- package/package.json +133 -6
package/README.md
CHANGED
|
@@ -1,3 +1,1054 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# Margo Engine Animation
|
|
2
|
+
|
|
3
|
+
Import `margoengine/animation` from the `margoengine` package, or `@margoengine/animation` 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
|
+
Optional WebGPU skeletal animation and morph targets, isolated from core and stage.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {createStage} from 'margoengine';
|
|
9
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
10
|
+
import {Animation} from 'margoengine/animation';
|
|
11
|
+
const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
|
|
12
|
+
const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
|
|
13
|
+
const animation = Animation.attach(model);
|
|
14
|
+
animation.play('Walking');
|
|
15
|
+
animation.playing = false;
|
|
16
|
+
animation.seek(0.5);
|
|
17
|
+
animation.destroy();
|
|
18
|
+
model.destroy();
|
|
19
|
+
stage.dispose();
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`playing`, `time` and `clip` are plain fields. `time` is the seconds into the current clip; while the clip loops (the
|
|
23
|
+
default `loop: true`) it wraps at the clip's end, so a scrub bar can show it as is.
|
|
24
|
+
|
|
25
|
+
Parses glTF skins, joint hierarchies and inverse bind matrices. Samples STEP, LINEAR (quaternion slerp), and CUBICSPLINE tracks. Animation advances in seconds before the engine updates world matrices. A compute pass blends position/normal/tangent morphs before skinning and writes the vertex draw buffer. Bone matrices use read-only storage buffers, bounded by the GPU's storage limits rather than a fixed bone count.
|
|
26
|
+
|
|
27
|
+
Every skinned or morphed primitive of a device, across all its Animations, lives in a few shared storage buffers and deforms in one compute dispatch per buffer page and influence format (100 morphed models with two primitives each: one dispatch, not 200). Copies of one asset primitive (`cloneModel`) share one copy of its bind-pose vertices, morph deltas and skin influences; only the deformed output, weights and bones are per copy, and a copy's output starts as a GPU copy of the bind pose, so a hundred characters upload their vertices once. A primitive's deformed vertices start `primitive.deformedOffset` bytes (a multiple of 256) into `primitive.deformed`; gltf/pbr, shadows, TAA, selection and picking read them there, and a custom reader binds or copies from that offset.
|
|
28
|
+
|
|
29
|
+
Use `animation.setMorph(nodeIndex, targetIndex, weight)` for manual expressions. Play a clip by name/index; set `loop:false` for one-shot playback. Up to eight influences per vertex are supported through paired `JOINTS_0`/`WEIGHTS_0` and optional `JOINTS_1`/`WEIGHTS_1`. Higher sets reject explicitly. No blending between clips is included.
|
|
30
|
+
|
|
31
|
+
`nodeIndex` is the glTF mesh node with morph targets, which can be a child of an
|
|
32
|
+
armature root. Invalid node/target/weight input throws `RangeError` before changing
|
|
33
|
+
weights; its diagnostic lists available mesh node indices and target counts.
|
|
34
|
+
Find candidates through `model.primitives` (`nodeIndex` and `weights.length`), then
|
|
35
|
+
call `setMorph` with a target index below that count. For a named expression, `setMorph(name, weight)` matches glTF
|
|
36
|
+
`extras.targetNames` across every mesh node and sets every matching target
|
|
37
|
+
atomically. Missing names and invalid weights leave all targets unchanged.
|
|
38
|
+
Names exposed by `primitive.targetNames` include the loader's indexed fallback
|
|
39
|
+
names when the asset omits names. The indexed overload keeps its precise node
|
|
40
|
+
selection and its existing hot path.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import {Engine} from '@margoengine/core';
|
|
44
|
+
import {loadGLTF} from '@margoengine/gltf/pbr';
|
|
45
|
+
import {Animation} from '@margoengine/animation';
|
|
46
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
47
|
+
const model = await loadGLTF(engine, '/robot-expressive.glb');
|
|
48
|
+
const animation = Animation.attach(model);
|
|
49
|
+
animation.setMorph('Surprised', 0.8);
|
|
50
|
+
animation.dispose(); model.dispose(); engine.dispose();
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Clip names preserve the glTF `name`, including an explicit empty string. An absent
|
|
54
|
+
name is synthesized as `Animation <i>` with the zero-based glTF animation index,
|
|
55
|
+
for example `Animation 0`. `animation.clips` exposes the resulting names; `play(i)`
|
|
56
|
+
also selects by the original unchanged glTF index. An unnamed RiggedFigure clip is covered by the contract test.
|
|
57
|
+
|
|
58
|
+
Four-influence primitives keep their 32-byte influence records and the arithmetic of the per-primitive shader, bit for bit. An eight-influence primitive uses a 64-byte record and a second, lazily created compute pipeline; both formats can coexist in one model. Weights normalize across all present sets, including assets whose positive weights are entirely in the secondary set. Joint indices accept unsigned 8-bit or 16-bit accessors; weights accept Float32 or normalized unsigned 8-bit/16-bit accessors. Both sets require matching vertex counts, valid palette indices, nonnegative weights, and a positive combined sum.
|
|
59
|
+
|
|
60
|
+
Single-clip playback reuses sample buffers, quaternion arrays, palette matrices, and each skin's inverse-bind array (read at joint offsets, no view per joint). Making an Animation reads each channel's morph width from the node grouping, without searching the primitives per channel. The animation hot path allocates no new typed arrays, quaternion copies, or GPU resources. Each frame re-checks the options and morph widths without allocating (the primitives are grouped by node once), each track continues from the key it found last frame instead of searching again (a seek back or a loop wrap searches), and node translations and scales go through `node.position.set` and `node.scale.set`, the same store writes as `setPosition` and `setScale`. The skinned primitives of one node (same joints and inverse binds) share one bone range: their palette is computed, checked, encoded and uploaded once a frame, not once per primitive. An Animation's palettes sit back to back in one array, so when their bone ranges are contiguous (the usual case) one write uploads all of them, and the copy kept to skip unchanged uploads is a second array swapped with the live one, not copied. Device restoration recreates both pipeline variants and the shared buffers. `sampleTrack()` retains its independently owned return value by default; an optional seventh `target: Float32Array` argument lets other consumers reuse their own output storage.
|
|
61
|
+
|
|
62
|
+
`createMaterialAnimation(model, {clip?, loop?})` plays a clip's `KHR_animation_pointer` STEP tracks on base-color `KHR_texture_transform` offset and scale (what `@margoengine/exporters` writes from `materialAnimations`): `seek(seconds)` writes the sampled UV transform into every primitive material of the targeted glTF material, and `dispose()` releases its claim on those properties. Given the opt-in `pointers` option, `Animation` also plays those channels, with every other `KHR_animation_pointer` channel it supports (see below); without it, it skips them and counts them in the clip's duration.
|
|
63
|
+
|
|
64
|
+
The separate `@margoengine/animator` package adds gameplay states, blend trees, additive masks and foot IK while reusing this pass's palette buffers. `sampleTrack()` is exported for animation consumers (matrix products: `@margoengine/math/mat4`).
|
|
65
|
+
|
|
66
|
+
Animation installs an optional `model.prepareDeformation` encoding hook. GPU
|
|
67
|
+
picking and explicit CPU snapshots use it to update the same skin/morph output
|
|
68
|
+
after a seek, bone edit or weight change without needing a beauty frame. Queries
|
|
69
|
+
do not advance playback time. The hook survives device restoration; disposal
|
|
70
|
+
removes only the animation instance's own hook. No CPU skinning copy is added to
|
|
71
|
+
the playback path.
|
|
72
|
+
|
|
73
|
+
Synchronous CPU raycasts (`Raycaster.intersectEngine`, `intersectObjects`, `SceneBVH`
|
|
74
|
+
and `RaycastSnapshot` of `@margoengine/bvh`) hit an animated model at its current
|
|
75
|
+
pose with no readback: for the ray, `Animation` evaluates the deformation pass's
|
|
76
|
+
arithmetic on the CPU (morph targets, then the linear blend of four or eight
|
|
77
|
+
joints, positions and normals) from the node matrices and morph weights as they
|
|
78
|
+
are at the call. It is redone only when a bone, a morph weight or the bind
|
|
79
|
+
vertices changed, and nothing is kept for a model no ray ever asks about; the
|
|
80
|
+
first query reads the influences and morph deltas from the asset once (32 or 64
|
|
81
|
+
bytes per skinned vertex, 48 bytes per vertex and target). `Skin` and
|
|
82
|
+
`GeometryCachePlayer` do the same from their own CPU data. An `Animation` with
|
|
83
|
+
a `skinning` mode, or one whose weights a `MorphWeightPlayer` drives, has no CPU
|
|
84
|
+
pose: those raycasts throw MargoError `unsupported`, and
|
|
85
|
+
`await raycaster.intersectModel(model)` reads the pose back from the GPU.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import {Engine} from '@margoengine/core';
|
|
89
|
+
import {loadGLTF} from '@margoengine/gltf/pbr';
|
|
90
|
+
import {Animation} from '@margoengine/animation';
|
|
91
|
+
import {Raycaster} from '@margoengine/bvh';
|
|
92
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
93
|
+
|
|
94
|
+
const hero = await loadGLTF(engine, '/hero.glb');
|
|
95
|
+
const animation = Animation.attach(hero);
|
|
96
|
+
animation.seek(0.4);
|
|
97
|
+
const [hit] = new Raycaster().setFromEngine(engine, 320, 240).intersectObjects(engine, [hero]);
|
|
98
|
+
console.log(hit ? hit.distance : 'the ray misses the pose');
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Run the character demo at `/examples/robot-expressive.html` (also `character-animation.html`). RobotExpressive is by Tomás Laulhé with morphs by Don McCurdy (CC0). It is not a Khronos sample.
|
|
102
|
+
|
|
103
|
+
The demo leaves facial weights under the sliders' control by removing weight tracks from its clips. Expressions persist while playing, pausing and switching clips. Presets include a neutral reset; playback speed and a reset-view button accompany touch-enabled orbit controls. The studio floor uses the optional shadows and tone-mapping packages.
|
|
104
|
+
|
|
105
|
+
After building the packages, run `node --test packages/animation/tests/*.test.js` for influence validation, packed formats, lifecycle, and allocation checks. `node scripts/animation-influences-browser-tests.js` checks real WebGPU deformation against an independent CPU reference, four-influence parity, eight active influences with morphs, a 1,001-joint palette, and device restoration. Its Margo-made [rig fixture](tests/fixtures/README.md) (`scripts/make-rig-fixture.js`) has 273 vertices, 8 joints, two clips, and 247 vertices with secondary skin weights (up to eight influences); it is committed in the repository and not bundled with the package.
|
|
106
|
+
|
|
107
|
+
## Hidden models and shared skeletons
|
|
108
|
+
|
|
109
|
+
A scale key of 0 on any axis plays like any other (glTF 2.0 section 3.5.3): pop-in animations that grow a node from
|
|
110
|
+
zero work as exported, and CPU poses (`skin.pose`, `bakeVAT`) give a flattened vertex a finite normal.
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
A model whose primitives are all hidden skips its GPU deformation: its clips keep running, its joints keep moving, and its deformed vertices wait at the last pose shown. They catch up in the first frame it shows, before anything draws it. `GPUDynamicBVH` and `readPickingGeometry` on a hidden model read that last pose. A hidden model that `DeformedPoints` draws (`@margoengine/animation/deformed-points`) keeps deforming, because the points read its vertices.
|
|
114
|
+
|
|
115
|
+
`skeleton` plays a model on the joints of another model of the same file, so the two can never drift apart. It has no clips of its own, and `@margoengine/lod/auto` uses it for the levels of a skinned model:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { Animation } from '@margoengine/animation';
|
|
119
|
+
import { cloneModel } from '@margoengine/animation/skeleton-utils';
|
|
120
|
+
import { loadGLTF } from '@margoengine/gltf/pbr';
|
|
121
|
+
import {Engine} from '@margoengine/core';
|
|
122
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
123
|
+
|
|
124
|
+
const hero = await loadGLTF(engine, '/hero.glb');
|
|
125
|
+
const animation = Animation.attach(hero);
|
|
126
|
+
const copy = await cloneModel(hero);
|
|
127
|
+
Animation.attach(copy, { skeleton: hero }); // moves with hero, whatever moves hero
|
|
128
|
+
animation.play(0);
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
A copy is ready to draw when `cloneModel` resolves: it makes its own nodes, uniforms and bind groups up front (three's clone defers that to the first render) and writes the source's node transforms straight into the transform store, with no arrays per node.
|
|
132
|
+
|
|
133
|
+
## Skeletons and skins from raw data
|
|
134
|
+
|
|
135
|
+
`Skeleton` and `Skin` rig a mesh from plain arrays, for editors that author bones and weights themselves (no glTF
|
|
136
|
+
document needed). Bones live in the skinned mesh's local space; exactly one bone is the root (`parent: -1`).
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import {createStage} from 'margoengine';
|
|
140
|
+
import {boxGeometry} from 'margoengine/geometry';
|
|
141
|
+
import {Material, createMesh} from 'margoengine/materials';
|
|
142
|
+
import {Skeleton, Skin} from 'margoengine/animation';
|
|
143
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
144
|
+
const skeleton = new Skeleton([
|
|
145
|
+
{name: 'upper', parent: -1},
|
|
146
|
+
{name: 'forearm', parent: 0, translation: [0, 1, 0]},
|
|
147
|
+
]); // inverse bind matrices come from this base pose unless passed as a second argument
|
|
148
|
+
const geometry = boxGeometry(1, 2, 1);
|
|
149
|
+
const mesh = createMesh(stage.engine, geometry, new Material({color: '#c08060'}));
|
|
150
|
+
// Four bone indices and four weights per vertex; weights normalise to sum 1, a zero sum follows the root bone.
|
|
151
|
+
const count = geometry.positions.length / 3, joints = new Uint16Array(count * 4), weights = new Float32Array(count * 4);
|
|
152
|
+
for (let v = 0; v < count; v++) {
|
|
153
|
+
joints[v * 4] = geometry.positions[v * 3 + 1] > 0 ? 1 : 0; // the top half follows the forearm
|
|
154
|
+
weights[v * 4] = 1;
|
|
155
|
+
}
|
|
156
|
+
const skin = Skin.attach(mesh, skeleton, joints, weights); // or new Skin(...) for CPU-only skinning
|
|
157
|
+
skeleton.setPose(1, {rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2]}); // posing; the GPU follows next frame
|
|
158
|
+
skeleton.restorePose(1); // Restore Pose; restorePose(1, true) also resets nested bones; restorePose() resets all
|
|
159
|
+
skeleton.setBindPose(); // the current pose becomes the base pose, inverse binds recomputed
|
|
160
|
+
skin.setInfluences(0, [1, 0, 0, 0], [1, 0, 0, 0]); // weight painting: vertex 0 now follows the forearm
|
|
161
|
+
const world = skeleton.worldMatrix(1, mesh.primitives[0].node.matrix); // for drawing and picking bones
|
|
162
|
+
const posed = skin.pose(geometry.positions, geometry.normals); // CPU skinning: picking, Export Static Pose (OBJ/DAE)
|
|
163
|
+
skin.dispose();
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`Skin.attach` reuses the four-influence compute shader above and swaps the mesh's draw buffer (`primitive.deformed`), so
|
|
167
|
+
textures, nearest sampling, vertex colours, shadows and GPU picking follow the pose; the mesh needs one shared vertex
|
|
168
|
+
array (any `createMesh` mesh). An unchanged pose dispatches nothing. A pose change uploads 64 bytes per bone;
|
|
169
|
+
`setInfluences` costs O(changed vertices) on the CPU, then the next frame uploads 32 bytes per vertex spanning the
|
|
170
|
+
changed ones.
|
|
171
|
+
Validation rejects bad indices and counts, repeated names, parent cycles and anything but one root (`RangeError` /
|
|
172
|
+
`TypeError`). Material meshes do not render through `model.createRenderer(otherDevice)`, so neither does a skin.
|
|
173
|
+
|
|
174
|
+
## Keyframe clips from raw keys
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
import {createStage} from 'margoengine';
|
|
178
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
179
|
+
import {
|
|
180
|
+
Animation,
|
|
181
|
+
Skeleton,
|
|
182
|
+
applyKeyframeClip,
|
|
183
|
+
bakeKeyframeClip,
|
|
184
|
+
compileRigidClip,
|
|
185
|
+
createKeyframeClip,
|
|
186
|
+
sampleKeyframes,
|
|
187
|
+
segmentTime,
|
|
188
|
+
} from 'margoengine/animation';
|
|
189
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
190
|
+
const model = await loadGLTF(stage.engine, '/face.glb');
|
|
191
|
+
const skeleton = new Skeleton([{name: 'forearm', parent: -1}]);
|
|
192
|
+
const exportNodes = new Map([['forearm', 0], ['door', 1]]); // track target -> exporter node index
|
|
193
|
+
const elapsed = 1.25; // seconds since the segment started
|
|
194
|
+
const wave = createKeyframeClip({name: 'Wave', tracks: [
|
|
195
|
+
{target: 'forearm', path: 'rotation', keys: [
|
|
196
|
+
{time: 0, value: [0, 0, 0, 1], interpolation: 'easeInOut'}, // shapes the time until the next key
|
|
197
|
+
{time: 0.5, value: [0, 0, 0.38268, 0.92388], interpolation: 'discrete'},
|
|
198
|
+
{time: 1, value: [0, 0, 0, 1]},
|
|
199
|
+
]},
|
|
200
|
+
{target: 'door', path: 'translation', keys: [{time: 0, value: [0, 0, 0]}, {time: 1, value: [2, 0, 0]}]},
|
|
201
|
+
]});
|
|
202
|
+
const t = segmentTime(elapsed, wave.duration, {loop: true, timeScale: -1}); // a reversed, looping segment
|
|
203
|
+
applyKeyframeClip(wave, skeleton, t); // poses bones named by track targets
|
|
204
|
+
const door = sampleKeyframes(wave.tracks[1], t); // any other target: sample it yourself
|
|
205
|
+
const baked = bakeKeyframeClip(wave, 30, (target) => exportNodes.get(target)); // exporters AnimationData
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Tracks target a bone (by name) or the caller's node by a stable string id, for translation, rotation, scale and morph
|
|
209
|
+
`weights` (one number per morph target in every key, blended per component and never normalised). Each
|
|
210
|
+
key carries its own interpolation for the time until the next key: `discrete` (hold, then jump at the next key),
|
|
211
|
+
`linear`, `easeIn`, `easeOut` or `easeInOut` (cubic); rotations slerp along the shortest path by the eased factor.
|
|
212
|
+
Sampling is a pure function of time, so editing, scrubbing, playback and offline rendering agree at any frame rate.
|
|
213
|
+
`bakeKeyframeClip` writes glTF samplers: a track of only discrete keys becomes STEP and one of only linear keys becomes
|
|
214
|
+
LINEAR, both at their keys and exact everywhere; other tracks are LINEAR at the keys plus every `1 / fps` second inside
|
|
215
|
+
eased segments, exact at those times. Pass the result to `@margoengine/exporters` as an `ExportScene` animation; tracks
|
|
216
|
+
whose target `resolve` maps to undefined are left out.
|
|
217
|
+
|
|
218
|
+
A track's `blend` picks the arithmetic between keys a and b at eased factor f. The default, `'delta'`, is
|
|
219
|
+
`a + (b - a) * f`. `'weighted'` is for saved data that needs a finite, exactly held result: a sample at a key, before
|
|
220
|
+
the first, after the last or inside a discrete segment copies the key's value before any arithmetic, and translation
|
|
221
|
+
and scale between keys are `(1 - f) * a + f * b`, finite for all finite keys (keys of ±1e308 included, where
|
|
222
|
+
`'delta'`'s b - a overflows to NaN). Rotations slerp the same way in both. `'weighted'` reproduces Margo Voxel Studio's
|
|
223
|
+
saved vector-track evaluation bit for bit (`tests/keyframes-blend.test.js`).
|
|
224
|
+
|
|
225
|
+
Code clips also drive glTF PBR models: pass the model's `Animation` instead of a skeleton. Tracks then name model nodes
|
|
226
|
+
(the first node with that name); transform tracks set the node's local transform and `weights` tracks set every morph
|
|
227
|
+
weight through `animation.setMorph`, so expressions authored in code play on loaded characters. Pause the model's own
|
|
228
|
+
clip (`animation.playing = false`) while a code clip drives it. A `weights` track whose width differs from the node's
|
|
229
|
+
morph target count throws `RangeError`; a `Skeleton` skips `weights` tracks. `bakeKeyframeClip` writes `weights`
|
|
230
|
+
tracks as glTF `weights` channels, which gltf/pbr and `Animation` play back (`tests/keyframes-weights.test.js` checks
|
|
231
|
+
the round trip through `exportGLB`).
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const blink = createKeyframeClip({name: 'Blink', tracks: [
|
|
235
|
+
{target: 'Face', path: 'weights', keys: [{time: 0, value: [0, 0]}, {time: 0.1, value: [1, 0]}, {time: 0.2, value: [0, 0]}]},
|
|
236
|
+
]});
|
|
237
|
+
const animation = Animation.attach(model);
|
|
238
|
+
animation.playing = false;
|
|
239
|
+
applyKeyframeClip(blink, animation, t); // node 'Face' has two morph targets
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
`skin.pose()` runs the GPU pass's maths on the CPU (linear blend of the four bone matrices; normals by the cofactor
|
|
243
|
+
matrix, flipped under mirroring scales) and returns Float32 positions and normals in the mesh's space.
|
|
244
|
+
`tests/raw-rig-roundtrip.test.js` writes a raw rig and clip with `@margoengine/exporters` `exportGLB` (bones as export
|
|
245
|
+
nodes under the mesh node, `skeleton.inverseBindMatrices`, `bakeKeyframeClip`), reads it back through gltf/pbr and
|
|
246
|
+
`Animation`, and matches `skin.pose()` within 1e-4 at frame and key times.
|
|
247
|
+
`node scripts/animation-skin-browser-tests.js` (real WebGPU, after building the packages) reads back the deformed
|
|
248
|
+
buffer of a skinned `createMesh` strip and matches `skin.pose()` positions and normals within 1e-5 after posing, a
|
|
249
|
+
ranged `setInfluences` and a device restore, with no validation errors.
|
|
250
|
+
|
|
251
|
+
## Rigid rigs: whole meshes bound to bones
|
|
252
|
+
|
|
253
|
+
`compileRigidClip(bones, bindings, keys, {name, duration})` turns keys of meshes rigidly bound to bones into stepped
|
|
254
|
+
bone translation and rotation tracks. A key moves its bone by the mesh's offset from its rest pose and rotates it by
|
|
255
|
+
the key rotation times the inverse rest rotation; each bone follows the first bound mesh (in binding order) keyed so
|
|
256
|
+
far, and holds the last pose until `duration`. Times are seconds; rotations are `[x, y, z, w]`.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
const clip = compileRigidClip(
|
|
260
|
+
[{id: 'arm', translation: [0.5, 1.5, 0]}],
|
|
261
|
+
[{object: 'sword', bone: 'arm', position: [1, 1, 0], rotation: [0, 0, 0, 1]}],
|
|
262
|
+
[{object: 'sword', time: 0.5, position: [1, 2, 0], rotation: [0, 0, 0, 1]}],
|
|
263
|
+
{duration: 2},
|
|
264
|
+
);
|
|
265
|
+
applyKeyframeClip(clip, skeleton, t);
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## Property tracks: any number, vector or colour
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
import {applyKeyframeClip, bakeKeyframeTrack, createKeyframeClip, sampleKeyframes} from 'margoengine/animation';
|
|
272
|
+
const lamp = {intensity: 0, material: {roughness: 1, color: new Float32Array([1, 1, 1, 1])}};
|
|
273
|
+
let fov = 60;
|
|
274
|
+
const pulse = createKeyframeClip({name: 'Pulse', tracks: [
|
|
275
|
+
{target: lamp, property: 'intensity', keys: [{time: 0, value: [0], interpolation: 'easeOut'}, {time: 1, value: [5]}]},
|
|
276
|
+
{target: lamp, property: 'material.roughness', keys: [{time: 0, value: [1], interpolation: 'discrete'}, {time: 0.5, value: [0.2]}]},
|
|
277
|
+
{target: lamp, property: 'material.color', type: 'color', keys: [{time: 0, value: [1, 0, 0]}, {time: 1, value: [0, 0, 1]}]},
|
|
278
|
+
{target: lamp, name: 'fov', get: () => fov, set: (value) => { fov = value[0]; }, keys: [
|
|
279
|
+
{time: 0, value: [40], interpolation: 'cubicSpline', outTangent: [30]},
|
|
280
|
+
{time: 1, value: [60], inTangent: [0]},
|
|
281
|
+
]},
|
|
282
|
+
]});
|
|
283
|
+
applyKeyframeClip(pulse, 0.5); // writes all four properties
|
|
284
|
+
const color = sampleKeyframes(pulse.properties![2], 0.25); // [0.75, 0, 0.25]
|
|
285
|
+
const baked = bakeKeyframeTrack(pulse.properties![0], 30); // a glTF sampler for one property track
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
A track whose `target` is an object drives a property of it instead of a bone or node: name it with a dot path
|
|
289
|
+
(`'material.roughness'`, `'intensity'`, `'position'`, `'lights.0.color'`) or pass `set` (and `get`, for
|
|
290
|
+
`track.read()`) accessors. Keys hold 1 to 4 numbers; `type` says what they are: `'number'`, `'vector'`, `'color'`
|
|
291
|
+
(linear RGB or RGBA, blended per channel in linear space) or `'quaternion'` (normalised, slerped along the shortest
|
|
292
|
+
path). They take the same interpolations (`'cubicSpline'` is a glTF CUBICSPLINE segment through the key's
|
|
293
|
+
`outTangent` and the next key's `inTangent`, in units per second) and the same `blend` modes as transform tracks.
|
|
294
|
+
`createKeyframeClip` resolves each path once into a setter, so playback does no lookups and allocates nothing: a
|
|
295
|
+
number property is assigned, a boolean gets `value >= 0.5`, an array or typed array (a materials `Material`'s live
|
|
296
|
+
`color`, a clustered light's `color`) is written in place, a getter that returns a fresh array is assigned through its
|
|
297
|
+
setter, and an `{x, y, z}` object such as a mesh's `position` is set through its `set(x, y, z)`. A path that does not
|
|
298
|
+
resolve throws `RangeError` naming the segment; one that ends on a value it cannot write throws `TypeError`. Engine
|
|
299
|
+
objects work the same way: `{target: mesh, property: 'visible'}`, `{target: material, property: 'roughness'}`,
|
|
300
|
+
`{target: stage.engine.camera, property: 'fov'}`. Replacing an object along a path later leaves the track driving the
|
|
301
|
+
old one: create the clip again. Property tracks land in `clip.properties`; `applyKeyframeClip(clip, time)` writes
|
|
302
|
+
them, and `applyKeyframeClip(clip, skeleton, time)` writes them and poses the skeleton. `bakeKeyframeClip` leaves them
|
|
303
|
+
out (glTF nodes have no such paths); `AnimationGroup` and `retarget` ignore them.
|
|
304
|
+
|
|
305
|
+
## KHR_animation_pointer playback
|
|
306
|
+
|
|
307
|
+
Transmission can start at `0` (or its omitted default) and animate to a positive
|
|
308
|
+
factor. Seeking back to `0` restores the opaque path. Volume attenuation and native
|
|
309
|
+
capture follow the transition; the source document stays unchanged. The
|
|
310
|
+
[self-contained triangle example](../gltf/README.md#animate-an-opaque-material-into-glass)
|
|
311
|
+
builds this channel without a downloaded model.
|
|
312
|
+
|
|
313
|
+
Volume pointer writes update attenuation and optical depth together. Optical depth
|
|
314
|
+
is retained before transmittance underflows, so a thick volume scaled down in the
|
|
315
|
+
scene keeps its absorption. Backward seeks recompute those values from the source
|
|
316
|
+
volume and the sampled keys.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
import {createStage} from 'margoengine';
|
|
320
|
+
import {loadGLTF, viewGLTFCamera} from 'margoengine/gltf/pbr';
|
|
321
|
+
import {Animation} from 'margoengine/animation';
|
|
322
|
+
import {pointerChannels} from 'margoengine/animation/pointer';
|
|
323
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
324
|
+
const model = await loadGLTF(stage.engine, '/pointer-show.glb');
|
|
325
|
+
const animation = Animation.attach(model, {pointers: pointerChannels});
|
|
326
|
+
for (const warning of animation.warnings) console.warn(warning); // pointers this player skips
|
|
327
|
+
animation.playing = false;
|
|
328
|
+
animation.seek(1.5);
|
|
329
|
+
viewGLTFCamera(model, 0); // cameras and lights are data: hand them on after each update
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Pointer playback is opt-in, like gltf/pbr's optional decoders: import `pointerChannels` from
|
|
333
|
+
`@margoengine/animation/pointer` and pass it as the `pointers` option, so apps whose files have no pointer channels do
|
|
334
|
+
not ship it. Without it, `Animation` skips every pointer channel (still counting it in the clip's duration) and lists
|
|
335
|
+
it in `animation.warnings` with the fix. With it, `Animation` plays a clip's `KHR_animation_pointer` channels with its
|
|
336
|
+
ordinary ones, at the same time, speed and loop, with glTF's STEP, LINEAR and CUBICSPLINE sampling. It drives:
|
|
337
|
+
|
|
338
|
+
- nodes: `/nodes/i/translation`, `rotation` (slerp), `scale`, `weights`, `/meshes/i/weights` (every node using the mesh,
|
|
339
|
+
unless the node's own weights are animated) and `/nodes/i/extensions/KHR_node_visibility/visible` (STEP, unsigned
|
|
340
|
+
byte);
|
|
341
|
+
- materials (every primitive material of the glTF material): `pbrMetallicRoughness/baseColorFactor`, `metallicFactor`,
|
|
342
|
+
`roughnessFactor`, `emissiveFactor`, `alphaCutoff`, `normalTexture/scale`, `occlusionTexture/strength`,
|
|
343
|
+
`KHR_materials_emissive_strength`, `KHR_materials_dispersion`, and with the physical renderer the clearcoat,
|
|
344
|
+
transmission, specular, sheen, IOR and volume factors (the transmission tint and volume follow);
|
|
345
|
+
- `KHR_texture_transform` `offset`, `scale` and `rotation` on the base, metallic-roughness, normal, occlusion,
|
|
346
|
+
emissive, clearcoat, transmission, sheen and specular textures (the map and its uniform rows);
|
|
347
|
+
- `KHR_lights_punctual`: `color`, `intensity`, `range`, `spot/innerConeAngle`, `spot/outerConeAngle` on `model.lights`,
|
|
348
|
+
so `model.clusteredLights()` and `applyGLTFLights` pick them up;
|
|
349
|
+
- cameras: `perspective/yfov`, `aspectRatio`, `znear`, `zfar` and `orthographic/xmag`, `ymag`, `znear`, `zfar` on
|
|
350
|
+
`model.cameras`, for `viewGLTFCamera`.
|
|
351
|
+
|
|
352
|
+
Values are written to copies the model owns, never to `model.asset.doc`, and bound on the clip's first playback.
|
|
353
|
+
Pointers that break the glTF rules throw: malformed or out-of-range indices, properties animations may not change
|
|
354
|
+
(`/materials/0/name`), a repeated pointer, a node property animated both by pointer and by an ordinary channel,
|
|
355
|
+
accessors of the wrong type or count, booleans that are not STEP unsigned bytes, and an IOR sampler with a key below 1
|
|
356
|
+
(`KHR_materials_ior` keeps 0 as a mode set in the file, never an animated value). Valid pointers this player cannot
|
|
357
|
+
drive are skipped and listed in `animation.warnings`: other extensions (iridescence, anisotropy and diffuse
|
|
358
|
+
transmission factors, unknown extensions), `extras`, `texCoord`, textures of extended materials, properties the file
|
|
359
|
+
leaves undefined (a camera without `zfar`, a light without `range`), factors gltf/pbr did not load (physical factors
|
|
360
|
+
without the materials decoder, transmission on a material loaded without it), the IOR of a material whose file sets it to
|
|
361
|
+
0 (the extension ignores updates of that mode) and targets no scene node or primitive uses. A cubic IOR spline that dips
|
|
362
|
+
below 1 between its keys writes 1.
|
|
363
|
+
|
|
364
|
+
## Behaviour graphs (`@margoengine/animation/interactivity`)
|
|
365
|
+
|
|
366
|
+
A glTF file can carry its own behaviour: on a click, play this clip, turn that material green. `GLTFInteractivity` runs the `KHR_interactivity` graph of a loaded model on the engine's frame loop, so the file behaves with no code of the app's. The graph itself lives in [`@margoengine/gltf/interactivity`](../gltf/README.md#behaviour-graphs-in-gltf-interactivity); this entry reaches the engine, and sits in this package because it plays clips and writes the same live properties as `KHR_animation_pointer`.
|
|
367
|
+
|
|
368
|
+
```ts
|
|
369
|
+
import {createStage} from 'margoengine';
|
|
370
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
371
|
+
import {GLTFInteractivity} from 'margoengine/animation/interactivity';
|
|
372
|
+
|
|
373
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
374
|
+
const model = await loadGLTF(stage.engine, '/product.glb');
|
|
375
|
+
const behaviour = GLTFInteractivity.attach(model);
|
|
376
|
+
if (behaviour.rejected) console.warn(behaviour.rejected);
|
|
377
|
+
behaviour.graph?.on('checkout', ({variant}) => console.log(variant));
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
| Option | Default | Meaning |
|
|
381
|
+
| --- | --- | --- |
|
|
382
|
+
| `pointer` | `true` | Turns pointer input on the canvas into select and hover events. Attaches `Picking` of `@margoengine/selection`, an optional peer loaded on first use, unless the engine has a picker. |
|
|
383
|
+
| `physics` | none | The `GLTFPhysics` of `@margoengine/gltf/physics`, for `rigid_body/*` operations and trigger events. |
|
|
384
|
+
| `shareCamera` | `true` | Reports the viewer's camera to the graph. `false` makes `activeCamera` read as NaN, for a file you do not trust with where the viewer looks. |
|
|
385
|
+
| `log` | none | Receives `debug/log` text. |
|
|
386
|
+
| `maxActivations` | 1,000,000 | Node activations one step may run before the graph halts. |
|
|
387
|
+
| `maxEventsPerTick` | 10,000 | Custom events one tick delivers. |
|
|
388
|
+
|
|
389
|
+
A file's clips start only when its graph says so, so do not also play them with `Animation`. A press that moves over 4 CSS pixels is a drag and selects nothing. A click passes through unselectable nodes to what is behind them, and the graph receives the point it hit. `behaviour.notes` lists properties the graph wrote that it can read back but that change nothing on screen. `dispose()` stops the input.
|
|
390
|
+
|
|
391
|
+
## Groups: one clip for many models
|
|
392
|
+
|
|
393
|
+
`AnimationGroup` is one clip and one clock for a crowd. Members are glTF PBR models'
|
|
394
|
+
`Animation`s playing a glTF clip they all have (by name or index), or, for a code-authored `KeyframeClip`, `Skeleton`s
|
|
395
|
+
and `Animation`s whose bones or nodes the tracks name. Each member can run ahead or behind by an offset in seconds.
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
import {createStage} from 'margoengine';
|
|
399
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
400
|
+
import {Animation, AnimationGroup} from 'margoengine/animation';
|
|
401
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
402
|
+
const walkers = await Promise.all([0, 1, 2].map(() => loadGLTF(stage.engine, '/RobotExpressive.glb')));
|
|
403
|
+
const crowd = new AnimationGroup('Walking', {speed: 1});
|
|
404
|
+
const animations = walkers.map((model) => Animation.attach(model));
|
|
405
|
+
for (const [i, animation] of animations.entries()) crowd.add(animation, i * 0.37); // offset per walker
|
|
406
|
+
const walkerAnimation = animations[0];
|
|
407
|
+
stage.engine.use(crowd); // advances in onPreUpdate; or call crowd.update(delta) yourself
|
|
408
|
+
crowd.seek(2); crowd.playing = false; crowd.setOffset(walkerAnimation, 0.5); crowd.remove(walkerAnimation);
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Adding an `Animation` pauses its own playback; the group seeks it each frame through its usual sampling path. A glTF
|
|
412
|
+
clip loops as each member's own `loop` option says (a negative member time wraps back from the end); code clips take
|
|
413
|
+
the group's `loop` option (default true; false holds the first and last frames). Code-clip tracks are bound to bones,
|
|
414
|
+
nodes and morph weights once, in `add`, and group playback creates no typed arrays per frame
|
|
415
|
+
(`tests/group.test.js` traps the constructors over 120 frames). Each member still deforms on the GPU through its own
|
|
416
|
+
`Animation`; the group adds no GPU work.
|
|
417
|
+
|
|
418
|
+
## Sampling (`@margoengine/animation/sampling`)
|
|
419
|
+
|
|
420
|
+
`sampleTrack` and `sampleTrackInto` (also on the root) without the deformation pipeline or
|
|
421
|
+
gltf/pbr, for code that samples tracks itself (`@margoengine/animator` does).
|
|
422
|
+
|
|
423
|
+
```ts
|
|
424
|
+
import {sampleTrack} from 'margoengine/animation/sampling';
|
|
425
|
+
|
|
426
|
+
const times = new Float32Array([0, 1]);
|
|
427
|
+
const values = new Float32Array([0, 0, 0, 10, 0, 0]); // x, y, z per key
|
|
428
|
+
const position = sampleTrack(times, values, 3, 0.5, 'LINEAR'); // Float32Array [5, 0, 0]
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
### Clip markers
|
|
432
|
+
|
|
433
|
+
`ClipMarkers` reports the named moments a play position passes: footsteps, hits, sound cues. A marker counts as passed
|
|
434
|
+
once the position is at or beyond it, so moving forward from a to b reports markers in (a, b], moving back reports (b, a],
|
|
435
|
+
and a loop repeats them every lap (a step longer than the clip reports every lap). `seek` is silent unless you pass
|
|
436
|
+
`fire`. `createKeyframeClip` takes `markers` and sorts them onto `clip.markers`.
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import {ClipMarkers} from 'margoengine/animation/sampling';
|
|
440
|
+
import {createKeyframeClip} from 'margoengine/animation';
|
|
441
|
+
|
|
442
|
+
const clip = createKeyframeClip({
|
|
443
|
+
tracks: [{target: 'hips', path: 'translation', keys: [{time: 0, value: [0, 0, 0]}, {time: 1, value: [0, 0, 2]}]}],
|
|
444
|
+
markers: [{time: 0.25, name: 'footstep'}, {time: 0.75, name: 'footstep'}],
|
|
445
|
+
});
|
|
446
|
+
const player = new ClipMarkers(clip.markers ?? [], clip.duration); // loops by default
|
|
447
|
+
player.advance(0.5).map((m) => m.time); // [0.25]
|
|
448
|
+
player.advance(0.5).map((m) => m.time); // [0.75]
|
|
449
|
+
player.advance(-0.5).map((m) => m.time); // [0.75] (leaving 0.75 backward)
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
### Clip compression
|
|
453
|
+
|
|
454
|
+
`compressTrack` removes keys a track does not need and `quantizeTrack` stores what is left as 16-bit integers. Both keep
|
|
455
|
+
the sampling call the same (`dequantizeTrack` gives the Float32 track back), and both report the error you can check:
|
|
456
|
+
after `compressTrack(track, tolerance)` every original key time samples within `tolerance` per component
|
|
457
|
+
(`result.error` is the measured maximum); quantisation adds at most half a `step` (range / 131070) per component.
|
|
458
|
+
`LINEAR` and `STEP` tracks only; rotation tracks take `quaternion: true`. On six KayKit Rig_Medium clips (rotations and
|
|
459
|
+
translations, 0.0005 tolerance) the keys went from 4,589 to 3,441 and the bytes from 88,440 to 50,832; a 2 second, 60 fps
|
|
460
|
+
walk bob at 1 cm keeps 33 of 121 keys and shrinks from 1,936 to 354 bytes (`tests/clip-tools.test.js`).
|
|
461
|
+
|
|
462
|
+
```ts
|
|
463
|
+
import {compressTrack, dequantizeTrack, quantizeTrack, sampleTrack} from 'margoengine/animation/sampling';
|
|
464
|
+
|
|
465
|
+
const times = Float32Array.from({length: 61}, (_, i) => i / 30);
|
|
466
|
+
const values = Float32Array.from(times, (t) => Math.sin(t * 3));
|
|
467
|
+
const track = {times, values, width: 1, interpolation: 'LINEAR' as const};
|
|
468
|
+
|
|
469
|
+
const small = compressTrack(track, 0.001); // fewer keys, small.error <= 0.001
|
|
470
|
+
const packed = quantizeTrack(small); // packed.data is a Uint16Array
|
|
471
|
+
const back = dequantizeTrack(packed);
|
|
472
|
+
const x = sampleTrack(back.times, back.values, 1, 0.5, 'LINEAR'); // within 0.001 plus half a step of sin(1.5)
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
## GPU morph weights (`@margoengine/animation/morph-gpu`)
|
|
476
|
+
|
|
477
|
+
The deformation pass always blends morph targets on the GPU. `MorphWeightPlayer` moves the rest of the work there too:
|
|
478
|
+
a clip's weight tracks upload once, and one compute dispatch per deformation buffer page samples every copy's weights
|
|
479
|
+
each frame, so the CPU writes 16 bytes a frame however many faces play.
|
|
480
|
+
|
|
481
|
+
```ts
|
|
482
|
+
import {createStage} from 'margoengine';
|
|
483
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
484
|
+
import {Animation} from 'margoengine/animation';
|
|
485
|
+
import {MorphWeightPlayer} from 'margoengine/animation/morph-gpu';
|
|
486
|
+
import {cloneModel} from 'margoengine/animation/skeleton-utils';
|
|
487
|
+
const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 16384});
|
|
488
|
+
// Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
|
|
489
|
+
const source = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
|
|
490
|
+
const models = [source, ...(await Promise.all(Array.from({length: 99}, () => cloneModel(source))))];
|
|
491
|
+
const talk = MorphWeightPlayer.attach(stage.engine, 'Dance'); // this asset's clip includes weight tracks
|
|
492
|
+
for (const [i, model] of models.entries()) {
|
|
493
|
+
const animation = Animation.attach(model);
|
|
494
|
+
animation.playing = false; // or keep it playing a body clip: only weights are driven here
|
|
495
|
+
talk.add(animation, {offset: i * 0.13, speed: 1}); // defaults 0 and 1; add again to change them
|
|
496
|
+
}
|
|
497
|
+
talk.speed = 0.5; // every copy; talk.time, talk.playing and talk.remove(animation) work as you would expect
|
|
498
|
+
talk.dispose();
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
A copy samples `time * speed + offset`, with `sampleTrack`'s arithmetic for STEP, LINEAR and CUBICSPLINE. Copies must
|
|
502
|
+
share one asset (`cloneModel`), because they share the tracks; a disposed copy leaves by itself. Weights the player
|
|
503
|
+
drives are overwritten every frame, so `setMorph` has no effect on them, and `primitive.weights` on the CPU does not
|
|
504
|
+
follow them. `scripts/animation-morph-gpu-tests.js` reads the weights back on real WebGPU and matches `sampleTrack`
|
|
505
|
+
within 1e-5 on 70 copies, looping and held.
|
|
506
|
+
|
|
507
|
+
## Animation LOD (`@margoengine/animation/lod`)
|
|
508
|
+
|
|
509
|
+
`AnimationLOD` updates each character as often as its distance and visibility call for, so a big crowd spends its CPU
|
|
510
|
+
on the characters people can see. Time keeps running for every copy, so one that is updated again lands exactly where
|
|
511
|
+
it would have been.
|
|
512
|
+
|
|
513
|
+
```ts
|
|
514
|
+
import {createStage} from 'margoengine';
|
|
515
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
516
|
+
import {Animation} from 'margoengine/animation';
|
|
517
|
+
import {AnimationLOD} from 'margoengine/animation/lod';
|
|
518
|
+
import {cloneModel} from 'margoengine/animation/skeleton-utils';
|
|
519
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
520
|
+
const source = await loadGLTF(stage.engine, '/RobotExpressive.glb');
|
|
521
|
+
const models = [source, ...(await Promise.all(Array.from({length: 199}, () => cloneModel(source))))];
|
|
522
|
+
const lod = AnimationLOD.attach(stage.engine, {
|
|
523
|
+
tiers: [
|
|
524
|
+
{distance: 0, interval: 1}, // the default tiers are these three
|
|
525
|
+
{distance: 15, interval: 2}, // every second frame from 15 units
|
|
526
|
+
{distance: 40, interval: 4, depth: 4}, // every fourth frame, and nodes below level 4 hold
|
|
527
|
+
],
|
|
528
|
+
hidden: {distance: 0, interval: 16, depth: 1}, // off screen, at any distance
|
|
529
|
+
});
|
|
530
|
+
const walkers = models.map((model, i) => {
|
|
531
|
+
model.root.setPosition([(i % 20) * 3, 0, -Math.floor(i / 20) * 6]);
|
|
532
|
+
return Animation.attach(model).play('Walking');
|
|
533
|
+
});
|
|
534
|
+
for (const walker of walkers) lod.add(walker, {radius: 1.5}); // the sphere tested against the view; default 2
|
|
535
|
+
stage.onTick(() => console.log(lod.stats)); // {updated, skipped, hidden} of the last frame
|
|
536
|
+
lod.remove(walkers[0]); // hands a copy back, fully posed, playing as it was
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
`add` takes over a copy's playback; its clip, `speed` and `loop` still come from its `Animation`. A copy takes the last
|
|
540
|
+
tier whose `distance` it has reached, and copies on one interval take turns, so no frame carries them all. `depth`
|
|
541
|
+
counts node levels from the scene roots, so what level 4 means depends on the rig: pick it per character. Weight tracks
|
|
542
|
+
always play. Distance and visibility use the root's position from the previous frame.
|
|
543
|
+
|
|
544
|
+
## Clip editing (`@margoengine/animation/clip-utils`)
|
|
545
|
+
|
|
546
|
+
`subclip` cuts a time range into a new clip, and `makeAdditive` turns a clip into differences from a reference pose.
|
|
547
|
+
|
|
548
|
+
```ts
|
|
549
|
+
import {Skeleton, applyKeyframeClip, createKeyframeClip} from 'margoengine/animation';
|
|
550
|
+
import {applyAdditiveClip, makeAdditive, subclip, subclipFrames} from 'margoengine/animation/clip-utils';
|
|
551
|
+
const skeleton = new Skeleton([{name: 'hips', parent: -1}, {name: 'head', parent: 0, translation: [0, 1, 0]}]);
|
|
552
|
+
const walk = createKeyframeClip({
|
|
553
|
+
name: 'Walk',
|
|
554
|
+
tracks: [{target: 'hips', path: 'translation', keys: [
|
|
555
|
+
{time: 0, value: [0, 0, 0]}, {time: 1, value: [0, 0.1, 1]}, {time: 2, value: [0, 0, 2]},
|
|
556
|
+
]}],
|
|
557
|
+
markers: [{time: 0.75, name: 'footstep'}],
|
|
558
|
+
});
|
|
559
|
+
const nod = createKeyframeClip({
|
|
560
|
+
name: 'Nod',
|
|
561
|
+
tracks: [{target: 'head', path: 'rotation', keys: [
|
|
562
|
+
{time: 0, value: [0, 0, 0, 1]}, {time: 0.5, value: [0.2588, 0, 0, 0.9659]}, {time: 1, value: [0, 0, 0, 1]},
|
|
563
|
+
]}],
|
|
564
|
+
});
|
|
565
|
+
const stride = subclip(walk, 0.5, 1.5, {name: 'Stride'}); // seconds; starts at 0, markers come along
|
|
566
|
+
const opening = subclipFrames(walk, 0, 15); // frames, both included, at 30 per second unless you pass a rate
|
|
567
|
+
const additive = makeAdditive(nod); // against the first frame; or {clip: idle, time: 0.5}
|
|
568
|
+
const t = 0.25;
|
|
569
|
+
applyKeyframeClip(stride, skeleton, t); // pose the base first, every frame
|
|
570
|
+
applyAdditiveClip(additive, skeleton, t, 0.5); // then add half of the nod
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
A cut plays exactly as the source did: both ends are sampled, keys inside keep their interpolation, and only an eased or
|
|
574
|
+
cubic segment the cut passes through becomes short straight keys, 60 per second unless you pass `fps`. Property tracks
|
|
575
|
+
stay bound to their targets, and `blend` carries over. `makeAdditive` uses the sums `@margoengine/animator` additive
|
|
576
|
+
layers use: translation and weights subtract, scale divides (a zero reference axis gives 1) and rotation is
|
|
577
|
+
`inverse(reference) * rotation`. Every key keeps its time and interpolation, so the result is exact between keys too.
|
|
578
|
+
`applyAdditiveClip` adds to whatever pose the skeleton holds, so applying it twice adds twice.
|
|
579
|
+
|
|
580
|
+
## Dual quaternion skinning (`@margoengine/animation/dqs`)
|
|
581
|
+
|
|
582
|
+
Blended matrices pinch a joint that twists: a forearm turned 170 degrees shrinks to under a tenth of its radius halfway
|
|
583
|
+
along. Pass `dualQuaternionSkinning` and the bones blend as rigid motions, so the arm keeps its volume. It is a per
|
|
584
|
+
`Animation` choice, made when you create it. The cost is one matrix split per bone per frame on the CPU, and more
|
|
585
|
+
arithmetic per vertex on the GPU.
|
|
586
|
+
|
|
587
|
+
```ts
|
|
588
|
+
import {createStage} from 'margoengine';
|
|
589
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
590
|
+
import {Animation} from 'margoengine/animation';
|
|
591
|
+
import {dualQuaternionSkinning} from 'margoengine/animation/dqs';
|
|
592
|
+
const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
|
|
593
|
+
const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
|
|
594
|
+
const animation = Animation.attach(model, {skinning: dualQuaternionSkinning});
|
|
595
|
+
animation.play('Walking');
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
Scaled, stretched, sheared and mirrored bones keep working: each bone's matrix splits exactly into a rotation, a
|
|
599
|
+
translation and a symmetric stretch, the stretch blends linearly and applies first, then the blended rigid motion. A
|
|
600
|
+
vertex held by one bone lands where the matrix puts it. A bone scaled to nothing still encodes, so hiding a part that
|
|
601
|
+
way works. Between two bones of different scale the result differs from a linear blend, because the stretch applies
|
|
602
|
+
about the mesh origin rather than each joint. Four and eight influences, morph targets under the skin, clones and
|
|
603
|
+
models of both kinds in one scene all work; each kind is its own dispatch.
|
|
604
|
+
|
|
605
|
+
`encodeDualQuaternions(palette, out?)` turns 16-float bone matrices into 16-float slots (rotation, dual part, stretch),
|
|
606
|
+
and `skinDualQuaternion(slots, joints, weights, position, normal?)` is the shader's CPU twin, for tests and CPU picking.
|
|
607
|
+
`blendSkinning` is the same dual quaternion skin with a share per vertex: each vertex mixes the linear skin of its bones
|
|
608
|
+
with the dual quaternion skin by a number in [0, 1], which is what an FBX `Blend` skin means. The shares come from the
|
|
609
|
+
node's glTF `extras.fbxSkinning.blendWeights` (one per vertex of its primitive, written by `@margoengine/fbx/deformers`);
|
|
610
|
+
a node without them is all dual quaternion, and a list of the wrong length or a share outside [0, 1] throws. Position,
|
|
611
|
+
normal and tangent blend between the two skins. `skinDualQuaternion(slots, joints, weights, position, normal, share)` takes
|
|
612
|
+
the share as its sixth argument, and matches the GPU to 7e-6 on a twisted tube (`npm run test:gpu:dqs`).
|
|
613
|
+
|
|
614
|
+
```ts
|
|
615
|
+
import {createStage} from 'margoengine';
|
|
616
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
617
|
+
import {Animation} from 'margoengine/animation';
|
|
618
|
+
import {blendSkinning} from 'margoengine/animation/dqs';
|
|
619
|
+
const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
|
|
620
|
+
const model = await loadGLTF(stage.engine, '/RobotExpressive.glb'); // an FBX Blend skin: loadFBX with the deformers extension
|
|
621
|
+
const animation = Animation.attach(model, {skinning: blendSkinning});
|
|
622
|
+
animation.play('Walking');
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
Only `Animation` has the option: `Skin` on raw data, `bakeVAT` and the bone-texture crowd stay linear.
|
|
626
|
+
|
|
627
|
+
## Bone-texture crowds (`@margoengine/animation/instanced-skin`)
|
|
628
|
+
|
|
629
|
+
A vertex animation texture stores finished vertices, so a crowd member can only play one clip. `bakeBones` stores bone
|
|
630
|
+
matrices instead, one row per clip frame, and `SkinnedCrowd` skins each member in the vertex shader: any number of
|
|
631
|
+
characters in one draw, and each can blend two clips, with its own offsets and speeds. The CPU does nothing per member
|
|
632
|
+
per frame. The texture is also far smaller: three texels per bone per frame, whatever the vertex count.
|
|
633
|
+
|
|
634
|
+
```ts
|
|
635
|
+
import {createStage} from 'margoengine';
|
|
636
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
637
|
+
import {Animation} from 'margoengine/animation';
|
|
638
|
+
import {SkinnedCrowd, bakeBones} from 'margoengine/animation/instanced-skin';
|
|
639
|
+
const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
|
|
640
|
+
const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
|
|
641
|
+
const bake = bakeBones(new Animation(model), {fps: 30, clips: ['Walking', 'Running']});
|
|
642
|
+
model.dispose();
|
|
643
|
+
|
|
644
|
+
const crowd = SkinnedCrowd.attach(stage.engine, bake);
|
|
645
|
+
for (let i = 0; i < 1000; i++)
|
|
646
|
+
crowd.add({
|
|
647
|
+
matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, (i % 40) * 2, 0, Math.floor(i / 40) * 2, 1],
|
|
648
|
+
clip: 0,
|
|
649
|
+
offset: i * 0.13,
|
|
650
|
+
blendClip: 1,
|
|
651
|
+
blend: (i % 10) / 10, // a jog: part walk, part run
|
|
652
|
+
});
|
|
653
|
+
crowd.set(0, {blend: 1});
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
`bakeBones(animation, {fps = 30, clips})` bakes clips by name or index, all primitives merged in the model root's space,
|
|
657
|
+
up to eight influences per vertex; an unskinned part becomes a bone of its own. The animation's clip, time and playing
|
|
658
|
+
state are restored. A member takes `VATCrowd`'s `matrix`, `clip`, `offset`, `speed` and `uvTransform`, and adds
|
|
659
|
+
`blendClip` (default 0), `blendOffset` (default 0), `blendSpeed` (default 1) and `blend` (0 to 1, default 0, all of the
|
|
660
|
+
first clip). Clips mix as matrices, and bones blend linearly. Everything else follows `VATCrowd`: one material, opaque,
|
|
661
|
+
`shadows.add(crowd)` and `lighting.add(crowd)`, no CPU culling. One vertex entry draws colour and shadow, its position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit. `poseBones(bake, member, time, out?)` is the shader's CPU
|
|
662
|
+
twin, for bounds and picking. `poseBone(bake, member, bone, time, out?)` is the twin for one bone: its skinning matrix as
|
|
663
|
+
the 12 numbers of its 3x4 rows, both clips and the blend applied, for what follows a member (a rider on a horse's back,
|
|
664
|
+
a rifle in a hand):
|
|
665
|
+
|
|
666
|
+
```ts
|
|
667
|
+
import {poseBone} from 'margoengine/animation/instanced-skin';
|
|
668
|
+
const bake = {bones: 1, rows: 2, width: 2048, texels: new Float32Array(2048 * 4), vertexCount: 0, vertices: new Float32Array(0),
|
|
669
|
+
joints: new Uint32Array(0), weights: new Float32Array(0), indices: new Uint32Array(0), uvs: new Float32Array(0),
|
|
670
|
+
clips: [{name: 'still', start: 0, frames: 1, duration: 1, loop: true}]};
|
|
671
|
+
for (const row of [0, 1]) bake.texels.set([1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1, 0], row * 12); // lifted 2 m
|
|
672
|
+
const m = poseBone(bake, {clip: 0}, 0, 0.5);
|
|
673
|
+
console.log(m[7]); // 2: a point on this bone rides 2 m up
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
Morph targets stay at the weights they had when baked; `MorphedCrowd` (next section) gives each member its own.
|
|
677
|
+
|
|
678
|
+
## Morph weights per crowd member (`@margoengine/animation/instanced-morph`)
|
|
679
|
+
|
|
680
|
+
`MorphedCrowd` is a `SkinnedCrowd` whose members each carry their own morph weights, set from JavaScript at any time:
|
|
681
|
+
one face smiles while the next one frowns, in the same instanced draw. `bakeMorphBones` bakes like `bakeBones` but
|
|
682
|
+
leaves the live targets out of the vertices and stores their position and normal offsets in the bone texture, after the
|
|
683
|
+
bone rows; each member's weights ride in its instance row, and the vertex shader adds the weighted offsets before it
|
|
684
|
+
skins. The CPU does no per-vertex work.
|
|
685
|
+
|
|
686
|
+
```ts
|
|
687
|
+
import {createStage} from 'margoengine';
|
|
688
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
689
|
+
import {Animation} from 'margoengine/animation';
|
|
690
|
+
import {MorphedCrowd, bakeMorphBones} from 'margoengine/animation/instanced-morph';
|
|
691
|
+
const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
|
|
692
|
+
// Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
|
|
693
|
+
const model = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
|
|
694
|
+
const bake = bakeMorphBones(new Animation(model), {fps: 30, clips: ['Walking']});
|
|
695
|
+
model.dispose();
|
|
696
|
+
|
|
697
|
+
const crowd = MorphedCrowd.attach(stage.engine, bake);
|
|
698
|
+
const [first, second] = bake.morphs.names; // the live targets, in weight order
|
|
699
|
+
for (let i = 0; i < 100; i++)
|
|
700
|
+
crowd.add({
|
|
701
|
+
matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, (i % 10) * 2, 0, Math.floor(i / 10) * 2, 1],
|
|
702
|
+
offset: i * 0.13,
|
|
703
|
+
morphs: [i % 2], // weights in bake.morphs.names order; a short array sets the first ones
|
|
704
|
+
});
|
|
705
|
+
crowd.setMorph(0, first, 0.5); // one weight of one member, by name or index
|
|
706
|
+
crowd.set(1, {morphs: {[second]: 1}}); // by name; the weights not named keep their value
|
|
707
|
+
console.log(crowd.getMorph(1, second)); // 1
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
`bakeMorphBones(animation, {fps = 30, clips, morphs})` takes `bakeBones`'s options and `morphs`: the targets that stay
|
|
711
|
+
live, by name or by index (default: every target of the model). Targets are joined by name across primitives, in
|
|
712
|
+
first-seen order, so a face split over three primitives has one weight per expression; an unnamed target is
|
|
713
|
+
`'Target <index>'`. A target left out of `morphs` is baked in at the weight it has now, as `bakeBones` bakes it. The
|
|
714
|
+
result is a `BoneBake` with `morphs.names` (the live targets), `morphs.weights` (the model's weights when baked: what a
|
|
715
|
+
new member starts with), `morphs.vertices` and `morphs.blocks` (where each vertex finds its offsets).
|
|
716
|
+
|
|
717
|
+
A member takes everything a `SkinnedCrowd` member does, and `morphs`: an array in `bake.morphs.names` order, or an
|
|
718
|
+
object of weights by name. Weights may be any finite number (below 0 and above 1 extrapolate, as glTF allows); a weight
|
|
719
|
+
of 0 costs no texture reads. `setMorph(index, target, weight)` and `getMorph(index, target)` set and read one weight. A
|
|
720
|
+
weight that is not finite, an unknown target or a member that does not exist throws RangeError and changes nothing.
|
|
721
|
+
Changed weights upload with the next frame.
|
|
722
|
+
|
|
723
|
+
A bake holds at most 64 live targets (`MORPH_TARGET_LIMIT`): the weights are part of the instance row, four to a
|
|
724
|
+
vector, so a member row is 28 floats plus the target count rounded up to 4. Name the targets you animate in `morphs`
|
|
725
|
+
when a model has more. Offsets cost two texels (32 bytes) per vertex of each primitive that has the target, and nothing
|
|
726
|
+
for primitives without it. Tangent offsets are not carried (the crowd has no tangents). `morphVertices(bake, weights)`
|
|
727
|
+
and `poseMorphedBones(bake, member, time)` are the shader's CPU twins, for bounds and picking. Everything else is
|
|
728
|
+
`SkinnedCrowd`'s: two clips and a blend per member, one material, `shadows.add(crowd)`, `lighting.add(crowd)`.
|
|
729
|
+
|
|
730
|
+
`packages/animation/tests/instanced-morph-browser.mjs` runs the vertex stage's own morph and skin functions from a
|
|
731
|
+
compute shader on real WebGPU and on the WebGL2 compatibility layer: 48 members with their own weights, clips and blends
|
|
732
|
+
match `poseMorphedBones` within 1e-5 at every vertex, and a member drawn at given weights covers the same pixels as the
|
|
733
|
+
model itself at those weights.
|
|
734
|
+
|
|
735
|
+
## Points on a deforming mesh (`@margoengine/animation/deformed-points`)
|
|
736
|
+
|
|
737
|
+
`DeformedPoints` draws every vertex of a model as a point where the model's deformer last put it, so a skinned or
|
|
738
|
+
morphed triangle mesh shows as a moving cloud of its own vertices. The points are instanced straight from the buffer the
|
|
739
|
+
deformation pass wrote: no second skinning pass, no CPU work per vertex, one draw per primitive.
|
|
740
|
+
|
|
741
|
+
```ts
|
|
742
|
+
import {createStage} from 'margoengine';
|
|
743
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
744
|
+
import {Animation} from 'margoengine/animation';
|
|
745
|
+
import {DeformedPoints} from 'margoengine/animation/deformed-points';
|
|
746
|
+
const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
|
|
747
|
+
// Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
|
|
748
|
+
const model = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
|
|
749
|
+
Animation.attach(model).play('Dance');
|
|
750
|
+
|
|
751
|
+
const points = DeformedPoints.attach(model, {size: 3, color: '#ffcc00'});
|
|
752
|
+
model.root.visible = false; // the points alone; leave it true to draw them over the mesh
|
|
753
|
+
points.set({shape: 'round', sizeUnits: 'world', size: 0.02}); // 2 cm discs that shrink with distance
|
|
754
|
+
points.opacity = 0.8; // every option is also a live field
|
|
755
|
+
```
|
|
756
|
+
|
|
757
|
+
| Option | Default | Meaning |
|
|
758
|
+
| --- | --- | --- |
|
|
759
|
+
| `size` | `4` | Point diameter: pixels of the view, or world units with `sizeUnits: 'world'`. Finite, 0 or more |
|
|
760
|
+
| `sizeUnits` | `'pixels'` | `'pixels'` keeps a constant screen size; `'world'` shrinks with distance |
|
|
761
|
+
| `color` | white | `'#rrggbb'`, `'#rgb'` or `0xrrggbb` (sRGB), or a linear `[r, g, b]` array. Change it with `set({color})`; `points.color` reads the linear RGB |
|
|
762
|
+
| `opacity` | `1` | 0 to 1. Below 1 the points blend over what is already drawn and still write depth |
|
|
763
|
+
| `shape` | `'square'` | `'square'`, or `'round'` (a disc cut from the square, no antialiasing of its own) |
|
|
764
|
+
| `vertexColors` | `true` | Multiplies `color` by each vertex's colour (glTF `COLOR_0`; white where the mesh has none) |
|
|
765
|
+
|
|
766
|
+
`points.visible` (default `true`) turns the points off and on, `points.count` is the number of points, and
|
|
767
|
+
`points.dispose()` (or `using`) frees them; disposing the model disposes its points. `set(options)` checks every value
|
|
768
|
+
and changes nothing when one is out of range (RangeError; TypeError for a `vertexColors` that is not a boolean or a
|
|
769
|
+
colour that is not one).
|
|
770
|
+
|
|
771
|
+
The deformer can be `Animation` (skins and morph targets, any skinning mode), `Skin` on raw data, `MorphWeightPlayer`
|
|
772
|
+
or a geometry cache player. A primitive no deformer writes draws its own vertices at its node, so the rigid parts of a
|
|
773
|
+
model show too. The points are unlit, depth tested against the scene, and written in the target's own encoding (sRGB on
|
|
774
|
+
a display target, linear on an HDR one). They cast no shadows, are not fogged and are not picked. A primitive drawn with
|
|
775
|
+
`EXT_mesh_gpu_instancing` shows its points once, at its node. `pointScale(cameraMatrix, size, sizeUnits, width, height)`
|
|
776
|
+
is the size maths the shader uses, for tools that need a point's footprint on screen.
|
|
777
|
+
|
|
778
|
+
`packages/animation/tests/deformed-points-browser.mjs` draws a skinned strip and a morphed triangle, both hidden, as
|
|
779
|
+
points on real WebGPU and on the WebGL2 compatibility layer: every vertex's point is on the pixel its pose projects to
|
|
780
|
+
at three clip times and three morph weights, covers its 5 x 5 pixels within 10 percent, and nothing else draws.
|
|
781
|
+
|
|
782
|
+
## Geometry caches (`@margoengine/animation/geometry-cache`)
|
|
783
|
+
|
|
784
|
+
Cloth, destruction and fluid simulations from a DCC tool end up as baked vertices, frame by frame. `GeometryCachePlayer`
|
|
785
|
+
plays such a file while it downloads. It holds a few chunks at a time, so a long cache never has to fit in memory, and each
|
|
786
|
+
chunk carries its own triangles, so a fluid can change vertex count as it plays.
|
|
787
|
+
|
|
788
|
+
```ts
|
|
789
|
+
import {createStage} from 'margoengine';
|
|
790
|
+
import {GeometryCachePlayer, encodeGeometryCache} from 'margoengine/animation/geometry-cache';
|
|
791
|
+
const stage = await createStage('#viewport', {backend:'webgpu',capacity:2048});
|
|
792
|
+
// Two frames of one triangle, generated here so no external cache file is needed.
|
|
793
|
+
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]);
|
|
794
|
+
const bytes = encodeGeometryCache(30, [{frameCount: 2, positions, indices: new Uint32Array([0, 1, 2])}]);
|
|
795
|
+
const flag = await GeometryCachePlayer.attach(stage.engine, bytes, {ahead: 3});
|
|
796
|
+
flag.seek(1 / 60);
|
|
797
|
+
flag.speed = 0.5;
|
|
798
|
+
```
|
|
799
|
+
|
|
800
|
+
`attach(engine, source, options)` resolves once the first chunk is in. `source` is a URL, a `ReadableStream` or other async
|
|
801
|
+
iterable of bytes, one `Uint8Array`, or `(signal) => bytes`. Options: `loop` (default true), `speed` (default 1), `ahead`
|
|
802
|
+
(chunks read past the one playing, default 2), `signal`, `material` (a glTF material, default plain white) and
|
|
803
|
+
`maxChunkBytes` (default 1 GiB). The player owns `player.model`: move it through `player.model.root`, and dispose the player.
|
|
804
|
+
|
|
805
|
+
The clock waits when the stream falls behind, so playback never jumps; `player.stats.stalls` counts the frames it waited.
|
|
806
|
+
Between two frames of one mesh the vertices interpolate. A chunk with other triangles or another vertex count swaps the mesh
|
|
807
|
+
at its first frame, and the last frame of the chunk before it holds, since there is no mesh to mix towards. A URL, an array
|
|
808
|
+
or a function can start over, so played chunks are let go, a seek back reads again and a loop reads the file once a lap, with
|
|
809
|
+
the first chunk held so the wrap does not wait; a stream cannot, so it keeps every chunk it read. `player.done` settles when the read ends, which follows the clock by `ahead` chunks, so a paused player may
|
|
810
|
+
never get there. A failure rejects it and leaves the last frame up.
|
|
811
|
+
|
|
812
|
+
`readGeometryCache(bytes, {signal, maxChunkBytes})` is the same reader without a player, an async iterator of chunks, and
|
|
813
|
+
`encodeGeometryCache(rate, chunks)` writes a file, so an exporter is a few lines:
|
|
814
|
+
|
|
815
|
+
```ts
|
|
816
|
+
import {encodeGeometryCache, readGeometryCache} from 'margoengine/animation/geometry-cache';
|
|
817
|
+
|
|
818
|
+
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]);
|
|
819
|
+
const file = encodeGeometryCache(30, [{frameCount: 2, positions, indices: new Uint32Array([0, 1, 2])}]);
|
|
820
|
+
for await (const chunk of readGeometryCache(file)) console.log(chunk.firstFrame, chunk.vertexCount);
|
|
821
|
+
```
|
|
822
|
+
|
|
823
|
+
A cache from a DCC tool is usually a PC2 or MDD file. `parsePointCache` from `@margoengine/animation/point-cache` reads both. They hold vertices and no triangles, so give it the triangles of the mesh it was baked from:
|
|
824
|
+
|
|
825
|
+
```ts
|
|
826
|
+
import {encodeGeometryCache} from 'margoengine/animation/geometry-cache';
|
|
827
|
+
import {parsePointCache} from 'margoengine/animation/point-cache';
|
|
828
|
+
|
|
829
|
+
const bytes = new Uint8Array(await (await fetch('/ball.pc2')).arrayBuffer()); // written by Blender's PC2 add-on
|
|
830
|
+
const cache = parsePointCache(bytes, {fps: 24});
|
|
831
|
+
// A fan over the points stands in here: use the triangles of the mesh the cache was baked from.
|
|
832
|
+
const indices = new Uint32Array(3 * (cache.vertexCount - 2)).map((_, n) => (n % 3 ? Math.floor(n / 3) + (n % 3) : 0));
|
|
833
|
+
const file = encodeGeometryCache(cache.rate, [{frameCount: cache.frameCount, positions: cache.positions, indices}]);
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
`fps` (default 24) is for PC2, which does not say; an MDD file's own times win. `zUp: true` turns a Z-up file to Y-up as `(x, z, -y)`; Blender's MDD add-on writes Z-up and its PC2 add-on Y-up by default. `maxFloats` (default 2^28) refuses a larger file. A header that asks for more than the file holds is refused as a cut file or no point cache at all, before the limit: MDD has no magic, so any other file reads as an MDD header. Alembic is not read: it has no published file specification to build from. The result fits the player as it is, so the file above goes straight to `GeometryCachePlayer.attach`.
|
|
837
|
+
|
|
838
|
+
A meshed fluid, a fracture or any bake that writes one whole mesh a frame is a mesh sequence: the triangles change every
|
|
839
|
+
frame. `encodeMeshSequence(rate, frames, {maxChunkFrames})` groups it into chunks for the player, frames with the same
|
|
840
|
+
triangles, vertex count, UVs and normals-or-not sharing one (up to `maxChunkFrames`, default the rate rounded, about a
|
|
841
|
+
second) and a frame whose topology changes starting the next; a chunk with the triangles or UVs of the one before leaves
|
|
842
|
+
them out. `frames` is any iterable or async iterable of `{positions, indices, normals?, uvs?}`, and
|
|
843
|
+
`streamMeshSequence` yields the file a chunk at a time (its header then says 0 total frames), so a long bake read file by
|
|
844
|
+
file never sits in memory whole. A frame with an index past its vertices, a non-finite position, or normals or UVs of the
|
|
845
|
+
wrong size is refused by number. From the command line, `margo-convert sequence <folder>` does the same for a folder of
|
|
846
|
+
per-frame OBJ, PLY or STL files (Blender's OBJ export with Animation on, a fluid add-on's mesh export).
|
|
847
|
+
|
|
848
|
+
```ts
|
|
849
|
+
import {GeometryCachePlayer, encodeMeshSequence} from 'margoengine/animation/geometry-cache';
|
|
850
|
+
import {createStage} from 'margoengine';
|
|
851
|
+
|
|
852
|
+
const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
|
|
853
|
+
// A fan whose triangle count grows each frame, as a fluid surface's does.
|
|
854
|
+
const fan = (sides: number, z: number) => {
|
|
855
|
+
const positions = new Float32Array((sides + 1) * 3), indices: number[] = [];
|
|
856
|
+
for (let s = 0; s < sides; s++) {
|
|
857
|
+
const a = (s / sides) * Math.PI * 2;
|
|
858
|
+
positions.set([Math.cos(a), Math.sin(a), z], (s + 1) * 3);
|
|
859
|
+
indices.push(0, s + 1, ((s + 1) % sides) + 1);
|
|
860
|
+
}
|
|
861
|
+
return {positions, indices: new Uint32Array(indices)};
|
|
862
|
+
};
|
|
863
|
+
const file = await encodeMeshSequence(24, [fan(6, 0), fan(6, 0.1), fan(9, 0.2), fan(12, 0.3)]);
|
|
864
|
+
const water = await GeometryCachePlayer.attach(stage.engine, file);
|
|
865
|
+
```
|
|
866
|
+
|
|
867
|
+
The format is little endian. A 16 byte header holds the magic `MGCH`, version 1, frames per second (f32) and the total
|
|
868
|
+
frames (0 if unknown). Chunks follow, each a 64 byte header and its payload.
|
|
869
|
+
|
|
870
|
+
| Chunk header offset | Field |
|
|
871
|
+
| --- | --- |
|
|
872
|
+
| 0 | magic `CHNK` |
|
|
873
|
+
| 4 | payload bytes |
|
|
874
|
+
| 8 | first frame, which must follow the last chunk's end |
|
|
875
|
+
| 12 | frame count |
|
|
876
|
+
| 16 | vertex count, 3 to 1,000,000 |
|
|
877
|
+
| 20 | index count, 0 to repeat the last chunk's triangles |
|
|
878
|
+
| 24 | flags: 1 normals stored, 2 UVs stored |
|
|
879
|
+
| 32 | bounds over the chunk: min xyz, max xyz (f32) |
|
|
880
|
+
|
|
881
|
+
The payload is the indices (u32), then UVs (2 floats a vertex), positions (3 floats a vertex, all frames), then normals
|
|
882
|
+
(same shape). A chunk without normals gets smooth ones when it is read; a chunk without UVs repeats the last chunk's if the
|
|
883
|
+
vertex count matches, else zero. A damaged or cut off file rejects with a `failed` error, and a bad chunk header is refused
|
|
884
|
+
before its payload is held.
|
|
885
|
+
|
|
886
|
+
## Cloning and retargeting (`@margoengine/animation/skeleton-utils`)
|
|
887
|
+
|
|
888
|
+
Cloning skinned models and retargeting poses and clips between skeletons, in their own entry:
|
|
889
|
+
|
|
890
|
+
```ts
|
|
891
|
+
import {Animation, Skeleton, createKeyframeClip, applyKeyframeClip} from 'margoengine/animation';
|
|
892
|
+
import {Retarget, cloneModel, retargetRig} from 'margoengine/animation/skeleton-utils';
|
|
893
|
+
import {createStage} from 'margoengine';
|
|
894
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
895
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
896
|
+
// Copy this repository's CC0 RobotExpressive asset to the same public URL in your app.
|
|
897
|
+
const robot = await loadGLTF(stage.engine, '/examples/assets/robot-expressive.glb');
|
|
898
|
+
|
|
899
|
+
const second = await cloneModel(robot); // own nodes and skeleton; shares the parsed asset
|
|
900
|
+
Animation.attach(second).play('Dance'); // animates apart from `robot`
|
|
901
|
+
|
|
902
|
+
// Explicit miniature rigs make the required names and reference poses reproducible.
|
|
903
|
+
const source = new Skeleton([
|
|
904
|
+
{name: 'mixamorig:Hips', parent: -1, translation: [0, 1, 0]},
|
|
905
|
+
{name: 'mixamorig:Spine', parent: 0, translation: [0, 0.5, 0]},
|
|
906
|
+
]);
|
|
907
|
+
const hero = new Skeleton([
|
|
908
|
+
{name: 'Hips', parent: -1, translation: [0, 2, 0]},
|
|
909
|
+
{name: 'Spine', parent: 0, translation: [0, 1, 0]},
|
|
910
|
+
]);
|
|
911
|
+
const retarget = new Retarget(retargetRig(source), retargetRig(hero), {
|
|
912
|
+
names: {Hips: 'mixamorig:Hips', Spine: 'mixamorig:Spine'},
|
|
913
|
+
hip: 'Hips', // follows the source hips' movement, scaled by the rest hip heights unless hipScale is given
|
|
914
|
+
});
|
|
915
|
+
source.setPose(0, {translation: [0.3, 1, 0]});
|
|
916
|
+
retarget.apply(source, hero); // hero's hips now move 0.6 along x
|
|
917
|
+
const sourceClip = createKeyframeClip({name: 'Walk', tracks: [{
|
|
918
|
+
target: 'mixamorig:Hips', path: 'translation', keys: [
|
|
919
|
+
{time: 0, value: [0, 1, 0]}, {time: 1, value: [1, 1, 0]},
|
|
920
|
+
],
|
|
921
|
+
}]});
|
|
922
|
+
const walk = retarget.clip(sourceClip, {fps: 30});
|
|
923
|
+
applyKeyframeClip(walk, hero, 0.5);
|
|
924
|
+
```
|
|
925
|
+
|
|
926
|
+
`cloneModel(model)` resolves to a new `PBRModel` with its own root and nodes, starting in the source's current local
|
|
927
|
+
transforms, visibility and morph weights, and registered with the engine when the source is. It shares the source's
|
|
928
|
+
parsed asset (document, buffers, accessors), decoded images and packed vertex arrays. Copies share the GPU textures of
|
|
929
|
+
those images, the GPU vertex and index buffers of those arrays and, once animated, the deformation inputs (bind-pose
|
|
930
|
+
vertices, morph deltas, skin influences), so a clone uploads no geometry and no texture; what it adds on the GPU is its
|
|
931
|
+
own deformed output, weights, bones, uniforms and bind groups. Disposing any model, source included, leaves the others
|
|
932
|
+
working: each image, texture and buffer goes with its last holder. Materials are rebuilt from the document, so runtime material edits on the source are not copied.
|
|
933
|
+
|
|
934
|
+
A copy costs no engine tick, so spawning a crowd does not touch the rest of the scene: it takes the source's baked
|
|
935
|
+
static batches instead of baking its own. Its world matrices therefore publish with the next tick. Every frame and
|
|
936
|
+
pick runs one first, as do `model.bounds`, `extras()`, `clusteredLights()`, `readPickingGeometry()` and `compile()`, so
|
|
937
|
+
only a direct read of `node.matrix` right after `cloneModel` sees the old value, as after any `setPosition`. A source
|
|
938
|
+
that was moved since baking, or has a parent, costs its copy one tick to bake for itself.
|
|
939
|
+
|
|
940
|
+
`retargetRig(skeletonOrModel)` reads a bone hierarchy and its current local pose, which becomes the rig's rest pose; a
|
|
941
|
+
model's rig is every node, so armature and mesh nodes count toward bone orientations. `new Retarget(source, target,
|
|
942
|
+
options)` maps target bones to source bones by name (`names` overrides, `''` leaves a bone at rest; unnamed glTF nodes
|
|
943
|
+
map only through `names`). Each mapped target bone turns in model space by the rotation its source bone has turned
|
|
944
|
+
from rest, which absorbs different bone axes and rest orientations; bones keep their own lengths and scales, unmapped
|
|
945
|
+
bones keep their rest local pose, and the `hip` bone's position follows the source hip's movement times `hipScale`.
|
|
946
|
+
`pose(sourceLocal, out?)` does this on raw arrays (10 numbers per bone: translation, quaternion, scale) without
|
|
947
|
+
allocating, `apply(source, target)` reads and writes Skeletons or models, and `clip(source, {fps, name})` samples a
|
|
948
|
+
source `KeyframeClip`, or a glTF clip through the source model's `Animation` (restoring its clip, time and playing
|
|
949
|
+
state), into a target `KeyframeClip` with a rotation track per mapped bone and a translation track for the hip. Both
|
|
950
|
+
characters' model spaces must face the same way; morph weight tracks are not carried over.
|
|
951
|
+
`tests/retarget.test.js` checks analytic poses (bone directions, lengths, scaled hip motion, unmapped bones) across
|
|
952
|
+
renamed rigs with different bone axes, and models driven by their `Animation`.
|
|
953
|
+
|
|
954
|
+
### Scene of the result
|
|
955
|
+
|
|
956
|
+
`cloneModel` makes the copy in the scene of its source model (the scene the source is registered in), so a clone of a model in a second scene stays beside it, whichever scene is active when you call it. An abort or a failure leaves nothing in either scene.
|
|
957
|
+
|
|
958
|
+
## Mixer: blended actions (`@margoengine/animation/mixer`)
|
|
959
|
+
|
|
960
|
+
`AnimationMixer` plays several clips on one root at the same time and blends them per property. The root is a
|
|
961
|
+
model, an `Animation`, a `Skeleton`, or a plain object that hosts bound property tracks. `AnimationMixer.attach(engine,
|
|
962
|
+
root)` registers the mixer with the engine, so its clock advances in each frame. `new AnimationMixer(root)` builds the
|
|
963
|
+
same mixer unregistered, for a caller that drives it with `update(delta)` or `advanceTime(delta)`. Attaching a model
|
|
964
|
+
makes an `Animation` for it and pauses that `Animation`, so the mixer alone poses the model. Transform tracks need a
|
|
965
|
+
`Skeleton` or `Animation` root; a plain object takes property tracks only (clips from `createKeyframeClip`).
|
|
966
|
+
|
|
967
|
+
```ts
|
|
968
|
+
import {createStage} from 'margoengine';
|
|
969
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
970
|
+
import {AnimationMixer} from 'margoengine/animation/mixer';
|
|
971
|
+
const stage = await createStage('#viewport', {backend: 'webgpu', capacity: 2048});
|
|
972
|
+
const model = await loadGLTF(stage.engine, '/RobotExpressive.glb');
|
|
973
|
+
const mixer = AnimationMixer.attach(stage.engine, model);
|
|
974
|
+
const idle = mixer.clipAction('Idle').play();
|
|
975
|
+
const walk = mixer.clipAction('Walking').play();
|
|
976
|
+
idle.crossFadeTo(walk, 0.5); // idle fades out and walking fades in over half a second
|
|
977
|
+
walk.setDuration(2); // one walking cycle takes 2 s
|
|
978
|
+
mixer.dispose(); // restores the original pose and disposes the Animation the mixer made
|
|
979
|
+
model.dispose();
|
|
980
|
+
stage.dispose();
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
### Exports
|
|
984
|
+
|
|
985
|
+
- `AnimationMixer` (class). `static attach(engine, root)` creates, registers and returns a mixer; disposing it removes
|
|
986
|
+
its registration. `time` (default `0`) is the global clock in seconds and `timeScale` (default `1`) its signed rate.
|
|
987
|
+
`clipAction(clip, root = the mixer's root, blendMode = NormalAnimationBlendMode)` returns the cached action for that
|
|
988
|
+
clip, root and blend mode, creating it once; `clip` is a glTF clip name or index (an `Animation` root), or an
|
|
989
|
+
`ActionClip` object. `existingAction(clip, root?)` returns the cached action or `null` and never creates one.
|
|
990
|
+
`update(delta)` advances the clocks and blends once; `advanceTime(delta)` moves the clocks without writing a pose;
|
|
991
|
+
`setTime(time)` rewinds every action and seeks to `time`; `stopAllAction()` stops every action and restores the
|
|
992
|
+
original pose. `uncacheAction(clip, root?)`, `uncacheClip(clip)` and `uncacheRoot(root)` drop cached actions (stop
|
|
993
|
+
them first); `uncacheRoot` also disposes the `Animation` the mixer made for that root. `getRoot()` returns the default
|
|
994
|
+
root. `dispose()` and `[Symbol.dispose]()` stop everything, restore the originals and dispose only the `Animation`s
|
|
995
|
+
the mixer created, never the model. The engine calls `setup(engine)` and `onPreUpdate(delta)`, its plugin hooks.
|
|
996
|
+
- `AnimationAction` (class), made by `clipAction`. Options with their defaults: `time` (`0`), `timeScale` (`1`),
|
|
997
|
+
`weight` (`1`), `enabled` (`true`), `paused` (`false`), `clampWhenFinished` (`false` disables the action when it ends;
|
|
998
|
+
`true` holds its end pose), `loop` (`LoopRepeat`) and `repetitions` (`Infinity`). `blendMode` is
|
|
999
|
+
read-only and set at creation. Methods: `play()` starts or resumes without resetting the clock; `stop()` stops, restores
|
|
1000
|
+
the original pose on the next update and rewinds; `reset()` rewinds and clears envelopes; `startAt(time)` delays the
|
|
1001
|
+
start to a mixer time; `isScheduled()` reports whether `play()` was called and not stopped, and `isRunning()` also needs it enabled, at a non-zero rate and past its `startAt` time; `getClip()`,
|
|
1002
|
+
`getMixer()`, `getRoot()`, `getEffectiveWeight()` and `getEffectiveTimeScale()` read it back;
|
|
1003
|
+
`setEffectiveWeight(weight)` sets the weight and cancels a fade, `setEffectiveTimeScale(scale)` sets the rate and cancels a warp;
|
|
1004
|
+
`setDuration(seconds)` sets the time scale so one pass takes `seconds` (positive); `syncWith(action)` copies another
|
|
1005
|
+
action's clock and rate; `setLoop(mode, repetitions = Infinity)` takes `LoopOnce`, `LoopRepeat` or `LoopPingPong` and a
|
|
1006
|
+
count of at least 1; `fadeIn(duration)` and `fadeOut(duration)` ramp the weight from 0 to 1 or 1 to 0 (`fadeIn` does
|
|
1007
|
+
not start the action: call `play()`); `stopFading()` cancels a fade; `warp(from, to, duration)` ramps the rate from
|
|
1008
|
+
`from` to `to` over `duration` seconds; `halt(duration)` slows the rate to 0 over `duration`; `stopWarping()` cancels
|
|
1009
|
+
a warp; `crossFadeTo(action, duration, warp = false)` fades this action out and `action` in, and `crossFadeFrom(action,
|
|
1010
|
+
duration, warp = false)` does the same from the other side. `warp` matches the two cycle rates during the fade (both
|
|
1011
|
+
clips need a positive duration). `step`, `contribute`, `uses`, `usesDiscrete` and `rewind` are the mixer's own
|
|
1012
|
+
per-frame hooks; app code does not call them.
|
|
1013
|
+
- `LoopOnce` (`2200`): play once, clamped at the end. `LoopRepeat` (`2201`): repeat from the opposite end. This is the
|
|
1014
|
+
default. `LoopPingPong` (`2202`): alternate forward and backward passes.
|
|
1015
|
+
- `NormalAnimationBlendMode` (`2500`): weighted replacement, with the original pose filling the weight below one. This
|
|
1016
|
+
is the default. `AdditiveAnimationBlendMode` (`2501`): adds translation and property deltas, multiplies scale deltas
|
|
1017
|
+
and composes rotation deltas. Categorical (boolean or string) tracks have no additive arithmetic and throw with it.
|
|
1018
|
+
- Types: `ActionLoop` (the three loop constants), `ActionClip` (a glTF clip, a `KeyframeClip` or a discrete clip) and
|
|
1019
|
+
`MixerRoot` (`object`).
|
|
1020
|
+
|
|
1021
|
+
Blending normalises by the total weight of the actions that touch a property, so two full-weight actions average, and a
|
|
1022
|
+
property that no action touches returns to its original value.
|
|
1023
|
+
|
|
1024
|
+
## Film time: seeking animation to a cut
|
|
1025
|
+
|
|
1026
|
+
`Animation`, `PlaybackAnimation`, `AnimationGroup`, `AnimationMixer`, `AnimationLOD`, `MorphWeightPlayer`, `VATCrowd`
|
|
1027
|
+
and `GeometryCachePlayer` have `advanceTime(delta)`, the CPU part of their frame update, and a `time` that reads 0 on a
|
|
1028
|
+
fresh clock. A replayed step moves the clip clock (loops, ends, fades, warps, start times, LOD turns) and poses nothing;
|
|
1029
|
+
the next frame update poses the place reached. So `seek` from `@margoengine/cutscene/seek` lands a fresh scene on the
|
|
1030
|
+
pose a continuous run shows there, bit for bit to 54,000 steps (`tests/seek.test.js`, `tests/geometry-cache.test.js`).
|
|
1031
|
+
A replayed `PlaybackAnimation` sends no `loop` or `finished` event (a replayed end still settles `finished`).
|
|
1032
|
+
`AnimationLOD` gives the same turns when the camera is where the continuous run had it. `GeometryCachePlayer` waits for a
|
|
1033
|
+
chunk it does not hold only in a live update, so seek a cache whose file is held in memory (`await player.done`).
|
|
1034
|
+
Behaviour graphs (`interactivity`) have no `advanceTime`: they fire listeners and random nodes, so `seek` lists them in
|
|
1035
|
+
`unseekable` and they start at the cut.
|
|
1036
|
+
|
|
1037
|
+
```ts
|
|
1038
|
+
import {createStage} from 'margoengine';
|
|
1039
|
+
import {loadGLTF} from 'margoengine/gltf/pbr';
|
|
1040
|
+
import {Animation} from 'margoengine/animation';
|
|
1041
|
+
import {seek} from 'margoengine/cutscene/seek';
|
|
1042
|
+
const stage = await createStage('#viewport', {backend: 'webgpu'});
|
|
1043
|
+
const hero = await loadGLTF(stage.engine, '/hero.glb');
|
|
1044
|
+
const walk = Animation.attach(hero, {speed: 1.2});
|
|
1045
|
+
// The scene starts 95 s into the film: replay the clocks, then the first frame poses what a continuous run poses there.
|
|
1046
|
+
const {clocks, unseekable} = await seek(stage.engine, 95, {fps: 60});
|
|
1047
|
+
console.log(walk.time, clocks, unseekable);
|
|
1048
|
+
```
|
|
1049
|
+
|
|
1050
|
+
## Preview tier contract
|
|
1051
|
+
|
|
1052
|
+
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.
|
|
1053
|
+
|
|
1054
|
+
This includes `VATCrowd` (and its crowd subclasses) and `MorphWeightPlayer`.
|