@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
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import type { Engine, EnginePlugin } from '@margoengine/core/extension';
|
|
4
|
+
import { PBRModel, type GLTFDocument } from '@margoengine/gltf/pbr-model';
|
|
5
|
+
/** One run of frames sharing a topology. Positions and normals hold `frameCount` frames of `vertexCount` vertices. */
|
|
6
|
+
export interface GeometryChunk {
|
|
7
|
+
/** Frames per second of the cache. */
|
|
8
|
+
rate: number;
|
|
9
|
+
/** Frames in the whole cache, or 0 when the file does not say. */
|
|
10
|
+
totalFrames: number;
|
|
11
|
+
firstFrame: number;
|
|
12
|
+
frameCount: number;
|
|
13
|
+
vertexCount: number;
|
|
14
|
+
indices: Uint32Array;
|
|
15
|
+
/** Two floats per vertex; zero when the cache has none. */
|
|
16
|
+
uvs: Float32Array;
|
|
17
|
+
positions: Float32Array;
|
|
18
|
+
normals: Float32Array;
|
|
19
|
+
/** Min xyz then max xyz over every frame of the chunk. */
|
|
20
|
+
bounds: Float32Array;
|
|
21
|
+
}
|
|
22
|
+
/** Bytes as they arrive: a `fetch` body, any async iterable, or one array. */
|
|
23
|
+
export type GeometryCacheBytes = AsyncIterable<Uint8Array> | ReadableStream<Uint8Array> | Uint8Array;
|
|
24
|
+
/** Options for {@link readGeometryCache}. */
|
|
25
|
+
export interface GeometryCacheReadOptions {
|
|
26
|
+
/** Stops the read: the iterator rejects with the signal's reason. */
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
/** Refuses a chunk larger than this, before allocating it. Default 1 GiB. */
|
|
29
|
+
maxChunkBytes?: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Reads a geometry cache as it arrives, one chunk per step, holding no more than the chunk being read. A chunk with no
|
|
33
|
+
* indices or UVs repeats the previous chunk's. Rejects with a `failed` MargoError on a damaged or cut off file.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* const response = await fetch('/flag.mgc');
|
|
38
|
+
* for await (const chunk of readGeometryCache(response.body!)) console.log(chunk.firstFrame, chunk.vertexCount);
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export declare function readGeometryCache(source: GeometryCacheBytes, { signal, maxChunkBytes }?: GeometryCacheReadOptions): AsyncGenerator<GeometryChunk, void, undefined>;
|
|
42
|
+
/** One chunk to write: frames of positions, with normals and UVs when the file should carry them. */
|
|
43
|
+
export interface GeometryChunkInput {
|
|
44
|
+
frameCount: number;
|
|
45
|
+
/** `frameCount` frames of three floats per vertex. */
|
|
46
|
+
positions: Float32Array;
|
|
47
|
+
/** Leave out to repeat the last chunk's topology. */
|
|
48
|
+
indices?: Uint32Array;
|
|
49
|
+
/** Same shape as `positions`. Default: computed when read. */
|
|
50
|
+
normals?: Float32Array;
|
|
51
|
+
/** Two floats per vertex. Default: the last chunk's if it has as many vertices, else zero. */
|
|
52
|
+
uvs?: Float32Array;
|
|
53
|
+
}
|
|
54
|
+
/** Writes a geometry cache (format in the package README). Chunks of about a second stream well. */
|
|
55
|
+
export declare function encodeGeometryCache(rate: number, chunks: readonly GeometryChunkInput[]): Uint8Array;
|
|
56
|
+
/** One frame of a mesh sequence, as a fluid or destruction bake writes one mesh a frame. */
|
|
57
|
+
export interface MeshSequenceFrame {
|
|
58
|
+
/** Three floats per vertex. */
|
|
59
|
+
positions: Float32Array;
|
|
60
|
+
/** Whole triangles into this frame's vertices. */
|
|
61
|
+
indices: Uint32Array;
|
|
62
|
+
/** Three floats per vertex. Default: computed when read. */
|
|
63
|
+
normals?: Float32Array;
|
|
64
|
+
/** Two floats per vertex. */
|
|
65
|
+
uvs?: Float32Array;
|
|
66
|
+
}
|
|
67
|
+
/** Options for {@link encodeMeshSequence} and {@link streamMeshSequence}. */
|
|
68
|
+
export interface MeshSequenceOptions {
|
|
69
|
+
/** Most frames in one chunk, 1..65,536. Default the frame rate rounded (about a second, which streams well). */
|
|
70
|
+
maxChunkFrames?: number;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Streams a mesh sequence (one whole mesh a frame, the topology free to change: a meshed fluid, a fracture) as
|
|
74
|
+
* geometry-cache bytes, chunk by chunk, for {@link GeometryCachePlayer}. Frames may arrive from any iterable or async
|
|
75
|
+
* iterable (files read one at a time), so a long bake is never in memory whole.
|
|
76
|
+
* @throws RangeError for a rate not above 0, a bad `maxChunkFrames`, an empty sequence or a malformed frame (named).
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* const parts: Uint8Array[] = [];
|
|
80
|
+
* const tri = (x: number) => ({positions: new Float32Array([x, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2])});
|
|
81
|
+
* for await (const part of streamMeshSequence(24, [tri(0), tri(0.1)])) parts.push(part);
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
export declare function streamMeshSequence(rate: number, frames: Iterable<MeshSequenceFrame> | AsyncIterable<MeshSequenceFrame>, options?: MeshSequenceOptions): AsyncGenerator<Uint8Array, void, undefined>;
|
|
85
|
+
/**
|
|
86
|
+
* A mesh sequence (one whole mesh a frame) as one geometry-cache file, its total frame count filled in.
|
|
87
|
+
* @throws RangeError as {@link streamMeshSequence}.
|
|
88
|
+
*/
|
|
89
|
+
export declare function encodeMeshSequence(rate: number, frames: Iterable<MeshSequenceFrame> | AsyncIterable<MeshSequenceFrame>, options?: MeshSequenceOptions): Promise<Uint8Array>;
|
|
90
|
+
/** Where a cache comes from. A URL, an array or a function can start again; a stream cannot, so it keeps what it read. */
|
|
91
|
+
export type GeometryCacheSource = string | URL | GeometryCacheBytes | ((signal: AbortSignal) => GeometryCacheBytes);
|
|
92
|
+
/** Options for {@link GeometryCachePlayer.attach}. */
|
|
93
|
+
export interface GeometryCachePlayerOptions {
|
|
94
|
+
/** Start over at the end. Default true. */
|
|
95
|
+
loop?: boolean;
|
|
96
|
+
/** Playback rate multiplier, finite and >= 0. Default 1. */
|
|
97
|
+
speed?: number;
|
|
98
|
+
/** Chunks to read ahead of the one playing, at least 1. Default 2. */
|
|
99
|
+
ahead?: number;
|
|
100
|
+
/** Stops the stream; the player keeps the frame it has. */
|
|
101
|
+
signal?: AbortSignal;
|
|
102
|
+
/** A glTF material for the mesh. Default: plain white. */
|
|
103
|
+
material?: NonNullable<GLTFDocument['materials']>[number];
|
|
104
|
+
/** See {@link GeometryCacheReadOptions.maxChunkBytes}. */
|
|
105
|
+
maxChunkBytes?: number;
|
|
106
|
+
}
|
|
107
|
+
/** What the player has done so far. */
|
|
108
|
+
export interface GeometryCacheStats {
|
|
109
|
+
/** Frames written to the GPU. */
|
|
110
|
+
uploads: number;
|
|
111
|
+
/** Frames the clock waited because the chunk had not arrived. */
|
|
112
|
+
stalls: number;
|
|
113
|
+
/** Chunks read, restarts included. */
|
|
114
|
+
chunks: number;
|
|
115
|
+
/** Times the mesh changed topology. */
|
|
116
|
+
swaps: number;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Plays a geometry cache on a mesh of its own (`player.model`), reading chunks only as far ahead as `ahead`. The clock
|
|
120
|
+
* waits when the stream falls behind, so playback never jumps. Between two frames of one topology the vertices
|
|
121
|
+
* interpolate; a chunk with another topology swaps the mesh at its first frame.
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* const flag = await GeometryCachePlayer.attach(stage.engine, '/flag.mgc');
|
|
126
|
+
* flag.model.root.setPosition([0, 2, 0]);
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
export declare class GeometryCachePlayer implements EnginePlugin {
|
|
130
|
+
private readonly open;
|
|
131
|
+
private readonly abort;
|
|
132
|
+
private readonly rewinds;
|
|
133
|
+
private readonly unlisten;
|
|
134
|
+
readonly name: string;
|
|
135
|
+
/** Seconds played. Set it, or call {@link seek}, to move. */
|
|
136
|
+
time: number;
|
|
137
|
+
playing: boolean;
|
|
138
|
+
speed: number;
|
|
139
|
+
loop: boolean;
|
|
140
|
+
/** The mesh being played. The player owns it: dispose the player, not the model. */
|
|
141
|
+
readonly model: PBRModel;
|
|
142
|
+
readonly stats: GeometryCacheStats;
|
|
143
|
+
/** Settles when the stream has been read to its end, which follows the clock by `ahead` chunks; rejects if reading fails. */
|
|
144
|
+
readonly done: Promise<void>;
|
|
145
|
+
/** Why reading stopped early, if it did. */
|
|
146
|
+
failure?: unknown;
|
|
147
|
+
disposed: boolean;
|
|
148
|
+
private engine?;
|
|
149
|
+
private buffer?;
|
|
150
|
+
private capacity;
|
|
151
|
+
private scratch;
|
|
152
|
+
private installed;
|
|
153
|
+
private chunks;
|
|
154
|
+
/** The frame the reader delivers next. */
|
|
155
|
+
private readTo;
|
|
156
|
+
/** Frames in the whole cache, once the end has been read. */
|
|
157
|
+
private frames;
|
|
158
|
+
private shown;
|
|
159
|
+
/** Ends a reader when a seek restarts it. */
|
|
160
|
+
private reader;
|
|
161
|
+
private wake?;
|
|
162
|
+
private settle;
|
|
163
|
+
private readonly ahead;
|
|
164
|
+
/** Reads the first chunk, then adds the mesh and the player to the engine. */
|
|
165
|
+
static attach(engine: EngineKernel, source: GeometryCacheSource, options?: GeometryCachePlayerOptions): Promise<GeometryCachePlayer>;
|
|
166
|
+
private constructor();
|
|
167
|
+
setup(engine: Engine): void;
|
|
168
|
+
/** Seconds in the whole cache, or Infinity until the stream has ended. */
|
|
169
|
+
get duration(): number;
|
|
170
|
+
/** Min xyz then max xyz of the chunk playing, over all its frames. */
|
|
171
|
+
get bounds(): Float32Array;
|
|
172
|
+
/**
|
|
173
|
+
* Moves the clock by `delta` seconds times `speed`, wrapping or stopping at the last frame as `loop` says: the CPU
|
|
174
|
+
* part of the frame update, which a seek from `@margoengine/cutscene/seek` replays. It reads and shows no frame, so a
|
|
175
|
+
* replayed step never waits for the stream; the next update shows the frame reached, or waits there for its data.
|
|
176
|
+
*/
|
|
177
|
+
advanceTime(delta: number): void;
|
|
178
|
+
/** The frame place and lap of the last `advanceTime`, read by the frame update that follows it. */
|
|
179
|
+
private at;
|
|
180
|
+
private wrapped;
|
|
181
|
+
/** Moves the clock. A place the player no longer holds starts the stream again, if it can. */
|
|
182
|
+
seek(seconds: number): this;
|
|
183
|
+
onPreUpdate(delta: number): void;
|
|
184
|
+
onDeviceRestored(engine: Engine): void;
|
|
185
|
+
dispose(): void;
|
|
186
|
+
[Symbol.dispose]: () => void;
|
|
187
|
+
private find;
|
|
188
|
+
private holdsAll;
|
|
189
|
+
/** The chunk that opens the next lap stays, so that a wrap can show it at once. */
|
|
190
|
+
private pinned;
|
|
191
|
+
/** Lets go of chunks already played, when they can be read again. */
|
|
192
|
+
private drop;
|
|
193
|
+
/** Chunks held unbroken after the one playing. One held further on, past a gap, does not stop the reader. */
|
|
194
|
+
private behind;
|
|
195
|
+
private pump;
|
|
196
|
+
private restart;
|
|
197
|
+
private packs;
|
|
198
|
+
/**
|
|
199
|
+
* The CPU pose synchronous scene queries test (shared/pose-source.js): `scratch`, the very floats the frame uploads.
|
|
200
|
+
*/
|
|
201
|
+
private readonly pose;
|
|
202
|
+
/** Writes the frame's vertices into `scratch`. Position and normal only: the rest is the chunk's. */
|
|
203
|
+
private pack;
|
|
204
|
+
private show;
|
|
205
|
+
/** Another topology: the mesh takes this chunk's vertices and triangles, and the output buffer grows if it must. */
|
|
206
|
+
private swap;
|
|
207
|
+
private bind;
|
|
208
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{n as e}from"./pose-source-MuCl8VDd.js";import{MargoError as t}from"@margoengine/math/errors";import{GLTFAsset as n,PBRModel as r}from"@margoengine/gltf/pbr-model";var i=16,a=64,o=1212368717,s=1263421507,c=1,l=1,u=2,d=20,f=e=>new t(`failed`,`Geometry cache ${e}; export the file again`);async function*p(e,t){if(e instanceof Uint8Array)yield e;else{if(`getReader`in e){let n=e.getReader(),r=()=>void n.cancel(t?.reason).catch(()=>{});t?.addEventListener(`abort`,r,{once:!0});try{for(;;){let{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t?.removeEventListener(`abort`,r),n.cancel().catch(()=>{}),n.releaseLock()}}yield*e}}var m=class{constructor(){this.parts=[],this.head=0,this.size=0}push(e){this.parts.push(e),this.size+=e.length}take(e){let t=new Uint8Array(e);for(let n=0;n<e;){let r=this.parts[0],i=Math.min(r.length-this.head,e-n);t.set(r.subarray(this.head,this.head+i),n),n+=i,this.head+=i,this.head===r.length&&(this.parts.shift(),this.head=0)}return this.size-=e,t}};function h(e){let{positions:t,indices:n,vertexCount:r,frameCount:i}=e,a=new Float32Array(t.length);for(let e=0;e<i;e++){let i=e*r*3;for(let e=0;e+2<n.length;e+=3){let r=i+n[e]*3,o=i+n[e+1]*3,s=i+n[e+2]*3,c=t[o]-t[r],l=t[o+1]-t[r+1],u=t[o+2]-t[r+2],d=t[s]-t[r],f=t[s+1]-t[r+1],p=t[s+2]-t[r+2],m=l*p-u*f,h=u*d-c*p,g=c*f-l*d;for(let e of[r,o,s])a[e]+=m,a[e+1]+=h,a[e+2]+=g}}for(let e=0;e<a.length;e+=3){let t=Math.hypot(a[e],a[e+1],a[e+2]);t>0?(a[e]/=t,a[e+1]/=t,a[e+2]/=t):a[e+2]=1}return a}async function*g(e,{signal:t,maxChunkBytes:n=2**30}={}){let r=new m,d=0,g=0,_=0,v,y,b=(e,t)=>{let n=t.getUint32(12,!0),r=t.getUint32(16,!0),i=t.getUint32(20,!0),a=t.getUint32(24,!0),o=e.buffer,s=0,c=e=>{let t=new Float32Array(o,s,e);return s+=e*4,t},p=i?new Uint32Array(o,0,i):y?.indices;if(s=i*4,!p)throw f(`starts with a chunk that has no indices`);for(let e=0;e<p.length;e++)if(p[e]>=r)throw f(`has an index past its vertices`);let m=a&u?c(r*2):y?.uvs.length===r*2?y.uvs:new Float32Array(r*2),_=c(n*r*3),v={rate:d,totalFrames:g,firstFrame:t.getUint32(8,!0),frameCount:n,vertexCount:r,indices:p,uvs:m,positions:_,normals:_,bounds:/* @__PURE__ */ new Float32Array(6)};for(let e=0;e<6;e++)v.bounds[e]=t.getFloat32(32+e*4,!0);v.normals=a&l?c(n*r*3):h(v);for(let e of[_,v.normals])for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw f(`holds a non-finite vertex`);return v};for await(let m of p(e,t))for(t?.throwIfAborted(),r.push(m);;){if(!d){if(r.size<i)break;let e=r.take(i),t=new DataView(e.buffer);if(t.getUint32(0,!0)!==o)throw f(`has the wrong magic number`);if(t.getUint32(4,!0)!==c)throw f(`has unknown version ${t.getUint32(4,!0)}`);if(d=t.getFloat32(8,!0),g=t.getUint32(12,!0),!(d>0&&Number.isFinite(d)))throw f(`has no frame rate`)}if(!v){if(r.size<a)break;let e=new DataView(r.take(a).buffer),t=e.getUint32(12,!0),i=e.getUint32(16,!0),o=e.getUint32(20,!0),c=e.getUint32(24,!0),d=o*4+(c&u?i*8:0)+t*i*(c&l?24:12);if(e.getUint32(0,!0)!==s)throw f(`has a damaged chunk header`);if(!t||i<3||i>1e6||o%3)throw f(`has a chunk with no frames, a broken triangle list, or not 3 to 1,000,000 vertices`);if(e.getUint32(8,!0)!==_)throw f(`skips from frame ${_} to ${e.getUint32(8,!0)}`);if(e.getUint32(4,!0)!==d)throw f(`has a chunk of the wrong size`);if(d>n)throw RangeError(`Geometry chunk of ${d} bytes is over maxChunkBytes; raise it or export smaller chunks`);v=e}let e=v.getUint32(4,!0);if(r.size<e)break;let p=b(r.take(e),v);v=void 0,y=p,_+=p.frameCount,yield p,t?.throwIfAborted()}if(!d||v||r.size)throw f(`ends inside a chunk`);if(g&&_!==g)throw f(`ends at frame ${_} of ${g}`)}function _(e,t){if(!(e>0&&Number.isFinite(e))||!t.length)throw RangeError(`Invalid geometry cache; pass a frame rate above 0 and at least one chunk`);let n=[],r=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i)),d=0;r.setUint32(0,o,!0),r.setUint32(4,c,!0),r.setFloat32(8,e,!0),n.push(new Uint8Array(r.buffer));for(let{frameCount:e,positions:r,indices:i,normals:o,uvs:c}of t){let t=r.length/3/e;if(!Number.isInteger(e)||e<1||!Number.isInteger(t)||t<1||o&&o.length!==r.length||c&&c.length!==t*2||i&&i.length%3)throw RangeError(`Invalid geometry chunk; give positions and normals frameCount frames of 3 floats per vertex, 2 UV floats per vertex and whole triangles`);let f=[i,c,r,o].filter(e=>e!==void 0),p=f.reduce((e,t)=>e+t.byteLength,0),m=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(a)),h=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0];for(let e=0;e<r.length;e++)h[e%3]=Math.min(h[e%3],r[e]),g[e%3]=Math.max(g[e%3],r[e]);m.setUint32(0,s,!0),m.setUint32(4,p,!0),m.setUint32(8,d,!0),m.setUint32(12,e,!0),m.setUint32(16,t,!0),m.setUint32(20,i?.length??0,!0),m.setUint32(24,(o?l:0)|(c?u:0),!0),[...h,...g].forEach((e,t)=>m.setFloat32(32+t*4,e,!0)),n.push(new Uint8Array(m.buffer));for(let e of f)n.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));d+=e}r.setUint32(12,d,!0);let f=new Uint8Array(n.reduce((e,t)=>e+t.length,0)),p=0;for(let e of n)f.set(e,p),p+=e.length;return f}var v=(e,t)=>e===t||!!e&&!!t&&e.length===t.length&&e.every((e,n)=>Object.is(e,t[n]));async function*y(e,t,n){if(!(e>0&&Number.isFinite(e)))throw RangeError(`Invalid mesh sequence rate; pass frames a second above 0`);let r=n?.maxChunkFrames??Math.max(1,Math.round(e));if(!Number.isInteger(r)||r<1||r>65536)throw RangeError(`Invalid maxChunkFrames; pass a whole number from 1 to 65536`);let a=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i));a.setUint32(0,o,!0),a.setUint32(4,c,!0),a.setFloat32(8,e,!0),yield new Uint8Array(a.buffer);let s=[],l=0,u,d,f=()=>{let t=s[0],n=t.positions.length,r=e=>{let t=new Float32Array(n*s.length);return s.forEach((r,i)=>t.set(e(r),i*n)),t},a=_(e,[{frameCount:s.length,positions:r(e=>e.positions),normals:t.normals?r(e=>e.normals):void 0,indices:u&&C(u,t.indices)?void 0:t.indices,uvs:t.uvs&&!v(d,t.uvs)?t.uvs:void 0}]).subarray(i);return new DataView(a.buffer,a.byteOffset).setUint32(8,l,!0),l+=s.length,u=t.indices,t.uvs&&(d=t.uvs),s=[],a},p=0;for await(let e of t){let{positions:t,indices:n,normals:i,uvs:a}=e??{},o=t?.length/3;if(!(t instanceof Float32Array)||!(n instanceof Uint32Array)||!Number.isInteger(o)||o<3||o>1e6||n.length%3||n.some(e=>e>=o)||i!==void 0&&(!(i instanceof Float32Array)||i.length!==t.length)||a!==void 0&&(!(a instanceof Float32Array)||a.length!==o*2)||!t.every(Number.isFinite))throw RangeError(`Invalid mesh sequence frame ${p}; pass 3 to 1,000,000 finite vertices, whole triangles into them, and normals and UVs sized to the vertices`);let c=s[0];c&&(s.length>=r||c.positions.length!==t.length||!C(c.indices,n)||!c.normals!=!i||!v(c.uvs,a))&&(yield f()),s.push(e),p++}if(!s.length)throw RangeError(`Empty mesh sequence; pass at least one frame`);return yield f(),l}async function*b(e,t,n={}){yield*y(e,t,n)}async function x(e,t,n={}){let r=[],i=y(e,t,n),a=await i.next();for(;!a.done;)r.push(a.value),a=await i.next();let o=new Uint8Array(r.reduce((e,t)=>e+t.length,0)),s=0;for(let e of r)o.set(e,s),s+=e.length;return new DataView(o.buffer).setUint32(12,a.value,!0),o}var S=0,C=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]),w=class i{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static async attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let{ahead:a=2,speed:o=1,signal:s,maxChunkBytes:c}=r;if(!Number.isInteger(a)||a<1||!Number.isFinite(o)||o<0)throw RangeError(`Invalid geometry cache options; ahead must be a whole number >= 1 and speed a finite number >= 0`);if(!e.gpu)throw new t(`unsupported`,`GeometryCachePlayer needs WebGPU; create the engine with the webgpu backend`);let l=new AbortController,u=()=>l.abort(s.reason),d=e,p,m={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:`geometry-cache:load:`+S++,setup(){p=d.sceneOf(m)}};for(;d.plugins.has(m.name);)m.name+=`:`;d.use(m),p.removePlugin(m.name);let h=()=>s?.removeEventListener(`abort`,u);s?.aborted?u():s?.addEventListener(`abort`,u,{once:!0});let _=()=>g(T(n,l.signal),{signal:l.signal,maxChunkBytes:c}),v=_();try{let e=await v.next();if(e.done)throw f(`holds no chunks`);let t=typeof n==`string`||typeof n==`function`||n instanceof URL||n instanceof Uint8Array,a,o={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:m.name,setup(){a=new i(d,e.value,v,_,l,r,t,h)}};try{p.use(o)}finally{p.plugins.get(o.name)===o&&p.removePlugin(o.name)}return a}catch(e){throw h(),l.abort(e),await v.return(),e}}constructor(e,t,i,a,o,{ahead:s=2,speed:c=1,loop:l=!0,material:u},f,p){this.open=a,this.abort=o,this.rewinds=f,this.unlisten=p,this.name=`geometry-cache:`+S++,this.time=0,this.playing=!0,this.stats={uploads:0,stalls:0,chunks:0,swaps:0},this.disposed=!1,this.capacity=0,this.readTo=0,this.frames=1/0,this.shown=``,this.reader=0,this.at=0,this.wrapped=!1,this.packs=0,this.pose=()=>this.buffer&&this.model.primitives[0].deformed===this.buffer?{vertices:this.scratch,revision:this.packs}:void 0,this.ahead=s,this.speed=c,this.loop=l,this.chunks=[t],this.installed=t,this.stats.chunks=1,this.readTo=t.frameCount,t.totalFrames&&(this.frames=t.totalFrames),this.scratch=new Float32Array(t.vertexCount*d),this.pack(t),this.model=new r(e,new n({asset:{version:`2.0`},materials:[u??{}],meshes:[{primitives:[{attributes:{POSITION:0},material:0}]}],nodes:[{mesh:0}]},[]),[],[[{vertices:this.scratch.slice(),indices:t.indices}]]),this.done=new Promise((e,t)=>{this.settle=n=>n===void 0?e():t(n)}),this.done.catch(()=>{});try{e.use(this.model),e.use(this),this.pump(i,this.reader)}catch(e){throw this.dispose(),e}}setup(e){this.engine=e,this.bind(e.gpu)}get duration(){return this.frames/this.installed.rate}get bounds(){return this.installed.bounds}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache delta; pass finite seconds >= 0`);let t=this.installed.rate;this.playing&&(this.time+=e*this.speed);let n=this.time*t,r=!1;n>=this.frames&&(this.loop?(n%=this.frames,this.time=n/t,r=!0):(n=this.frames-1,this.time=this.frames/t,this.playing=!1)),this.at=n,this.wrapped=r}seek(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache time; pass finite seconds >= 0`);return this.time=e,this}onPreUpdate(e){if(this.disposed)return;let t=this.time;this.advanceTime(e);let n=this.at,r=this.wrapped,i=Math.floor(n),a=this.find(i);r&&this.failure===void 0&&this.rewinds&&!this.holdsAll()&&this.restart(),a?(this.show(a,i,n-i),this.drop(i),this.wake?.()):(this.time=t,this.failure===void 0&&(this.stats.stalls++,this.rewinds&&i<this.readTo&&this.restart()),this.wake?.())}onDeviceRestored(e){this.buffer=void 0,this.capacity=0,this.shown=``,this.bind(e.gpu)}dispose(){this.disposed||(this.disposed=!0,this.unlisten(),this.reader++,this.abort.abort(new t(`disposed`,`GeometryCachePlayer is disposed; attach the cache again`)),this.wake?.(),this.settle(),this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.primitives[0].deformed=void 0,this.buffer?.destroy(),this.buffer=void 0,this.model.dispose(),this.chunks=[])}[Symbol.dispose??Symbol()](){this.dispose()}find(e){return this.chunks.find(t=>e>=t.firstFrame&&e<t.firstFrame+t.frameCount)}holdsAll(){return this.chunks.reduce((e,t)=>e+t.frameCount,0)>=this.frames}pinned(e){return this.loop&&e.firstFrame===0}drop(e){this.rewinds&&(this.chunks=this.chunks.filter(t=>t.firstFrame+t.frameCount>e||t===this.installed||this.pinned(t)))}behind(){let e=Math.floor(this.time*this.installed.rate),t=-1;this.find(e)||(t=0);for(let n=this.find(e);n;n=this.find(e))e=n.firstFrame+n.frameCount,t++;return t}async pump(e,t){try{for(;;){for(;t===this.reader&&this.behind()>=this.ahead;)await new Promise(e=>this.wake=e);if(t!==this.reader)break;let{done:n,value:r}=await e.next();if(t!==this.reader)break;if(n){this.frames=this.readTo,this.settle();return}this.stats.chunks++,this.readTo=r.firstFrame+r.frameCount,(!this.rewinds||r.firstFrame+r.frameCount>Math.floor(this.time*this.installed.rate))&&!this.chunks.some(e=>e.firstFrame===r.firstFrame)&&(this.chunks.push(r),this.chunks.sort((e,t)=>e.firstFrame-t.firstFrame))}e.return()}catch(e){if(t!==this.reader)return;this.failure=e,this.settle(e)}}restart(){this.reader++,this.readTo=0,this.wake?.(),this.chunks=this.chunks.filter(e=>this.pinned(e)),this.pump(this.open(),this.reader)}pack(e,t=0,n=e,r=0,i=0){this.packs++;let a=this.scratch,o=e.vertexCount,s=t*o*3,c=r*o*3,l=e.positions,u=n.positions,f=e.normals,p=n.normals;for(let t=0;t<o;t++){let n=t*d,r=s+t*3,o=c+t*3,m=f[r]+(p[o]-f[r])*i,h=f[r+1]+(p[o+1]-f[r+1])*i,g=f[r+2]+(p[o+2]-f[r+2])*i,_=Math.hypot(m,h,g);_>0?(m/=_,h/=_,g/=_):g=1,a[n]=l[r]+(u[o]-l[r])*i,a[n+1]=l[r+1]+(u[o+1]-l[r+1])*i,a[n+2]=l[r+2]+(u[o+2]-l[r+2])*i,a[n+3]=1,a[n+4]=m,a[n+5]=h,a[n+6]=g,a[n+12]=e.uvs[t*2],a[n+13]=e.uvs[t*2+1],a[n+16]=a[n+17]=a[n+18]=a[n+19]=1}}show(e,t,n){let r=t-e.firstFrame,i=e.firstFrame+`:`+r+`:`+n;if(i===this.shown)return;let a=e,o=r+1;if(o===e.frameCount){let t=this.find(e.firstFrame+e.frameCount);t&&t.vertexCount===e.vertexCount&&C(t.indices,e.indices)?(a=t,o=0):o=r}(this.installed.vertexCount!==e.vertexCount||!C(this.installed.indices,e.indices))&&this.swap(e),this.installed=e,this.pack(e,r,a,o,n),this.engine.gpu.queue.writeBuffer(this.buffer,0,this.scratch),this.shown=i,this.stats.uploads++}swap(e){let t=this.model.primitives[0];this.scratch=new Float32Array(e.vertexCount*d),this.pack(e),t.deformed=void 0,this.model.writeGeometry([{vertices:this.scratch.slice(),indices:e.indices}]),this.bind(this.engine.gpu),this.stats.swaps++}bind(t){let n=this.model.primitives[0];this.scratch.byteLength>this.capacity&&(this.buffer?.destroy(),this.capacity=this.scratch.byteLength,this.buffer=t.createBuffer({size:this.capacity,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),n.deformed=this.buffer,n.deformedOffset=0,e(n,this.pose),t.queue.writeBuffer(this.buffer,0,this.scratch)}};function T(e,n){return typeof e==`function`?e(n):typeof e!=`string`&&!(e instanceof URL)?e:(async function*(){let r=await fetch(e,{signal:n});if(!r.ok||!r.body)throw new t(`failed`,`Geometry cache request failed with status ${r.status}; check the URL`);yield*p(r.body,n)})()}export{w as GeometryCachePlayer,_ as encodeGeometryCache,x as encodeMeshSequence,g as readGeometryCache,b as streamMeshSequence};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(t);return e}function t(e,t){if(!Array.isArray(e))throw TypeError(t);return e}function n(n){let r=e(n,`Invalid glTF animation`);return{nodes:t(r.nodes,`Invalid glTF nodes`),accessors:t(r.accessors??[],`Invalid glTF accessors`),animations:t(r.animations??[],`Invalid glTF animations`),skins:t(r.skins??[],`Invalid glTF skins`)}}function r(n){let r=e(n,`Invalid glTF animation`);if(r.name!==void 0&&typeof r.name!=`string`)throw TypeError(`Invalid glTF animation; name must be a string when present`);return{name:r.name,channels:t(r.channels,`Invalid glTF animation`),samplers:t(r.samplers,`Invalid glTF animation`)}}function i(t){let n=e(t,`Invalid glTF animation`),r=n.target&&typeof n.target==`object`&&!Array.isArray(n.target)?n.target:{};return{sampler:n.sampler,target:{node:r.node,path:r.path}}}function a(t){let n=e(t,`Invalid glTF animation`);return{input:n.input,output:n.output,interpolation:n.interpolation}}function o(t){let n=e(t,`Invalid animation target`);return{matrix:n.matrix,skin:n.skin}}function s(e,t){let n=typeof t==`number`?e.accessors[t]:void 0;if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;return{componentType:r.componentType,normalized:r.normalized}}function c(e,t,n){if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>=t)throw TypeError(`Invalid animation ${n}; use an integer index inside the array it refers to`);return e}function l(e){if(e!==`translation`&&e!==`rotation`&&e!==`scale`&&e!==`weights`)throw TypeError(`Invalid animation target; path must be translation, rotation, scale or weights`);return e}function u(e){if(e===void 0)return`LINEAR`;if(e!==`STEP`&&e!==`LINEAR`&&e!==`CUBICSPLINE`)throw RangeError(`Invalid animation time/interpolation; interpolation must be STEP, LINEAR or CUBICSPLINE`);return e}function d(n,r){let i=e(n,`Invalid skin joints`),a=t(i.joints,`Invalid skin joints`);if(!a.length||new Set(a).size!==a.length||!a.every(e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<r))throw TypeError(`Invalid skin joints; use integer node indices inside the glTF nodes array`);return{joints:a,inverseBindMatrices:i.inverseBindMatrices}}function f(n){let r=e(n,`Invalid glTF morph target`);return{targets:t(r.targets??[],`Invalid glTF morph target`).map(t=>{let n=e(t,`Invalid glTF morph target`);return{POSITION:n.POSITION,NORMAL:n.NORMAL,TANGENT:n.TANGENT}}),attributes:e(r.attributes??{},`Invalid skin attributes`)}}export{c as a,l as c,d,n as i,a as l,i as n,u as o,r,o as s,s as t,f as u};
|
package/dist/gltf.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Interpolation } from './sampling.js';
|
|
2
|
+
export type AnimationPath = 'translation' | 'rotation' | 'scale' | 'weights';
|
|
3
|
+
export interface AnimationDocument {
|
|
4
|
+
nodes: unknown[];
|
|
5
|
+
accessors: unknown[];
|
|
6
|
+
animations: unknown[];
|
|
7
|
+
skins: unknown[];
|
|
8
|
+
}
|
|
9
|
+
export interface AnimationChannel {
|
|
10
|
+
sampler: unknown;
|
|
11
|
+
target: {
|
|
12
|
+
node: unknown;
|
|
13
|
+
path: unknown;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export interface AnimationSampler {
|
|
17
|
+
input: unknown;
|
|
18
|
+
output: unknown;
|
|
19
|
+
interpolation: unknown;
|
|
20
|
+
}
|
|
21
|
+
export interface AnimationDefinition {
|
|
22
|
+
name?: string;
|
|
23
|
+
channels: unknown[];
|
|
24
|
+
samplers: unknown[];
|
|
25
|
+
}
|
|
26
|
+
export interface AnimationNode {
|
|
27
|
+
matrix: unknown;
|
|
28
|
+
skin: unknown;
|
|
29
|
+
}
|
|
30
|
+
export interface AnimationAccessor {
|
|
31
|
+
componentType: unknown;
|
|
32
|
+
normalized: unknown;
|
|
33
|
+
}
|
|
34
|
+
export interface Skin {
|
|
35
|
+
joints: number[];
|
|
36
|
+
inverseBindMatrices: unknown;
|
|
37
|
+
}
|
|
38
|
+
export interface MorphTarget {
|
|
39
|
+
POSITION?: unknown;
|
|
40
|
+
NORMAL?: unknown;
|
|
41
|
+
TANGENT?: unknown;
|
|
42
|
+
}
|
|
43
|
+
export interface SkinAttributes extends Record<string, unknown> {
|
|
44
|
+
JOINTS_0?: unknown;
|
|
45
|
+
WEIGHTS_0?: unknown;
|
|
46
|
+
JOINTS_1?: unknown;
|
|
47
|
+
WEIGHTS_1?: unknown;
|
|
48
|
+
}
|
|
49
|
+
export interface MorphDefinition {
|
|
50
|
+
targets: MorphTarget[];
|
|
51
|
+
attributes: SkinAttributes;
|
|
52
|
+
}
|
|
53
|
+
export declare function animationDocument(value: unknown): AnimationDocument;
|
|
54
|
+
export declare function animationDefinition(value: unknown): AnimationDefinition;
|
|
55
|
+
export declare function animationChannel(value: unknown): AnimationChannel;
|
|
56
|
+
export declare function animationSampler(value: unknown): AnimationSampler;
|
|
57
|
+
export declare function animationNode(value: unknown): AnimationNode;
|
|
58
|
+
export declare function animationAccessor(doc: AnimationDocument, id: unknown): AnimationAccessor | undefined;
|
|
59
|
+
export declare function animationIndex(value: unknown, length: number, label: string): number;
|
|
60
|
+
export declare function animationPath(value: unknown): AnimationPath;
|
|
61
|
+
export declare function animationInterpolation(value: unknown): Interpolation;
|
|
62
|
+
export declare function skinDefinition(value: unknown, nodeCount: number): Skin;
|
|
63
|
+
export declare function morphDefinition(value: unknown): MorphDefinition;
|
package/dist/group.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { Engine, EnginePlugin } from '@margoengine/core/extension';
|
|
3
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
4
|
+
import { type KeyframeClip } from './keyframes.js';
|
|
5
|
+
import { Skeleton } from './skin.js';
|
|
6
|
+
/**
|
|
7
|
+
* A glTF PBR model's player that an {@link AnimationGroup} drives: an `Animation` from this package fits. Its own
|
|
8
|
+
* playback is paused while it is a member; the group seeks it instead.
|
|
9
|
+
*/
|
|
10
|
+
export interface AnimationGroupPlayer {
|
|
11
|
+
readonly model: PBRModel;
|
|
12
|
+
readonly clips: readonly {
|
|
13
|
+
readonly name: string;
|
|
14
|
+
readonly duration: number;
|
|
15
|
+
}[];
|
|
16
|
+
readonly options: {
|
|
17
|
+
readonly loop?: boolean;
|
|
18
|
+
};
|
|
19
|
+
clip: number;
|
|
20
|
+
playing: boolean;
|
|
21
|
+
seek(time: number): unknown;
|
|
22
|
+
setMorph(node: number, target: number, weight: number): void;
|
|
23
|
+
}
|
|
24
|
+
/** A member of an {@link AnimationGroup}: a model's `Animation`, or (for a code-authored clip) a `Skeleton`. */
|
|
25
|
+
export type AnimationGroupMember = AnimationGroupPlayer | Skeleton;
|
|
26
|
+
/** Options for {@link AnimationGroup}. */
|
|
27
|
+
export interface AnimationGroupOptions {
|
|
28
|
+
/**
|
|
29
|
+
* For a code-authored clip: wrap at its end (default true), else hold its first and last frames. A glTF clip loops
|
|
30
|
+
* as each member Animation's own `loop` option says.
|
|
31
|
+
*/
|
|
32
|
+
loop?: boolean;
|
|
33
|
+
/** Clip seconds per second, finite and >= 0. Default 1. */
|
|
34
|
+
speed?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One clip and one clock driving many models, for crowds of clones. Members are
|
|
38
|
+
* glTF PBR models' `Animation`s playing a clip they all have (by name or index), or, for a code-authored
|
|
39
|
+
* `KeyframeClip`, `Skeleton`s and `Animation`s whose bones or nodes the tracks name. Each member may run `offset`
|
|
40
|
+
* seconds ahead (negative: behind) of the group. A glTF clip plays through each member's own sampling path
|
|
41
|
+
* (`animation.seek`), and a code clip through bindings resolved once in `add`, so a frame allocates nothing in the group
|
|
42
|
+
* itself. Use it as an engine plugin (`engine.use(group)`; it advances in `onPreUpdate`) or call `update(delta)`.
|
|
43
|
+
* A member whose model is disposed leaves the group at the next `update` or `seek`; remove a member before disposing
|
|
44
|
+
* only its Animation.
|
|
45
|
+
*/
|
|
46
|
+
export declare class AnimationGroup implements EnginePlugin {
|
|
47
|
+
readonly clip: string | number | KeyframeClip;
|
|
48
|
+
readonly options: AnimationGroupOptions;
|
|
49
|
+
readonly name: string;
|
|
50
|
+
/** Group time in seconds; a member plays `time + offset`. */
|
|
51
|
+
time: number;
|
|
52
|
+
/** False stops `update` (and the plugin) from advancing `time`. */
|
|
53
|
+
playing: boolean;
|
|
54
|
+
private readonly members;
|
|
55
|
+
private engine?;
|
|
56
|
+
private disposed;
|
|
57
|
+
/** Creates a group and adds it to `engine` as a plugin, so it advances every frame. */
|
|
58
|
+
static attach(engine: Engine, clip: string | number | KeyframeClip, options?: AnimationGroupOptions): AnimationGroup;
|
|
59
|
+
/**
|
|
60
|
+
* @param clip A glTF clip name or index that every member Animation has, or a code-authored `KeyframeClip`.
|
|
61
|
+
* @param options `loop` (code clips) and `speed`.
|
|
62
|
+
*/
|
|
63
|
+
constructor(clip: string | number | KeyframeClip, options?: AnimationGroupOptions);
|
|
64
|
+
/** Number of members. */
|
|
65
|
+
get size(): number;
|
|
66
|
+
/** True when `target` is a member. */
|
|
67
|
+
has(target: AnimationGroupMember): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* Adds a member that plays `offset` seconds ahead of the group (adding it again only changes its offset) and poses it
|
|
70
|
+
* at the current time. An Animation member's own playback is paused (`playing = false`).
|
|
71
|
+
*/
|
|
72
|
+
add(target: AnimationGroupMember, offset?: number): this;
|
|
73
|
+
/** Removes a member; it keeps its last pose (an Animation stays paused). */
|
|
74
|
+
remove(target: AnimationGroupMember): this;
|
|
75
|
+
/** Changes a member's time offset in seconds and poses it. */
|
|
76
|
+
setOffset(target: AnimationGroupMember, offset: number): this;
|
|
77
|
+
/** Sets the group time and poses every member. */
|
|
78
|
+
seek(time: number): this;
|
|
79
|
+
/** Advances the group by `delta` seconds times `speed` (when playing) and poses every member. */
|
|
80
|
+
update(delta: number): this;
|
|
81
|
+
/**
|
|
82
|
+
* Moves the group clock by `delta` seconds times `speed` when playing, posing nothing: the CPU part of `update`,
|
|
83
|
+
* which a seek from `@margoengine/cutscene/seek` replays; the next update poses every member at the time reached.
|
|
84
|
+
*/
|
|
85
|
+
advanceTime(delta: number): void;
|
|
86
|
+
/** Engine plugin hook; the group needs no GPU resources. */
|
|
87
|
+
setup(engine: Engine): void;
|
|
88
|
+
/** Engine plugin hook: `update(delta)` before the engine updates world matrices. */
|
|
89
|
+
onPreUpdate(delta: number): void;
|
|
90
|
+
/** Drops every member (they keep their last pose) and detaches from the engine. */
|
|
91
|
+
dispose(): void;
|
|
92
|
+
[Symbol.dispose]: () => void;
|
|
93
|
+
/** Poses every member; a member whose model was disposed leaves the group. */
|
|
94
|
+
private poseAll;
|
|
95
|
+
private pose;
|
|
96
|
+
private bind;
|
|
97
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return e?.view?.viewport}function t(t){let n=e(t);return n?[n[2],n[3]]:[t.width,t.height]}function n(t,n){let r=e(n);if(!r)return;t.setViewport(r[0],r[1],r[2],r[3],0,1);let i=n.view.scissor??r;t.setScissorRect(i[0],i[1],i[2],i[3])}var r=e=>typeof e==`string`&&e.endsWith(`float`);export{n,t as r,r as t};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
3
|
+
import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
|
|
4
|
+
import type { Interpolation } from './sampling.js';
|
|
5
|
+
import type { SkinningMode } from './shader.js';
|
|
6
|
+
import type { PointerChannels } from './pointer.js';
|
|
7
|
+
import { type KeyframeClip } from './keyframes.js';
|
|
8
|
+
export { createMaterialAnimation } from './material-animation.js';
|
|
9
|
+
export { sampleTrack, sampleTrackInto, type ClipMarker, type Interpolation } from './sampling.js';
|
|
10
|
+
export type { SkinningMode } from './shader.js';
|
|
11
|
+
export { Skeleton, Skin, type BoneData, type BonePose } from './skin.js';
|
|
12
|
+
export { createKeyframeClip, sampleKeyframes, applyKeyframeClip, segmentTime, bakeKeyframeClip, bakeKeyframeTrack, type KeyInterpolation, type KeyframeBlend, type KeyframePath, type KeyframeModelTarget, type Keyframe, type KeyframeTrackData, type KeyframeClipData, type KeyframeTrack, type KeyframeClip, type BakedChannel, type BakedSampler, type PropertyValueType, type PropertyTrackData, type PropertyKeyframeTrack, } from './keyframes.js';
|
|
13
|
+
export { compileRigidClip, type RigidBinding, type RigidBone, type RigidClipOptions, type RigidKey, } from './rigid.js';
|
|
14
|
+
export { AnimationGroup, type AnimationGroupMember, type AnimationGroupOptions, type AnimationGroupPlayer, } from './group.js';
|
|
15
|
+
interface Track {
|
|
16
|
+
node: number;
|
|
17
|
+
path: 'translation' | 'rotation' | 'scale' | 'weights';
|
|
18
|
+
times: Float32Array;
|
|
19
|
+
values: Float32Array;
|
|
20
|
+
width: number;
|
|
21
|
+
interpolation: Interpolation;
|
|
22
|
+
sample: Float32Array;
|
|
23
|
+
rotation?: number[];
|
|
24
|
+
/** The key the previous frame's sample found (key-cursor.ts). */
|
|
25
|
+
cursor: number;
|
|
26
|
+
}
|
|
27
|
+
interface Clip {
|
|
28
|
+
name: string;
|
|
29
|
+
duration: number;
|
|
30
|
+
tracks: Track[];
|
|
31
|
+
/** Binds the clip's KHR_animation_pointer material, light, camera and visibility channels on first playback. */
|
|
32
|
+
bind?: () => KeyframeClip;
|
|
33
|
+
bound?: KeyframeClip;
|
|
34
|
+
}
|
|
35
|
+
/** Portable clip playback; clip index disambiguates repeated names. */
|
|
36
|
+
export interface AnimationState {
|
|
37
|
+
version: 1;
|
|
38
|
+
clip: number;
|
|
39
|
+
time: number;
|
|
40
|
+
playing: boolean;
|
|
41
|
+
loop: boolean;
|
|
42
|
+
speed: number;
|
|
43
|
+
}
|
|
44
|
+
/** Options for {@link Animation}. */
|
|
45
|
+
export interface AnimationOptions {
|
|
46
|
+
/** Wrap time at the end of the clip. Default true; false holds the last frame. */
|
|
47
|
+
loop?: boolean;
|
|
48
|
+
/** Playback rate multiplier, finite and >= 0. Default 1. */
|
|
49
|
+
speed?: number;
|
|
50
|
+
/**
|
|
51
|
+
* KHR_animation_pointer playback, opt-in so apps without pointer channels do not ship it: pass `pointerChannels`
|
|
52
|
+
* from `@margoengine/animation/pointer`. Without it, pointer channels are skipped (still counted in the clip's
|
|
53
|
+
* duration) and listed in `warnings`.
|
|
54
|
+
*/
|
|
55
|
+
pointers?: PointerChannels;
|
|
56
|
+
/**
|
|
57
|
+
* How bones blend, opt-in so apps that do not use it do not ship it: pass `dualQuaternionSkinning` from
|
|
58
|
+
* `@margoengine/animation/dqs`. Unset blends matrices linearly. Fixed for the Animation's life.
|
|
59
|
+
*/
|
|
60
|
+
skinning?: SkinningMode;
|
|
61
|
+
/**
|
|
62
|
+
* Another model of the same file whose nodes are the joints, so this model's skin follows that model's pose, whatever
|
|
63
|
+
* moves it. This Animation then has no clips of its own. Default: the model's own nodes.
|
|
64
|
+
*/
|
|
65
|
+
skeleton?: PBRModel;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Plays a glTF model's animation clips on the GPU: node translation, rotation and scale, skinning and morph targets. Add it to the engine with {@link Animation.attach}; it advances each frame and removes itself when the model is disposed.
|
|
69
|
+
*
|
|
70
|
+
* Defaults: plays clip 0, looping, at speed 1 (see {@link AnimationOptions}).
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* const model = await loadGLTF(engine, 'character.glb');
|
|
75
|
+
* const animation = Animation.attach(model);
|
|
76
|
+
* animation.play('Walk');
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export declare class Animation implements EnginePlugin {
|
|
80
|
+
readonly model: PBRModel;
|
|
81
|
+
readonly options: AnimationOptions;
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly clips: readonly Clip[];
|
|
84
|
+
/**
|
|
85
|
+
* One line per KHR_animation_pointer channel the clips skip: valid pointers this player cannot drive (an extension
|
|
86
|
+
* it does not know, `extras`, a property the asset leaves undefined, a target no scene node or primitive uses).
|
|
87
|
+
*/
|
|
88
|
+
readonly warnings: readonly string[];
|
|
89
|
+
playing: boolean;
|
|
90
|
+
/** Seconds into the current clip. Wraps at the clip's end while `loop` is on; jump with `seek`. */
|
|
91
|
+
time: number;
|
|
92
|
+
clip: number;
|
|
93
|
+
/** `time` moved since the pose was last applied (a replayed `advanceTime` step poses on the next frame). */
|
|
94
|
+
private due;
|
|
95
|
+
private device?;
|
|
96
|
+
private arena?;
|
|
97
|
+
private resources;
|
|
98
|
+
/**
|
|
99
|
+
* The records that compute and upload a palette, in bone-offset order. Their palettes sit back to back in two
|
|
100
|
+
* Float32Arrays (live and uploaded), so when their bone ranges are contiguous in one page one write uploads them all.
|
|
101
|
+
*/
|
|
102
|
+
private leaders;
|
|
103
|
+
/** The two whole palette arrays of the last placement, so a single write needs no new view. */
|
|
104
|
+
private wholes;
|
|
105
|
+
/** The distinct nodes of `resources`, so the hidden check walks each node's ancestry once. */
|
|
106
|
+
private deformedNodes;
|
|
107
|
+
/** The resources' slots, in order (the arena's view of this Animation). */
|
|
108
|
+
private slots;
|
|
109
|
+
/** This Animation's own dispatches, for deformation outside a shared frame-graph pass. */
|
|
110
|
+
private readonly cache;
|
|
111
|
+
private readonly inverse;
|
|
112
|
+
private readonly joint;
|
|
113
|
+
private readonly product;
|
|
114
|
+
private readonly workspace;
|
|
115
|
+
private readonly quaternion;
|
|
116
|
+
private disposed;
|
|
117
|
+
/**
|
|
118
|
+
* The model's primitives grouped by node: node n's are `primitives[groupItems[k]]` for k from groupStart[n] to
|
|
119
|
+
* groupStart[n + 1]. Built by validate(); each frame re-checks it and the morph widths without allocating.
|
|
120
|
+
*/
|
|
121
|
+
private groupStart;
|
|
122
|
+
private groupItems;
|
|
123
|
+
private unsubscribe?;
|
|
124
|
+
/** The model whose nodes are the joints: this one, or `options.skeleton`. */
|
|
125
|
+
private readonly joints;
|
|
126
|
+
/**
|
|
127
|
+
* Set by `MorphWeightPlayer` (morph-gpu.ts) once it writes this Animation's morph weights on the GPU: from then on
|
|
128
|
+
* `primitive.weights` no longer says what is drawn, so a morphed primitive has no CPU pose.
|
|
129
|
+
*/
|
|
130
|
+
private gpuWeights;
|
|
131
|
+
private readonly prepareDeformation;
|
|
132
|
+
/** The deformation group of the frame graph this Animation's pass is in. */
|
|
133
|
+
private group?;
|
|
134
|
+
private readonly createDeformationRenderer;
|
|
135
|
+
private readonly rest;
|
|
136
|
+
constructor(model: PBRModel, options?: AnimationOptions);
|
|
137
|
+
static attach(model: PBRModel, options?: AnimationOptions): Animation;
|
|
138
|
+
private validate;
|
|
139
|
+
/** Groups the primitives by node (once, and again only if `model.primitives` changes). */
|
|
140
|
+
private groupPrimitives;
|
|
141
|
+
/** True when the grouping still names every primitive of the model under its current node. */
|
|
142
|
+
private grouped;
|
|
143
|
+
/** Every primitive of a node has as many morph weights as the node's first. */
|
|
144
|
+
private checkWidths;
|
|
145
|
+
/** The per-frame form of validate(): the same checks and errors, with no allocation unless the primitives changed. */
|
|
146
|
+
private checkFrame;
|
|
147
|
+
private checkOptions;
|
|
148
|
+
play(clip?: string | number): this;
|
|
149
|
+
captureState(): AnimationState;
|
|
150
|
+
restoreState(state: AnimationState): this;
|
|
151
|
+
seek(time: number): this;
|
|
152
|
+
/** Set every model target with this glTF extras.targetNames name, across all mesh nodes. */
|
|
153
|
+
setMorph(name: string, weight: number): void;
|
|
154
|
+
/** Set one target on a specific glTF mesh node. */
|
|
155
|
+
setMorph(node: number, target: number, weight: number): void;
|
|
156
|
+
private morphError;
|
|
157
|
+
private apply;
|
|
158
|
+
setup(engine: Engine, device?: GPUDevice | null): void;
|
|
159
|
+
onPreUpdate(delta: number): void;
|
|
160
|
+
/**
|
|
161
|
+
* Moves the clip clock by `delta` seconds times `speed`, wrapping or stopping at the clip's end as `loop` says: the
|
|
162
|
+
* CPU part of the frame update, which a seek from `@margoengine/cutscene/seek` replays. It poses nothing; the next
|
|
163
|
+
* frame update applies the pose at the time reached.
|
|
164
|
+
*/
|
|
165
|
+
advanceTime(delta: number): void;
|
|
166
|
+
registerPasses(graph: FrameGraph): void;
|
|
167
|
+
/**
|
|
168
|
+
* Every Animation of a frame graph deforms in one compute pass: the first of their passes in each graph execution
|
|
169
|
+
* uploads each one's weights and bones and encodes one batched dispatch per buffer page and pipeline for all of
|
|
170
|
+
* them; the rest of that execution's passes skip. (A compute pass per model cost about 10 us of GPU time each, and a
|
|
171
|
+
* dispatch per primitive about 6 us: 100 two-primitive models 1.3 ms.)
|
|
172
|
+
*/
|
|
173
|
+
private deformAll;
|
|
174
|
+
private deform;
|
|
175
|
+
/** Checks and uploads this frame's weights and bone palettes; false when there is nothing to dispatch. */
|
|
176
|
+
private upload;
|
|
177
|
+
/**
|
|
178
|
+
* The primitive's pose on the CPU for synchronous queries (`@margoengine/bvh`), from the node matrices and morph
|
|
179
|
+
* weights as they are now: the palette arithmetic of `upload` and the shader's blend (pose.ts). Costs one palette
|
|
180
|
+
* (16 floats per joint) and a comparison per call, and one pass over the vertices when a bone, a weight or the bind
|
|
181
|
+
* vertices changed. Undefined once another deformer or no deformer writes the primitive.
|
|
182
|
+
*/
|
|
183
|
+
private cpuPose;
|
|
184
|
+
/** True when this Animation's palettes are two or more, in one bone page, back to back in palette-array order. */
|
|
185
|
+
private contiguous;
|
|
186
|
+
/** Swaps a palette's live and spare views (and its followers'). */
|
|
187
|
+
private swap;
|
|
188
|
+
/**
|
|
189
|
+
* Writes `values` (one palette, or the whole array `written` were computed into) at bone `offset`. Through a native
|
|
190
|
+
* writer the written records count as uploaded: what went up becomes `palette` by a swap of views, not a copy.
|
|
191
|
+
*/
|
|
192
|
+
private uploadBones;
|
|
193
|
+
/** Points each record that shares a palette at its leader's current views. */
|
|
194
|
+
private followLeaders;
|
|
195
|
+
private release;
|
|
196
|
+
onDeviceRestored(engine: Engine): void;
|
|
197
|
+
dispose(): void;
|
|
198
|
+
[Symbol.dispose]: () => void;
|
|
199
|
+
/** @deprecated Use dispose(); kept as an alias until 1.0. */
|
|
200
|
+
destroy(): void;
|
|
201
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./src-WGCsukxV.js";import{a as i,o as a}from"./sampling-DjDWYqt2.js";import{a as o,c as s,i as c,n as l,o as u,r as d,s as f,t as p}from"./keyframes-BO50xipp.js";export{r as Animation,t as AnimationGroup,f as Skeleton,s as Skin,p as applyKeyframeClip,l as bakeKeyframeClip,d as bakeKeyframeTrack,n as compileRigidClip,c as createKeyframeClip,e as createMaterialAnimation,o as sampleKeyframes,i as sampleTrack,a as sampleTrackInto,u as segmentTime};
|