@margoengine/animation 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1172 -2
- package/dist/batch.d.ts +162 -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/cor.d.ts +52 -0
- package/dist/cor.js +17 -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 +42 -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 +203 -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-YpidiYS4.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 +94 -0
- package/dist/morph-gpu.js +50 -0
- package/dist/morph-table.d.ts +29 -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-DyWpFsQi.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 +12 -0
- package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
- package/dist/retarget.d.ts +115 -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-DuGkHFKx.js +73 -0
- package/dist/shader.d.ts +62 -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-fuuIJ3rU.js +4 -0
- package/dist/vat-SpfL7y9U.js +53 -0
- package/dist/vat.d.ts +194 -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 +139 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
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) while it writes this Animation's morph weights on the GPU: then
|
|
128
|
+
* `primitive.weights` does not say what is drawn, so the CPU pose takes the player's samples, its shader's arithmetic
|
|
129
|
+
* on the CPU (KB-BVH-SYNCPOSE-MORPHGPU1). At `remove` the player writes the weights last drawn back into
|
|
130
|
+
* `primitive.weights` and clears this.
|
|
131
|
+
*/
|
|
132
|
+
private weightSource?;
|
|
133
|
+
private readonly prepareDeformation;
|
|
134
|
+
/** The deformation group of the frame graph this Animation's pass is in. */
|
|
135
|
+
private group?;
|
|
136
|
+
private readonly createDeformationRenderer;
|
|
137
|
+
private readonly rest;
|
|
138
|
+
constructor(model: PBRModel, options?: AnimationOptions);
|
|
139
|
+
static attach(model: PBRModel, options?: AnimationOptions): Animation;
|
|
140
|
+
private validate;
|
|
141
|
+
/** Groups the primitives by node (once, and again only if `model.primitives` changes). */
|
|
142
|
+
private groupPrimitives;
|
|
143
|
+
/** True when the grouping still names every primitive of the model under its current node. */
|
|
144
|
+
private grouped;
|
|
145
|
+
/** Every primitive of a node has as many morph weights as the node's first. */
|
|
146
|
+
private checkWidths;
|
|
147
|
+
/** The per-frame form of validate(): the same checks and errors, with no allocation unless the primitives changed. */
|
|
148
|
+
private checkFrame;
|
|
149
|
+
private checkOptions;
|
|
150
|
+
play(clip?: string | number): this;
|
|
151
|
+
captureState(): AnimationState;
|
|
152
|
+
restoreState(state: AnimationState): this;
|
|
153
|
+
seek(time: number): this;
|
|
154
|
+
/** Set every model target with this glTF extras.targetNames name, across all mesh nodes. */
|
|
155
|
+
setMorph(name: string, weight: number): void;
|
|
156
|
+
/** Set one target on a specific glTF mesh node. */
|
|
157
|
+
setMorph(node: number, target: number, weight: number): void;
|
|
158
|
+
private morphError;
|
|
159
|
+
private apply;
|
|
160
|
+
setup(engine: Engine, device?: GPUDevice | null): void;
|
|
161
|
+
onPreUpdate(delta: number): void;
|
|
162
|
+
/**
|
|
163
|
+
* Moves the clip clock by `delta` seconds times `speed`, wrapping or stopping at the clip's end as `loop` says: the
|
|
164
|
+
* CPU part of the frame update, which a seek from `@margoengine/cutscene/seek` replays. It poses nothing; the next
|
|
165
|
+
* frame update applies the pose at the time reached.
|
|
166
|
+
*/
|
|
167
|
+
advanceTime(delta: number): void;
|
|
168
|
+
registerPasses(graph: FrameGraph): void;
|
|
169
|
+
/**
|
|
170
|
+
* Every Animation of a frame graph deforms in one compute pass: the first of their passes in each graph execution
|
|
171
|
+
* uploads each one's weights and bones and encodes one batched dispatch per buffer page and pipeline for all of
|
|
172
|
+
* them; the rest of that execution's passes skip. (A compute pass per model cost about 10 us of GPU time each, and a
|
|
173
|
+
* dispatch per primitive about 6 us: 100 two-primitive models 1.3 ms.)
|
|
174
|
+
*/
|
|
175
|
+
private deformAll;
|
|
176
|
+
private deform;
|
|
177
|
+
/** Checks and uploads this frame's weights and bone palettes; false when there is nothing to dispatch. */
|
|
178
|
+
private upload;
|
|
179
|
+
/**
|
|
180
|
+
* The primitive's pose on the CPU for synchronous queries (`@margoengine/bvh`), from the node matrices and morph
|
|
181
|
+
* weights as they are now: the palette arithmetic of `upload` and the shader's blend (pose.ts). Costs one palette
|
|
182
|
+
* (16 floats per joint) and a comparison per call, and one pass over the vertices when a bone, a weight or the bind
|
|
183
|
+
* vertices changed. Undefined once another deformer or no deformer writes the primitive.
|
|
184
|
+
*/
|
|
185
|
+
private cpuPose;
|
|
186
|
+
/** True when this Animation's palettes are two or more, in one bone page, back to back in palette-array order. */
|
|
187
|
+
private contiguous;
|
|
188
|
+
/** Swaps a palette's live and spare views (and its followers'). */
|
|
189
|
+
private swap;
|
|
190
|
+
/**
|
|
191
|
+
* Writes `values` (one palette, or the whole array `written` were computed into) at bone `offset`. Through a native
|
|
192
|
+
* writer the written records count as uploaded: what went up becomes `palette` by a swap of views, not a copy.
|
|
193
|
+
*/
|
|
194
|
+
private uploadBones;
|
|
195
|
+
/** Points each record that shares a palette at its leader's current views. */
|
|
196
|
+
private followLeaders;
|
|
197
|
+
private release;
|
|
198
|
+
onDeviceRestored(engine: Engine): void;
|
|
199
|
+
dispose(): void;
|
|
200
|
+
[Symbol.dispose]: () => void;
|
|
201
|
+
/** @deprecated Use dispose(); kept as an alias until 1.0. */
|
|
202
|
+
destroy(): void;
|
|
203
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./src-fuuIJ3rU.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-YpidiYS4.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};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
2
|
+
import type { Animation } from './index.js';
|
|
3
|
+
import { type VATBakeOptions, type VATCrowdOptions } from './vat.js';
|
|
4
|
+
import { SkinnedCrowd, type BoneBake, type SkinnedCrowdInstance } from './instanced-skin.js';
|
|
5
|
+
/** Most morph targets one bake carries live: 16 four-weight vectors in each instance row. */
|
|
6
|
+
export declare const MORPH_TARGET_LIMIT = 64;
|
|
7
|
+
/** Options for {@link bakeMorphBones}: `bakeBones`'s, and which targets stay live. */
|
|
8
|
+
export interface MorphBakeOptions extends VATBakeOptions {
|
|
9
|
+
/**
|
|
10
|
+
* The targets each member sets live, by name or by index into the model's targets (every primitive's, joined by
|
|
11
|
+
* name in first-seen order). Default: all of them. A target left out is baked in at the weight it has now.
|
|
12
|
+
*/
|
|
13
|
+
morphs?: readonly (string | number)[];
|
|
14
|
+
}
|
|
15
|
+
/** A {@link bakeBones} bake whose vertices are the unmorphed shape, with its live targets after the bone rows. */
|
|
16
|
+
export interface MorphBake extends BoneBake {
|
|
17
|
+
morphs: {
|
|
18
|
+
/** Live target names; a member's weight `i` moves target `names[i]`. */
|
|
19
|
+
names: string[];
|
|
20
|
+
/** The weights the model had when baked: what a new member starts with. */
|
|
21
|
+
weights: Float32Array;
|
|
22
|
+
/** Per vertex: the texel of its first block entry, its number of blocks, its index in its primitive, 0. */
|
|
23
|
+
vertices: Uint32Array;
|
|
24
|
+
/** Blocks: one per live target of each primitive, an entry texel `[first offset texel, weight index, 0, 0]`. */
|
|
25
|
+
blocks: number;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Bakes like {@link bakeBones}, but keeps morph targets live: the vertices are baked with the live targets at zero,
|
|
30
|
+
* and each target's position and normal offsets go into the bone texture after the bone rows (two texels per vertex of
|
|
31
|
+
* each primitive that has the target, so an unmorphed body costs nothing for its head's targets).
|
|
32
|
+
* @throws RangeError for a model with no morph targets, an unknown or repeated target, more than
|
|
33
|
+
* {@link MORPH_TARGET_LIMIT} live targets, data past 8192 texture rows, or anything `bakeBones` rejects.
|
|
34
|
+
*/
|
|
35
|
+
export declare function bakeMorphBones(animation: Animation, options?: MorphBakeOptions): MorphBake;
|
|
36
|
+
/**
|
|
37
|
+
* The vertex stage of a {@link MorphedCrowd} whose instance rows end in `vectors` four-weight vectors: SkinnedCrowd's
|
|
38
|
+
* own text, with the weights in the instance, the per-vertex block record at location 7 and the morph before the skin.
|
|
39
|
+
* Exposed for tooling and tests.
|
|
40
|
+
*/
|
|
41
|
+
export declare function morphedCrowdVertex(vectors: number): string;
|
|
42
|
+
/** Morph weights for a member: an array in `bake.morphs.names` order (a shorter one sets the first ones), or weights by name. */
|
|
43
|
+
export type MorphWeights = ArrayLike<number> | Readonly<Record<string, number>>;
|
|
44
|
+
/** One crowd member for {@link MorphedCrowd.add} and {@link MorphedCrowd.set}. */
|
|
45
|
+
export interface MorphedCrowdInstance extends SkinnedCrowdInstance {
|
|
46
|
+
/** Weights to change; the others keep their value (for a new member, the bake's `morphs.weights`). Any finite number. */
|
|
47
|
+
morphs?: MorphWeights;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The bake's vertices with `weights` applied, as `bake.vertices` holds them (position and normal, 6 floats each): the
|
|
51
|
+
* CPU twin of the shader's morph step.
|
|
52
|
+
* @throws RangeError for weights that do not fit the bake's targets or are not finite.
|
|
53
|
+
*/
|
|
54
|
+
export declare function morphVertices(bake: MorphBake, weights?: MorphWeights, out?: Float32Array<ArrayBuffer>): Float32Array;
|
|
55
|
+
/**
|
|
56
|
+
* Where a member's vertices are at `time` (the crowd's clock), morphed by its weights and then skinned, in the model
|
|
57
|
+
* root's space before its matrix: `poseBones` on the morphed shape, for checks, picking and bounds.
|
|
58
|
+
*/
|
|
59
|
+
export declare function poseMorphedBones(bake: MorphBake, member: MorphedCrowdInstance, time: number, out?: Float32Array<ArrayBuffer>): Float32Array;
|
|
60
|
+
/**
|
|
61
|
+
* A {@link SkinnedCrowd} whose members each have their own morph weights, set from JavaScript at any time: one
|
|
62
|
+
* instanced draw, the weighted target offsets added in the vertex shader before the bones. Everything else is as
|
|
63
|
+
* `SkinnedCrowd`: two clips and a blend per member, `shadows.add(crowd)`, `lighting.add(crowd)`.
|
|
64
|
+
* @example
|
|
65
|
+
* const crowd = MorphedCrowd.attach(engine, bakeMorphBones(animation));
|
|
66
|
+
* const face = crowd.add({ morphs: { Smile: 1 } });
|
|
67
|
+
* crowd.setMorph(face, 'Smile', 0.25);
|
|
68
|
+
*/
|
|
69
|
+
export declare class MorphedCrowd extends SkinnedCrowd {
|
|
70
|
+
readonly bake: MorphBake;
|
|
71
|
+
/** Same as `engine.use(new MorphedCrowd(...))`; returns the crowd. */
|
|
72
|
+
static attach(engine: EngineKernel, bake: MorphBake, options?: VATCrowdOptions): MorphedCrowd;
|
|
73
|
+
constructor(bake: MorphBake, options?: VATCrowdOptions);
|
|
74
|
+
/** Adds a member at the bake's weights, changed by `instance.morphs`; returns its index. */
|
|
75
|
+
add(instance?: MorphedCrowdInstance): number;
|
|
76
|
+
/** Changes the given fields of one member; `morphs` changes the weights it names and keeps the rest. */
|
|
77
|
+
set(index: number, instance: MorphedCrowdInstance): this;
|
|
78
|
+
/** Sets one weight of one member (any finite number; 0 costs nothing in the shader). Uploads with the next frame. */
|
|
79
|
+
setMorph(index: number, target: number | string, weight: number): this;
|
|
80
|
+
/** One weight of one member. */
|
|
81
|
+
getMorph(index: number, target: number | string): number;
|
|
82
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{t as e}from"./vertex-map-BC_WH7ER.js";import{r as t}from"./vat-SpfL7y9U.js";import{SkinnedCrowd as n,bakeBones as r,poseBones as i,skinnedCrowdLayout as a,skinnedCrowdVertex as o}from"./instanced-skin.js";var s=64;function c(n,i={}){let a=n.model,o=a.asset,s=[],c=a.primitives.map(e=>{let t=e.definition.targets??[],n=t.map((t,n)=>e.targetNames[n]??`Target `+n);for(let e of n)s.includes(e)||s.push(e);return{p:e,targets:t,names:n,count:e.vertices.length/20}}),l=(i.morphs??s).map(e=>typeof e==`string`?e:s[e]);if(!s.length)throw RangeError(`The model has no morph targets; bake it with bakeBones`);if(!l.length||l.some((e,t)=>!s.includes(e)||l.indexOf(e)!==t))throw RangeError(`Unknown or repeated morph target; pass target names, or indices below the number of targets, once each`);if(l.length>64)throw RangeError(`${l.length} live morph targets exceed 64; name the ones members set in the morphs option`);let u=new Float32Array(l.length),d=c.map(({p:e})=>e.weights.slice()),f=/* @__PURE__ */ new Set,p;try{for(let{p:e,names:t}of c)t.forEach((t,n)=>{let r=l.indexOf(t);r<0||(f.has(r)||(u[r]=e.weights[n]),f.add(r),e.weights[n]=0)});p=r(n,i)}finally{c.forEach(({p:e},t)=>e.weights.set(d[t]))}let m=c.map(e=>e.names.map(e=>l.indexOf(e)).filter(e=>e>=0).length),h=m.reduce((e,t)=>e+t,0),g=p.rows*p.bones*3,_=g+h+c.reduce((e,t,n)=>e+m[n]*t.count*2,0),v=Math.ceil(_/t);if(v>8192)throw RangeError(`Morph data exceeds 8192 texture rows; keep fewer targets live, or bake fewer clips`);let y=new Float32Array(t*v*4),b=new Uint32Array(p.vertexCount*4);y.set(p.texels.subarray(0,g*4));let x=g,S=g+h,C=0;return c.forEach(({p:t,targets:n,names:r,count:i},a)=>{for(let e=0;e<i;e++)b.set([x,m[a],e,0],(C+e)*4);C+=i,n.forEach((n,a)=>{let s=l.indexOf(r[a]);s<0||(y[x*4]=S,y[x++*4+1]=s,[n.POSITION,n.NORMAL].forEach((n,r)=>{if(n===void 0)return;let a=e(o.accessor(n,`VEC3`),3,t.part?.vertexMap);for(let e=0;e<i;e++)y.set(a.subarray(e*3,e*3+3),(S+e*2+r)*4)}),S+=i*2)})}),{...p,texels:y,morphs:{names:l,weights:u,vertices:b,blocks:h}}}var l=`fn morphTexel(i:u32)->vec4f {let w=u32(f.vat.y);return textureLoad(vat,vec2u(i%w,i/w),0);}
|
|
5
|
+
fn morphed(s:Instance,position:vec3f,normal:vec3f,morph:vec4u)->SkinnedVertex {
|
|
6
|
+
var p=position;var n=normal;
|
|
7
|
+
for(var i=0u;i<morph.y;i++) {
|
|
8
|
+
let e=morphTexel(morph.x+i);let slot=u32(e.y);let w=s.w[slot>>2u][slot&3u];
|
|
9
|
+
if(w!=0.0) {let at=u32(e.x)+morph.z*2u;p+=morphTexel(at).xyz*w;n+=morphTexel(at+1u).xyz*w;}
|
|
10
|
+
}
|
|
11
|
+
return SkinnedVertex(p,n);
|
|
12
|
+
}
|
|
13
|
+
`;function u(e){return o.replace(`q:vec4f}`,`q:vec4f,w:array<vec4f,${e}>}`).replace(`@vertex fn vertex(`,l+`@vertex fn vertex(`).replace(`@location(6) w1:vec4f,`,`@location(6) w1:vec4f,@location(7) morph:vec4u,`).replace(`let k=skinned(s,position,normal,`,`let b=morphed(s,position,normal,morph);let k=skinned(s,b.position,b.normal,`)}function d(e,t){let n=typeof t==`string`?e.morphs.names.indexOf(t):t;if(!(Number.isInteger(n)&&n>=0&&n<e.morphs.names.length))throw RangeError(`Unknown morph target ${t}; use a name from bake.morphs.names or an index below ${e.morphs.names.length}`);return n}function f(e,t,n,r){let i=ArrayBuffer.isView(t)||Array.isArray(t)?Array.from(t,(e,t)=>[t,e]):Object.entries(t),a=i.map(([t])=>d(e,t));if(i.some(([,e])=>typeof e!=`number`||!Number.isFinite(e)))throw RangeError(`Invalid morph weight; pass finite numbers`);a.forEach((e,t)=>n[r+e]=i[t][1])}function p(e,t=e.morphs.weights,n=new Float32Array(e.vertices.length)){let r=e.morphs.weights.slice(),{vertices:i,texels:a}={vertices:e.morphs.vertices,texels:e.texels};if(f(e,t,r,0),n.length<e.vertices.length)throw RangeError(`Morph output needs 6 floats per vertex`);n.set(e.vertices);for(let t=0;t<e.vertexCount;t++)for(let e=0;e<i[t*4+1];e++){let o=(i[t*4]+e)*4,s=r[a[o+1]],c=(a[o]+i[t*4+2]*2)*4;if(s)for(let e=0;e<3;e++)n[t*6+e]+=a[c+e]*s,n[t*6+3+e]+=a[c+4+e]*s}return n}function m(e,t,n,r){return i({...e,vertices:p(e,t.morphs??e.morphs.weights)},t,n,r)}var h=class e extends n{static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,t){let n=e?.morphs?.names?.length;if(!(e?.morphs?.vertices instanceof Uint32Array)||!(n>=1&&n<=64))throw TypeError(`Invalid morphed crowd; pass the result of bakeMorphBones`);let r=Math.ceil(n/4),i=a(e);super(e,t,{...i,vertex:u(r),stride:28+r*4,vertices:[...i.vertices,e.morphs.vertices],attributes:[...i.attributes,{arrayStride:16,attributes:[{shaderLocation:7,offset:0,format:`uint32x4`}]}]})}add(e={}){let t=this.bake.morphs.weights.slice();return e.morphs!==void 0&&f(this.bake,e.morphs,t,0),super.add({...e,morphs:t})}set(e,t){let{morphs:n}=t,r=new Float32Array(this.bake.morphs.names.length);return n!==void 0&&f(this.bake,n,r,0),super.set(e,t),n!==void 0&&f(this.bake,n,this.rows,e*this.stride+28),this}setMorph(e,t,n){return this.set(e,{morphs:{[this.bake.morphs.names[d(this.bake,t)]]:n}})}getMorph(e,t){let n=d(this.bake,t);if(!(Number.isInteger(e)&&e>=0&&e<this.count))throw RangeError(`Invalid crowd member; use an index below the member count`);return this.rows[e*this.stride+28+n]}};export{s as MORPH_TARGET_LIMIT,h as MorphedCrowd,c as bakeMorphBones,p as morphVertices,u as morphedCrowdVertex,m as poseMorphedBones};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
2
|
+
import type { Animation } from './index.js';
|
|
3
|
+
import { VATCrowd, type CrowdLayout, type VATBakeOptions, type VATClip, type VATCrowdOptions, type VATInstance } from './vat.js';
|
|
4
|
+
/** Baked bones: per row and bone three rgba32float texels (the rows of its matrix), wrapped at `width`. */
|
|
5
|
+
export interface BoneBake {
|
|
6
|
+
/** Bones in a row: every joint of every skin used, then one per unskinned part. */
|
|
7
|
+
bones: number;
|
|
8
|
+
rows: number;
|
|
9
|
+
width: number;
|
|
10
|
+
texels: Float32Array;
|
|
11
|
+
vertexCount: number;
|
|
12
|
+
/** Bind-pose position and normal per vertex (6 floats). */
|
|
13
|
+
vertices: Float32Array;
|
|
14
|
+
/** Eight bone indices per vertex. */
|
|
15
|
+
joints: Uint32Array;
|
|
16
|
+
/** Eight weights per vertex, summing to 1. */
|
|
17
|
+
weights: Float32Array;
|
|
18
|
+
indices: Uint32Array;
|
|
19
|
+
/** UV0 with v up, like `@margoengine/materials` textures. */
|
|
20
|
+
uvs: Float32Array;
|
|
21
|
+
clips: VATClip[];
|
|
22
|
+
}
|
|
23
|
+
/** Floats per instance: the 24 of a VAT instance (slot 19 is the blend weight), then blend clip, offset, speed, 0. */
|
|
24
|
+
export declare const SKINNED_CROWD_STRIDE = 28;
|
|
25
|
+
/** Texel (x, y) of a baked row's bone: k 0, 1, 2 are its matrix rows. The shader computes the same. */
|
|
26
|
+
export declare function boneTexel(row: number, bone: number, k: number, bones: number, width?: number): [number, number];
|
|
27
|
+
/**
|
|
28
|
+
* Bakes clips of a glTF `Animation` on the CPU into one bone texture, all primitives merged in the model root's space.
|
|
29
|
+
* Morph targets stay at the weights they have now, unanimated. The animation's clip, time and playing state are
|
|
30
|
+
* restored afterwards.
|
|
31
|
+
*/
|
|
32
|
+
export declare function bakeBones(animation: Animation, { fps, clips }?: VATBakeOptions): BoneBake;
|
|
33
|
+
/** The bindings, pose sampling and vertex stage a {@link SkinnedCrowd} draws with. Exposed for tooling and tests. */
|
|
34
|
+
export declare const skinnedCrowdVertex = "\nstruct Frame {camera:mat4x4f,eye:vec4f,light:vec4f,radiance:vec4f,base:vec4f,options:vec4f,vat:vec4f}\nstruct Instance {m:mat4x4f,p:vec4f,uv:vec4f,q:vec4f}\n@group(0) @binding(0) var<uniform> f:Frame;\n@group(0) @binding(1) var<storage,read> instances:array<Instance>;\n@group(0) @binding(2) var<storage,read> clips:array<vec4f>;\n@group(0) @binding(3) var vat:texture_2d<f32>;\n@group(0) @binding(4) var map:texture_2d<f32>;\n@group(0) @binding(5) var mapSampler:sampler;\nstruct Out {@builtin(position) clip:vec4f,@location(0) position:vec3f,@location(1) normal:vec3f,@location(2) uv:vec2f}\nstruct SkinPhase {row:u32,w:f32}\nstruct SkinnedVertex {position:vec3f,normal:vec3f}\nfn skinPhase(c:vec4f,time:f32)->SkinPhase {\n var t=time/max(c.z,0.000001);t=select(clamp(t,0.0,1.0),fract(t),c.w>0.5);let x=t*c.y;let a=min(floor(x),c.y-1.0);\n return SkinPhase(u32(c.x+a),x-a);\n}\nfn boneTexel(row:u32,bone:u32,k:u32)->vec4f {let i=(row*u32(f.vat.x)+bone)*3u+k;let w=u32(f.vat.y);return textureLoad(vat,vec2u(i%w,i/w),0);}\nfn bonePose(a:SkinPhase,bone:u32,k:u32)->vec4f {return mix(boneTexel(a.row,bone,k),boneTexel(a.row+1u,bone,k),a.w);}\nfn skinned(s:Instance,position:vec3f,normal:vec3f,j0:vec4u,j1:vec4u,w0:vec4f,w1:vec4f)->SkinnedVertex {\n let a=skinPhase(clips[u32(s.p.x)],f.options.x*s.p.z+s.p.y);let b=skinPhase(clips[u32(s.q.x)],f.options.x*s.q.z+s.q.y);let blend=s.p.w;\n var r0=vec4f(0.0);var r1=vec4f(0.0);var r2=vec4f(0.0);\n for(var i=0u;i<8u;i++) {\n let w=select(w1[i&3u],w0[i&3u],i<4u);\n if(w>0.0) {\n let j=select(j1[i&3u],j0[i&3u],i<4u);\n var x=bonePose(a,j,0u);var y=bonePose(a,j,1u);var z=bonePose(a,j,2u);\n if(blend>0.0) {x=mix(x,bonePose(b,j,0u),blend);y=mix(y,bonePose(b,j,1u),blend);z=mix(z,bonePose(b,j,2u),blend);}\n r0+=x*w;r1+=y*w;r2+=z*w;\n }\n }\n let p=vec4f(position,1.0);let c0=cross(r1.xyz,r2.xyz);\n let n=vec3f(dot(c0,normal),dot(cross(r2.xyz,r0.xyz),normal),dot(cross(r0.xyz,r1.xyz),normal))*select(-1.0,1.0,dot(r0.xyz,c0)>=0.0);\n return SkinnedVertex(vec3f(dot(r0,p),dot(r1,p),dot(r2,p)),select(vec3f(0,1,0),n,dot(n,n)>0.0));\n}\n@vertex fn vertex(@location(0) uv:vec2f,@location(1) position:vec3f,@location(2) normal:vec3f,@location(3) j0:vec4u,@location(4) j1:vec4u,@location(5) w0:vec4f,@location(6) w1:vec4f,@builtin(instance_index) id:u32)->Out {\n let s=instances[id];let k=skinned(s,position,normal,j0,j1,w0,w1);\n let m=s.m;let c0=cross(m[1].xyz,m[2].xyz);let world=m*vec4f(k.position,1.0);\n var o:Out;o.clip=f.camera*world;o.position=world.xyz;let n=mat3x3f(c0,cross(m[2].xyz,m[0].xyz),cross(m[0].xyz,m[1].xyz))*k.normal*select(-1.0,1.0,dot(m[0].xyz,c0)>=0.0);o.normal=select(vec3f(0,1,0),n,dot(n,n)>0.0);o.uv=s.uv.xy+uv*s.uv.zw;return o;\n}\n";
|
|
35
|
+
/** @internal What a skinned crowd draws through VATCrowd; a crowd with more per member (instanced-morph.ts) extends it. */
|
|
36
|
+
export declare const skinnedCrowdLayout: (bake: BoneBake) => CrowdLayout;
|
|
37
|
+
/** One crowd member for {@link SkinnedCrowd.add} and {@link SkinnedCrowd.set}. */
|
|
38
|
+
export interface SkinnedCrowdInstance extends VATInstance {
|
|
39
|
+
/** The second clip, an index into `bake.clips`. Default 0. */
|
|
40
|
+
blendClip?: number;
|
|
41
|
+
/** Time offset into the second clip in seconds. Default 0. */
|
|
42
|
+
blendOffset?: number;
|
|
43
|
+
/** Playback speed of the second clip. Default 1. */
|
|
44
|
+
blendSpeed?: number;
|
|
45
|
+
/** How much of the second clip shows, 0 to 1. Default 0. */
|
|
46
|
+
blend?: number;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Draws any number of copies of a {@link bakeBones} bake in one instanced call, skinned in the vertex shader. Each
|
|
50
|
+
* instance has its own matrix, two clips with their own offsets and speeds, a blend between them and an atlas region,
|
|
51
|
+
* and the CPU does no per-instance work per frame. Everything else is as `VATCrowd`: opaque, no CPU culling,
|
|
52
|
+
* `shadows.add(crowd)`, `lighting.add(crowd)`.
|
|
53
|
+
*/
|
|
54
|
+
export declare class SkinnedCrowd extends VATCrowd {
|
|
55
|
+
readonly bake: BoneBake;
|
|
56
|
+
/** Same as `engine.use(new SkinnedCrowd(...))`; returns the crowd. */
|
|
57
|
+
static attach(engine: EngineKernel, bake: BoneBake, options?: VATCrowdOptions): SkinnedCrowd;
|
|
58
|
+
/** @internal Floats per member row. */
|
|
59
|
+
protected readonly stride: number;
|
|
60
|
+
constructor(bake: BoneBake, options?: VATCrowdOptions,
|
|
61
|
+
/** @internal */
|
|
62
|
+
custom?: CrowdLayout);
|
|
63
|
+
add(instance?: SkinnedCrowdInstance): number;
|
|
64
|
+
/** Changes the given fields of one instance. */
|
|
65
|
+
set(index: number, instance: SkinnedCrowdInstance): this;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* One bone of a member at `time` (the crowd's clock): its skinning matrix in the model root's space, before the
|
|
69
|
+
* member's own matrix, as the 12 numbers of its 3x4 rows (a bind-pose point `p` goes to `row . [p, 1]`), both clips and
|
|
70
|
+
* the blend applied as the shader applies them. The CPU twin of the shader for one bone: what a rider rides, a rifle in
|
|
71
|
+
* a hand, a flag on a pole follow, at the cost of 24 texel reads.
|
|
72
|
+
* @example
|
|
73
|
+
* const m = poseBone(bake, {clip: 1, offset: 0.4}, handBone, crowd.time);
|
|
74
|
+
* const grip = [m[0] * x + m[1] * y + m[2] * z + m[3], m[4] * x + m[5] * y + m[6] * z + m[7], m[8] * x + m[9] * y + m[10] * z + m[11]];
|
|
75
|
+
* @throws RangeError for a clip not in `bake.clips` or a bone not in the bake.
|
|
76
|
+
*/
|
|
77
|
+
export declare function poseBone(bake: BoneBake, { clip, offset, speed, blendClip, blendOffset, blendSpeed, blend }: SkinnedCrowdInstance, bone: number, time: number, out?: Float32Array<ArrayBuffer>): Float32Array;
|
|
78
|
+
/**
|
|
79
|
+
* Where a member's vertices are at `time` (the crowd's clock), in the model root's space before its matrix, as
|
|
80
|
+
* `[x, y, z]` triples: the CPU twin of the shader, for checks, picking and bounds.
|
|
81
|
+
*/
|
|
82
|
+
export declare function poseBones(bake: BoneBake, { clip, offset, speed, blendClip, blendOffset, blendSpeed, blend }: SkinnedCrowdInstance, time: number, out?: Float32Array<ArrayBuffer>): Float32Array;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{t as e}from"./vertex-map-BC_WH7ER.js";import{r as t,t as n}from"./vat-SpfL7y9U.js";import{invertMatrixStable as r,multiplyMatrices as i}from"@margoengine/math/mat4";var a=28;function o(e,n,r,i,a=t){let o=(e*i+n)*3+r;return[o%a,Math.floor(o/a)]}function s(n,{fps:a=30,clips:o}={}){let s=n.model,c=s.asset.doc,l=s.asset,u=s.root.engine.store,d=(o??n.clips.map((e,t)=>t)).map(e=>typeof e==`string`?n.clips.findIndex(t=>t.name===e):e);if(!(a>0&&a<=1e3)||!d.length||d.some(e=>!n.clips[e]))throw RangeError(`Invalid bone bake fps or clips; pass fps in (0, 1000] and clip indices that exist in animation.clips`);let f=[],p=/* @__PURE__ */ new Map,m=s.primitives.reduce((e,t)=>e+t.vertices.length/20,0),h=new Float32Array(m*6),g=new Uint32Array(m*8),_=new Float32Array(m*8),v=new Float32Array(m*2),y=[],b=0;for(let t of s.primitives){let n=t.definition,r=t.vertices.length/20,i=c.nodes[t.nodeIndex].skin,a=i===void 0?void 0:c.skins[i],o=t.vertices,s=t.part?.vertexMap,u=(n.targets??[]).map(t=>[t.POSITION,t.NORMAL].map(t=>t===void 0?null:e(l.accessor(t,`VEC3`),3,s))),d=i===void 0?void 0:p.get(i);if(d===void 0){if(d=f.length,a){p.set(i,d);let e=a.inverseBindMatrices===void 0?void 0:l.accessor(a.inverseBindMatrices,`MAT4`);a.joints.forEach((t,n)=>f.push({node:t,bind:e?.subarray(n*16,n*16+16)}))}else f.push({node:t.nodeIndex,part:t})}let m=a?[[n.attributes.JOINTS_0,n.attributes.WEIGHTS_0],[n.attributes.JOINTS_1,n.attributes.WEIGHTS_1]].filter(([e,t])=>e!==void 0&&t!==void 0).map(([t,n])=>[e(l.accessor(t,`VEC4`),4,s),e(l.accessor(n,`VEC4`),4,s)]):[];for(let e=0;e<r;e++){let n=b+e,r=o[e*20],i=o[e*20+1],s=o[e*20+2],c=o[e*20+4],l=o[e*20+5],f=o[e*20+6];if(u.forEach(([n,a],o)=>{let u=t.weights[o];n&&(r+=n[e*3]*u,i+=n[e*3+1]*u,s+=n[e*3+2]*u),a&&(c+=a[e*3]*u,l+=a[e*3+1]*u,f+=a[e*3+2]*u)}),h.set([r,i,s,c,l,f],n*6),v[n*2]=o[e*20+12],v[n*2+1]=1-o[e*20+13],!a){g[n*8]=d,_[n*8]=1;continue}let p=0;for(let[,t]of m)for(let n=0;n<4;n++)p+=t[e*4+n];if(!(p>0))throw RangeError(`Skin weights must have a positive sum; give every vertex a joint`);m.forEach(([t,r],i)=>{for(let a=0;a<4;a++)g[n*8+i*4+a]=d+t[e*4+a],_[n*8+i*4+a]=r[e*4+a]/p})}for(let e of t.indices)y.push(b+e);b+=r}let x=d.map(e=>Math.max(1,Math.ceil(n.clips[e].duration*a))),S=x.reduce((e,t)=>e+t+1,0),C=Math.ceil(S*f.length*3/t);if(C>8192)throw RangeError(`Bone data exceeds 8192 texture rows; bake fewer clips, a lower fps or fewer bones`);let w={clip:n.clip,time:n.time,playing:n.playing},T=new Float32Array(t*C*4),E=/* @__PURE__ */ new Float32Array(16),D=/* @__PURE__ */ new Float32Array(16),O=/* @__PURE__ */ new Float32Array(16),k=/* @__PURE__ */ new Float64Array(52),A=0;try{d.forEach((e,t)=>{let a=n.clips[e].duration;n.play(e);for(let e=0;e<=x[t];e++,A++){if(n.seek(a*e/x[t]),u.tick(!1),!r(s.root.matrix,E,k))throw RangeError(`Singular model root; give the model root a non-zero scale before baking`);f.forEach(({node:e,bind:t,part:n},r)=>{let a=n?n.node.matrix:s.nodes[e].matrix;t?i(a,t,D):D.set(a),i(E,D,O);let o=(A*f.length+r)*12;for(let e=0;e<3;e++)for(let t=0;t<4;t++){let n=O[t*4+e];if(!Number.isFinite(n))throw RangeError(`Bone bake produced non-finite matrices; use finite joints and inverse binds`);T[o+e*4+t]=n}})}})}finally{n.play(w.clip),n.seek(w.time),n.playing=w.playing,u.tick(!1)}let j=0;return{bones:f.length,rows:S,width:t,texels:T,vertexCount:m,vertices:h,joints:g,weights:_,indices:Uint32Array.from(y),uvs:v,clips:d.map((e,t)=>{let r={name:n.clips[e].name,start:j,frames:x[t],duration:n.clips[e].duration,loop:n.options.loop??!0};return j+=x[t]+1,r})}}var c=`
|
|
5
|
+
struct Frame {camera:mat4x4f,eye:vec4f,light:vec4f,radiance:vec4f,base:vec4f,options:vec4f,vat:vec4f}
|
|
6
|
+
struct Instance {m:mat4x4f,p:vec4f,uv:vec4f,q:vec4f}
|
|
7
|
+
@group(0) @binding(0) var<uniform> f:Frame;
|
|
8
|
+
@group(0) @binding(1) var<storage,read> instances:array<Instance>;
|
|
9
|
+
@group(0) @binding(2) var<storage,read> clips:array<vec4f>;
|
|
10
|
+
@group(0) @binding(3) var vat:texture_2d<f32>;
|
|
11
|
+
@group(0) @binding(4) var map:texture_2d<f32>;
|
|
12
|
+
@group(0) @binding(5) var mapSampler:sampler;
|
|
13
|
+
struct Out {@builtin(position) clip:vec4f,@location(0) position:vec3f,@location(1) normal:vec3f,@location(2) uv:vec2f}
|
|
14
|
+
struct SkinPhase {row:u32,w:f32}
|
|
15
|
+
struct SkinnedVertex {position:vec3f,normal:vec3f}
|
|
16
|
+
fn skinPhase(c:vec4f,time:f32)->SkinPhase {
|
|
17
|
+
var t=time/max(c.z,0.000001);t=select(clamp(t,0.0,1.0),fract(t),c.w>0.5);let x=t*c.y;let a=min(floor(x),c.y-1.0);
|
|
18
|
+
return SkinPhase(u32(c.x+a),x-a);
|
|
19
|
+
}
|
|
20
|
+
fn boneTexel(row:u32,bone:u32,k:u32)->vec4f {let i=(row*u32(f.vat.x)+bone)*3u+k;let w=u32(f.vat.y);return textureLoad(vat,vec2u(i%w,i/w),0);}
|
|
21
|
+
fn bonePose(a:SkinPhase,bone:u32,k:u32)->vec4f {return mix(boneTexel(a.row,bone,k),boneTexel(a.row+1u,bone,k),a.w);}
|
|
22
|
+
fn skinned(s:Instance,position:vec3f,normal:vec3f,j0:vec4u,j1:vec4u,w0:vec4f,w1:vec4f)->SkinnedVertex {
|
|
23
|
+
let a=skinPhase(clips[u32(s.p.x)],f.options.x*s.p.z+s.p.y);let b=skinPhase(clips[u32(s.q.x)],f.options.x*s.q.z+s.q.y);let blend=s.p.w;
|
|
24
|
+
var r0=vec4f(0.0);var r1=vec4f(0.0);var r2=vec4f(0.0);
|
|
25
|
+
for(var i=0u;i<8u;i++) {
|
|
26
|
+
let w=select(w1[i&3u],w0[i&3u],i<4u);
|
|
27
|
+
if(w>0.0) {
|
|
28
|
+
let j=select(j1[i&3u],j0[i&3u],i<4u);
|
|
29
|
+
var x=bonePose(a,j,0u);var y=bonePose(a,j,1u);var z=bonePose(a,j,2u);
|
|
30
|
+
if(blend>0.0) {x=mix(x,bonePose(b,j,0u),blend);y=mix(y,bonePose(b,j,1u),blend);z=mix(z,bonePose(b,j,2u),blend);}
|
|
31
|
+
r0+=x*w;r1+=y*w;r2+=z*w;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let p=vec4f(position,1.0);let c0=cross(r1.xyz,r2.xyz);
|
|
35
|
+
let n=vec3f(dot(c0,normal),dot(cross(r2.xyz,r0.xyz),normal),dot(cross(r0.xyz,r1.xyz),normal))*select(-1.0,1.0,dot(r0.xyz,c0)>=0.0);
|
|
36
|
+
return SkinnedVertex(vec3f(dot(r0,p),dot(r1,p),dot(r2,p)),select(vec3f(0,1,0),n,dot(n,n)>0.0));
|
|
37
|
+
}
|
|
38
|
+
@vertex fn vertex(@location(0) uv:vec2f,@location(1) position:vec3f,@location(2) normal:vec3f,@location(3) j0:vec4u,@location(4) j1:vec4u,@location(5) w0:vec4f,@location(6) w1:vec4f,@builtin(instance_index) id:u32)->Out {
|
|
39
|
+
let s=instances[id];let k=skinned(s,position,normal,j0,j1,w0,w1);
|
|
40
|
+
let m=s.m;let c0=cross(m[1].xyz,m[2].xyz);let world=m*vec4f(k.position,1.0);
|
|
41
|
+
var o:Out;o.clip=f.camera*world;o.position=world.xyz;let n=mat3x3f(c0,cross(m[2].xyz,m[0].xyz),cross(m[0].xyz,m[1].xyz))*k.normal*select(-1.0,1.0,dot(m[0].xyz,c0)>=0.0);o.normal=select(vec3f(0,1,0),n,dot(n,n)>0.0);o.uv=s.uv.xy+uv*s.uv.zw;return o;
|
|
42
|
+
}
|
|
43
|
+
`,l=e=>({vertex:c,stride:28,rowSize:e.bones,vertices:[e.vertices,e.joints,e.weights],attributes:[{arrayStride:24,attributes:[{shaderLocation:1,offset:0,format:`float32x3`},{shaderLocation:2,offset:12,format:`float32x3`}]},{arrayStride:32,attributes:[{shaderLocation:3,offset:0,format:`uint32x4`},{shaderLocation:4,offset:16,format:`uint32x4`}]},{arrayStride:32,attributes:[{shaderLocation:5,offset:0,format:`float32x4`},{shaderLocation:6,offset:16,format:`float32x4`}]}]}),u=class e extends n{static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,t,n){if(!(e?.vertices instanceof Float32Array)||!(e.bones>0))throw TypeError(`Invalid skinned crowd; pass the result of bakeBones`);let r=n??l(e);super(e,t,r),this.bake=e,this.stride=r.stride}add(e={}){return super.add(e)}set(e,t){let{blendClip:n,blendOffset:r,blendSpeed:i,blend:a}=t;if(n!==void 0&&!(Number.isInteger(n)&&n>=0&&n<this.bake.clips.length)||r!==void 0&&!Number.isFinite(r)||i!==void 0&&!Number.isFinite(i)||a!==void 0&&!(a>=0&&a<=1))throw RangeError(`Invalid crowd blend; use a blendClip from bake.clips, a finite blendOffset and blendSpeed, and a blend in 0..1`);super.set(e,t);let o=e*this.stride,s=this.rows;return a!==void 0&&(s[o+19]=a),n!==void 0&&(s[o+24]=n),r!==void 0&&(s[o+25]=r),i!==void 0&&(s[o+26]=i),this}},d=(e,t,n)=>e+(t-e)*n;function f(e,t){let n=t/Math.max(e.duration,1e-6);n=e.loop?n-Math.floor(n):Math.min(1,Math.max(0,n));let r=n*e.frames,i=Math.min(Math.floor(r),e.frames-1);return[e.start+i,r-i]}function p(e,{clip:t=0,offset:n=0,speed:r=1,blendClip:i=0,blendOffset:a=0,blendSpeed:s=1,blend:c=0},l,u,p=/* @__PURE__ */ new Float32Array(12)){if(!e.clips[t]||!e.clips[i]||!(Number.isInteger(l)&&l>=0&&l<e.bones)||p.length<12)throw RangeError(`Invalid bone pose; use clips from bake.clips, a bone below bake.bones and an output of 12 floats`);let m=f(e.clips[t],u*r+n),h=f(e.clips[i],u*s+a),g=(t,n,r)=>{let[i,a]=o(t,l,n,e.bones,e.width);return e.texels[(a*e.width+i)*4+r]},_=(e,t,n)=>d(g(e[0],t,n),g(e[0]+1,t,n),e[1]);for(let e=0;e<3;e++)for(let t=0;t<4;t++)p[e*4+t]=d(_(m,e,t),_(h,e,t),c);return p}function m(e,{clip:t=0,offset:n=0,speed:r=1,blendClip:i=0,blendOffset:a=0,blendSpeed:s=1,blend:c=0},l,u=new Float32Array(e.vertexCount*3)){if(!e.clips[t]||!e.clips[i]||u.length<e.vertexCount*3)throw RangeError(`Invalid pose; use clips from bake.clips and an output of 3 floats per vertex`);let p=f(e.clips[t],l*r+n),m=f(e.clips[i],l*s+a),h=(t,n,r,i)=>{let[a,s]=o(t,n,r,e.bones,e.width);return e.texels[(s*e.width+a)*4+i]},g=(e,t,n,r)=>d(h(e[0],t,n,r),h(e[0]+1,t,n,r),e[1]);for(let t=0;t<e.vertexCount;t++){let[n,r,i]=e.vertices.subarray(t*6,t*6+3);for(let a=0;a<3;a++){let o=0;for(let s=0;s<8;s++){let l=e.weights[t*8+s];if(!l)continue;let u=e.joints[t*8+s],f=e=>d(g(p,u,a,e),g(m,u,a,e),c);o+=l*(f(0)*n+f(1)*r+f(2)*i+f(3))}u[t*3+a]=o}}return u}export{a as SKINNED_CROWD_STRIDE,u as SkinnedCrowd,s as bakeBones,o as boneTexel,p as poseBone,m as poseBones,l as skinnedCrowdLayout,c as skinnedCrowdVertex};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Engine, EnginePlugin } from '@margoengine/core/extension';
|
|
2
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
3
|
+
import type { GLTFPhysics } from '@margoengine/gltf/physics';
|
|
4
|
+
import { type BehaviorGraph, type BehaviorGraphOptions } from '@margoengine/gltf/interactivity';
|
|
5
|
+
import { type Interpolation } from './sampling.js';
|
|
6
|
+
/** Options of {@link GLTFInteractivity}. */
|
|
7
|
+
export interface GLTFInteractivityOptions extends Pick<BehaviorGraphOptions, 'log' | 'maxActivations' | 'maxEventsPerTick'> {
|
|
8
|
+
/** Runs the file's `rigid_body/*` operations and trigger events. Default: they do nothing. */
|
|
9
|
+
physics?: GLTFPhysics;
|
|
10
|
+
/** Reports the viewer's camera under `activeCamera`. Default true; false reads as NaN, for privacy. */
|
|
11
|
+
shareCamera?: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Turns pointer input on the canvas into select and hover events. Default true, for a graph with such events; it attaches
|
|
14
|
+
* `Picking` of `@margoengine/selection`, loaded on first use, unless the engine has a picker. It stays attached afterwards.
|
|
15
|
+
*/
|
|
16
|
+
pointer?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** Samples one flattened animation channel, for `sample` of `loadBehaviorGraph`. */
|
|
19
|
+
export declare function sampleChannel(channel: {
|
|
20
|
+
times: Float32Array;
|
|
21
|
+
values: Float32Array;
|
|
22
|
+
width: number;
|
|
23
|
+
interpolation: Interpolation;
|
|
24
|
+
}, time: number): number[];
|
|
25
|
+
/**
|
|
26
|
+
* Runs the behaviour graph a model's file carries. The graph starts on the next frame, plays the file's animations itself,
|
|
27
|
+
* so do not also play them with `Animation`, and clicks and hovers on the canvas reach its `event/onSelect`,
|
|
28
|
+
* `event/onHoverIn` and `event/onHoverOut` nodes. A file the specification rejects leaves `graph` undefined and says why in
|
|
29
|
+
* `rejected`; the model still draws.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* const model = await loadGLTF(engine, '/product.glb');
|
|
33
|
+
* const behaviour = GLTFInteractivity.attach(model);
|
|
34
|
+
* behaviour.graph?.on('checkout', ({variant}) => console.log(variant));
|
|
35
|
+
*/
|
|
36
|
+
export declare class GLTFInteractivity implements EnginePlugin {
|
|
37
|
+
readonly name: string;
|
|
38
|
+
/** The running graph; undefined when the file has none or it was rejected. */
|
|
39
|
+
readonly graph?: BehaviorGraph;
|
|
40
|
+
/** Why the file's graph must not run, when it was rejected. */
|
|
41
|
+
readonly rejected?: string;
|
|
42
|
+
/** Properties the graph wrote that it can read back but that change nothing on screen, one line each. */
|
|
43
|
+
readonly notes: string[];
|
|
44
|
+
private readonly model;
|
|
45
|
+
private readonly options;
|
|
46
|
+
private readonly writers;
|
|
47
|
+
private readonly nodeOf;
|
|
48
|
+
private readonly removers;
|
|
49
|
+
private engine?;
|
|
50
|
+
private press?;
|
|
51
|
+
private moved?;
|
|
52
|
+
private picking;
|
|
53
|
+
private disposed;
|
|
54
|
+
private picker?;
|
|
55
|
+
/** Runs the graph of `model` on the engine that loaded it. */
|
|
56
|
+
static attach(model: PBRModel, options?: GLTFInteractivityOptions): GLTFInteractivity;
|
|
57
|
+
constructor(model: PBRModel, options?: GLTFInteractivityOptions);
|
|
58
|
+
setup(engine: Engine): void;
|
|
59
|
+
private listen;
|
|
60
|
+
private nodeAt;
|
|
61
|
+
/** What the ray through a canvas point crosses on this model, nearest first. Read on a click, so skins are in their pose. */
|
|
62
|
+
private trace;
|
|
63
|
+
private select;
|
|
64
|
+
private hover;
|
|
65
|
+
onPreUpdate(delta: number): void;
|
|
66
|
+
private write;
|
|
67
|
+
private camera;
|
|
68
|
+
/** Stops the graph and the input, and leaves the engine. */
|
|
69
|
+
dispose(): void;
|
|
70
|
+
[Symbol.dispose](): void;
|
|
71
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{t as e}from"./src-fuuIJ3rU.js";import{o as t}from"./sampling-DjDWYqt2.js";import{n,t as r}from"./pointer-DyWpFsQi.js";import{MargoError as i}from"@margoengine/math/errors";import{rotationToQuaternion as a}from"@margoengine/math/quat";import{screenToWorld as o}from"@margoengine/math/project";import{Ray as s}from"@margoengine/math/ray";import{Vector3 as c}from"@margoengine/math/vector3";import{loadBehaviorGraph as l}from"@margoengine/gltf/interactivity";function u(e,n){let{times:r,values:i,width:a,interpolation:o}=e;return Array.from(t(r,i,a,n,o,a===4&&o!==`STEP`))}var d=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y,e.z-t.z);function f(e,t,n){let r=e[t*20],i=e[t*20+1],a=e[t*20+2];return{x:n[0]*r+n[4]*i+n[8]*a+n[12],y:n[1]*r+n[5]*i+n[9]*a+n[13],z:n[2]*r+n[6]*i+n[10]*a+n[14]}}var p=0,m=/\/extensions\/KHR_node_(selectability|hoverability)\//,h=/KHR_physics_rigid_bodies/,g=class t{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,n={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let r=new t(e,n);return e.root.engine.use(r),r}constructor(e,t={}){this.name=`gltf-interactivity:`+p++,this.notes=[],this.writers=/* @__PURE__ */ new Map,this.nodeOf=/* @__PURE__ */ new Map,this.removers=[],this.picking=!1,this.disposed=!1,this.model=e,this.options=t;let{physics:n}=t,r=l(e.asset,{...t,sample:u,physics:n&&_(n),live:(e,t)=>this.write(e,t),camera:()=>t.shareCamera===!1?void 0:this.camera()});this.graph=r.graph,this.rejected=r.rejected,e.nodes.forEach((e,t)=>this.nodeOf.set(e,t))}setup(t){if(this.disposed)throw new i(`disposed`,`GLTFInteractivity is disposed; create a new graph before attaching`);this.engine=t;let{graph:n}=this,a=this.model.asset.doc;n&&((a.skins?.length||a.meshes?.some(e=>e.primitives?.some(e=>e.targets?.length)))&&(e.attach(this.model,{pointers:r,loop:!1}).playing=!1),this.options.physics&&this.removers.push(this.options.physics.onTrigger(({entered:e,nodeIndex:t,colliderNodeIndex:r,motionNodeIndex:i})=>n.trigger(e?`event/rigid_body_triggerEntered`:`event/rigid_body_triggerExited`,t,r,i))),this.options.pointer!==!1&&this.listen(t,n))}listen(e,t){let{canvas:n}=e,r=t.handles(`event/onSelect`),a=t.handles(`event/onHoverIn`)||t.handles(`event/onHoverOut`);(r||a)&&![...e.plugins.values()].some(e=>e.onPick)&&(this.picker=import(`@margoengine/selection`).then(({Picking:t})=>t.forEngine(e)??t.attach(e,{capture:!1}),()=>{throw new i(`unsupported`,`Clicks on a behaviour graph need @margoengine/selection; install it, or pass pointer: false`)}));let o=e=>{let t=n.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}},s=(e,t)=>{n.addEventListener(e,t),this.removers.push(()=>n.removeEventListener(e,t))};r&&(s(`pointerdown`,e=>this.press=o(e)),s(`pointerup`,e=>{let t=o(e),n=this.press;this.press=void 0,n&&Math.hypot(t.x-n.x,t.y-n.y)<=4&&this.select(t)})),a&&(s(`pointermove`,e=>this.moved=o(e)),s(`pointerleave`,()=>{this.moved=void 0,t.hover(void 0)}))}async nodeAt({x:e,y:t}){await this.picker;let n=await this.engine.pick(e,t);return n?this.nodeOf.get(n):void 0}async trace({x:e,y:t}){let{camera:n,canvas:r}=this.engine,i=r.clientWidth||r.width,a=r.clientHeight||r.height,l=r=>o(e,t,r,n,i,a,new c),[u,p,m]=n.position,h={x:u,y:p,z:m},[g,_]=[l(.25),l(.75)].sort((e,t)=>d(e,h)-d(t,h)),v=new s(g,_.clone().sub(g).normalize()),y=new c,b=[];for(let{vertices:e,indices:t,matrix:n,nodeIndex:r}of await this.model.readPickingGeometry()){if(r===void 0)continue;let i=1/0,a=[];for(let r=0;r+2<t.length;r+=3){let o=f(e,t[r],n),s=f(e,t[r+1],n),c=f(e,t[r+2],n);if(!v.intersectTriangle(o,s,c,!1,y))continue;let l=d(y,g);l<i&&(i=l,a=[y.x,y.y,y.z])}i<1/0&&b.push({node:r,distance:i,point:a})}return b.sort((e,t)=>e.distance-t.distance)}async select(e){let t=await this.nodeAt(e);if(t===void 0||this.model.disposed)return;let n=[...this.engine.camera.position],r=await this.trace(e);if(!this.model.disposed){for(let e of r)if(this.graph?.select(e.node,{point:e.point,origin:n}))return;r.length||this.graph?.select(t,{origin:n})}}async hover(e){this.picking=!0;let t=await this.nodeAt(e);this.picking=!1,this.model.disposed||this.graph?.hover(t)}onPreUpdate(e){if(this.model.disposed)this.dispose();else{if(this.moved&&!this.picking){let e=this.moved;this.moved=void 0,this.hover(e)}this.graph?.tick(e)}}write(e,t){if(m.test(e))return;let r=typeof t==`boolean`?[+!!t]:typeof t==`number`?[t]:t;if(h.test(e))this.options.physics?.setPointer(e,r.length===1?r[0]:r);else{if(!this.writers.has(e)){let t=n(this.model,e);this.writers.set(e,t),t||this.notes.push(`${e} has no effect on the rendered model`)}this.writers.get(e)?.(r)}}camera(){let e=this.engine;if(!e)return;let{position:t,target:n,up:r,fov:i,near:o,far:s}=e.camera,c=e=>{let t=Math.hypot(...e);return e.map(e=>e/t)},l=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],u=c(t.map((e,t)=>e-n[t])),d=c(l([...r],u)),f=l(u,d);return{position:[...t],rotation:a([...d,0,...f,0,...u],[0,0,0,0]),perspective:{aspectRatio:e.canvas.width/e.canvas.height,yfov:i*Math.PI/180,znear:o,zfar:s}}}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.removers.splice(0))e();this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose](){this.dispose()}};function _(e){let t=e=>e;return{applyImpulse(n,r,i){e.bodyOf(n)?.applyImpulse(t(r)).applyTorqueImpulse(t(i))},applyPointImpulse(n,r,i){e.bodyOf(n)?.applyImpulse(t(r),t(i))},rayCast(t,n){let r=n.map((e,n)=>e-t[n]),i=Math.hypot(...r);if(!i)return;let a=e.physics.raycast(t,r,{maxDistance:i});if(a)return{nodeIndex:[...e.bodies].find(([,e])=>e===a.body)?.[0]??-1,fraction:a.distance/i,normal:[...a.normal]}}}}export{g as GLTFInteractivity,u as sampleChannel};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Interpolation } from './sampling.js';
|
|
2
|
+
/**
|
|
3
|
+
* Blends keys `a` and `b` (b is a or a + 1) at `time`, with `ta` and `tb` their times, into `out` (width numbers).
|
|
4
|
+
* `sampleTrackInto` and the player's cursor sampler both call it, so they give the same bits for the same key pair.
|
|
5
|
+
*/
|
|
6
|
+
export declare function interpolateKeys(values: Float32Array, width: number, a: number, b: number, ta: number, tb: number, time: number, interpolation: Interpolation, quaternion: boolean, out: Float32Array): Float32Array;
|
|
7
|
+
/** The track-invalid error `sampleTrackInto` throws, word for word. */
|
|
8
|
+
export declare const invalidTrack: () => TypeError;
|
|
9
|
+
/** A track the Animation constructor already checked (width, value count, increasing times), plus its last key. */
|
|
10
|
+
export interface CursorTrack {
|
|
11
|
+
times: Float32Array;
|
|
12
|
+
values: Float32Array;
|
|
13
|
+
width: number;
|
|
14
|
+
interpolation: Interpolation;
|
|
15
|
+
/** The key found by the previous sample; 0 before the first. */
|
|
16
|
+
cursor: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Samples a checked track into `out` (width numbers) with the same bits as `sampleTrackInto`. Playing forward walks on
|
|
20
|
+
* from the previous key (per-track sorted key cursors, as in ACL's notes on keyframe decompression), reading two or
|
|
21
|
+
* three key times instead of a binary search; a seek back or a loop wrap searches as before.
|
|
22
|
+
*/
|
|
23
|
+
export declare function sampleCursor(track: CursorTrack, time: number, quaternion: boolean, out: Float32Array): Float32Array;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{n as e,t}from"./pose-source-MuCl8VDd.js";import{s as n}from"./sampling-DjDWYqt2.js";import{n as r}from"./shader-DuGkHFKx.js";import{MargoError as i}from"@margoengine/math/errors";import{composeMatrix as a,invertMatrixStable as o,multiplyMatrices as s}from"@margoengine/math/mat4";import{normalizeQuaternion as c}from"@margoengine/math/quat";function l(e,t,n){let r=e;if(!r||typeof r!=`object`||r.length!==t)throw TypeError(`${n} needs ${t} numbers; pass an array of length ${t}`);for(let e=0;e<t;e++)if(typeof r[e]!=`number`||!Number.isFinite(r[e]))throw RangeError(`${n} has a non-finite value; pass finite numbers`);return r}var u=/* @__PURE__ */ new Float64Array(4);function d(e,t){let n=e;if(!n||typeof n!=`object`||n.length!==t)return!1;for(let e=0;e<t;e++)if(typeof n[e]!=`number`||!Number.isFinite(n[e]))return!1;return!0}function f(e,t,n,r){let i=n.translation,a=n.scale,o=n.rotation;if(i!==void 0&&!d(i,3)&&l(i,3,`Skeleton bone ${r} translation`),a!==void 0&&!d(a,3)&&l(a,3,`Skeleton bone ${r} scale`),o!==void 0&&!d(o,4)&&l(o,4,`Skeleton bone ${r} rotation`),o&&!(o[0]||o[1]||o[2]||o[3]))throw RangeError(`Skeleton bone ${r} rotation is a zero quaternion; pass a unit quaternion`);i&&e.set(i,t),a&&e.set(a,t+7),o&&e.set(c(o,u),t+3)}var p=class{constructor(e,t){if(this.revision=0,this.order=[],this.local=/* @__PURE__ */ new Float64Array(16),this.workspace=/* @__PURE__ */ new Float64Array(52),this.dirty=!0,!Array.isArray(e)||!e.length)throw TypeError(`Skeleton bones must be a nonempty array; pass at least a root bone`);let n=e.length,r=e.map((e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`Skeleton bone ${t} must be an object`);if(typeof e.name!=`string`||!e.name)throw TypeError(`Skeleton bone ${t} needs a nonempty string name`);return e.name});if(this.byName=new Map(r.map((e,t)=>[e,t])),this.byName.size!==n)throw TypeError(`Skeleton bone names repeat; give every bone a unique name`);let i=e.map(({parent:e},t)=>{if(!Number.isInteger(e)||e<-1||e>=n||e===t)throw RangeError(`Skeleton bone ${t} parent ${e} is invalid; use -1 or another bone's index`);return e}),a=i.filter(e=>e===-1).length;if(a!==1)throw RangeError(`Skeleton has ${a} root bones; give exactly one bone parent -1`);this.names=Object.freeze(r),this.parents=Object.freeze(i),this.root=i.indexOf(-1);let o=i.map(()=>[]);i.forEach((e,t)=>e>=0&&o[e].push(t));for(let e=[this.root];e.length;){let t=e.pop();this.order.push(t),e.push(...o[t])}if(this.order.length!==n)throw RangeError(`Skeleton bone parents form a cycle; every parent chain must end at the root`);this.base=new Float64Array(n*10),e.forEach((e,t)=>{this.base.set([0,0,0,0,0,0,1,1,1,1],t*10),f(this.base,t*10,e,t)}),this.pose=this.base.slice(),this.world=new Float64Array(n*16),this.skin=new Float64Array(n*16),this.inverse=new Float64Array(n*16),t===void 0?this.bind():this.inverse.set(l(t,n*16,`Skeleton inverse bind matrices`))}get count(){return this.names.length}index(e){return this.byName.get(e)??-1}bone(e){if(!Number.isInteger(e)||e<0||e>=this.count)throw RangeError(`Skeleton bone ${e} does not exist; pass an index below ${this.count}`);return e}setPose(e,t){return f(this.pose,this.bone(e)*10,t??{},e),this.changed()}getPose(e){let t=this.pose,n=this.bone(e)*10;return{translation:[t[n],t[n+1],t[n+2]],rotation:[t[n+3],t[n+4],t[n+5],t[n+6]],scale:[t[n+7],t[n+8],t[n+9]]}}restorePose(e,t=!1){if(e===void 0)this.pose.set(this.base);else{let n=new Uint8Array(this.count);n[this.bone(e)]=1;for(let e of this.order)t&&this.parents[e]>=0&&n[this.parents[e]]&&(n[e]=1),n[e]&&this.pose.set(this.base.subarray(e*10,e*10+10),e*10)}return this.changed()}setBindPose(){return this.bind(),this.base.set(this.pose),this.changed()}bind(){let e=this.matrices,t=this.inverse.slice();for(let n=0;n<this.count;n++)if(!o(e.subarray(n*16,n*16+16),t.subarray(n*16,n*16+16),this.workspace))throw RangeError(`Skeleton bone ${n} bind pose is singular; give it a non-zero scale`);this.inverse.set(t),this.dirty=!0}changed(){return this.dirty=!0,this.revision++,this}update(){if(!this.dirty)return;let{pose:e,world:t,local:n}=this;for(let r of this.order){a(e.subarray(r*10,r*10+3),e.subarray(r*10+3,r*10+7),e.subarray(r*10+7,r*10+10),n);let i=this.parents[r],o=t.subarray(r*16,r*16+16);i<0?o.set(n):s(t.subarray(i*16,i*16+16),n,o),s(o,this.inverse.subarray(r*16,r*16+16),this.skin.subarray(r*16,r*16+16))}this.dirty=!1}get matrices(){return this.update(),this.world}get inverseBindMatrices(){return this.inverse}get skinMatrices(){return this.update(),this.skin}worldMatrix(e,t,n=/* @__PURE__ */ new Float32Array(16)){let r=this.bone(e)*16,i=this.matrices.subarray(r,r+16);return t===void 0?n.set(i):s(l(t,16,`Skeleton parent matrix`),i,n),n}},m=/* @__PURE__ */ new WeakMap,h=0,g=class n{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t,n){if(this.skeleton=e,this.name=`skin:`+h++,this.edits=0,this.dirtyFrom=0,this.uploaded=-1,this.disposed=!1,this.prepare=e=>this.deform(e),this.scenePose=()=>{let e=this.mesh;if(!this.gpu||!e||e.primitives[0].deformed!==this.gpu.output)return;let t=this.picking.posePickingGeometry()[0].vertices,n=this.scenePosed??={vertices:new Float32Array(t.length),revision:0};return n.from!==t&&(n.vertices.length!==t.length&&(n.vertices=new Float32Array(t.length)),n.vertices.set(t),n.from=t,n.revision++),n},!(e instanceof p))throw TypeError(`Skin needs a Skeleton; pass new Skeleton(bones)`);let r=t?.length/4;if(!Number.isInteger(r)||r<1)throw RangeError(`Skin joints need four bone indices per vertex for at least one vertex`);this.count=this.dirtyTo=r;let i=/* @__PURE__ */ new ArrayBuffer(r*32);this.ids=new Uint32Array(i),this.weights=new Float32Array(i),this.setInfluences(0,t,n)}setInfluences(e,t,n){let r=t?.length/4,i=this.skeleton.count;if(!Number.isInteger(e)||e<0||!Number.isInteger(r)||e+r>this.count)throw RangeError(`Skin influences for vertices ${e}+ exceed the ${this.count} vertices; pass 4 joints each`);if(n?.length!==t.length)throw RangeError(`Skin weights need one weight per joint index; pass 4 weights per vertex`);for(let r=0;r<t.length;r++){let a=t[r],o=n[r];if(!Number.isInteger(a)||a<0||a>=i)throw RangeError(`Skin joint ${a} at vertex ${e+(r>>2)} is not a bone; use 0 to ${i-1}`);if(typeof o!=`number`||!Number.isFinite(o)||o<0)throw RangeError(`Skin weight ${o} at vertex ${e+(r>>2)} is invalid; use a finite number >= 0`)}for(let i=0;i<r;i++){let r=(e+i)*8,a=n[i*4]+n[i*4+1]+n[i*4+2]+n[i*4+3];for(let e=0;e<4;e++)this.ids[r+e]=a>0?t[i*4+e]:this.skeleton.root,this.weights[r+4+e]=a>0?n[i*4+e]/a:+(e===0)}return this.edits++,this.dirtyFrom=Math.min(this.dirtyFrom,e),this.dirtyTo=Math.max(this.dirtyTo,e+r),this}pose(e,t){let n=l(e,this.count*3,`Skin positions`),r=t===void 0?void 0:l(t,this.count*3,`Skin normals`),i=this.skeleton.skinMatrices,a=/* @__PURE__ */ new Float64Array(16),o=new Float32Array(this.count*3),s=r&&new Float32Array(this.count*3);for(let e=0,t=0;e<this.count;e++,t+=3){a.fill(0);for(let t=0;t<4;t++){let n=this.weights[e*8+4+t],r=this.ids[e*8+t]*16;if(n)for(let e=0;e<16;e++)a[e]+=n*i[r+e]}for(let e=0;e<3;e++)o[t+e]=a[e]*n[t]+a[4+e]*n[t+1]+a[8+e]*n[t+2]+a[12+e];if(!r||!s)continue;let c=[a[5]*a[10]-a[6]*a[9],a[6]*a[8]-a[4]*a[10],a[4]*a[9]-a[5]*a[8]],l=[a[9]*a[2]-a[10]*a[1],a[10]*a[0]-a[8]*a[2],a[8]*a[1]-a[9]*a[0]],u=[a[1]*a[6]-a[2]*a[5],a[2]*a[4]-a[0]*a[6],a[0]*a[5]-a[1]*a[4]],d=a[0]*c[0]+a[1]*c[1]+a[2]*c[2]<0?-1:1,f=(c[0]*r[t]+l[0]*r[t+1]+u[0]*r[t+2])*d,p=(c[1]*r[t]+l[1]*r[t+1]+u[1]*r[t+2])*d,m=(c[2]*r[t]+l[2]*r[t+1]+u[2]*r[t+2])*d,h=Math.hypot(f,p,m);s[t]=h>0?f/h:0,s[t+1]=h>0?p/h:1,s[t+2]=h>0?m/h:0}return s?{positions:o,normals:s}:{positions:o}}get picking(){let e=this;return this.pickingSource??={get root(){return e.requireMesh().root},get disposed(){return e.disposed||!e.mesh||e.mesh.disposed},posePickingGeometry:()=>{let e=this.requireMesh(),t=this.skeleton.revision+`:`+this.edits;if(this.posed?.key===t&&this.posed.mesh===e){for(let e of this.posed.list)e.matrix.set(e.node.matrix);return this.posed.list}let n=e.primitives[0].vertices,r=new Float32Array(this.count*3),i=new Float32Array(this.count*3);for(let e=0;e<this.count;e++)for(let t=0;t<3;t++)r[e*3+t]=n[e*20+t],i[e*3+t]=n[e*20+4+t];let a=this.pose(r,i),o=n.slice();for(let e=0;e<this.count;e++)for(let t=0;t<3;t++)o[e*20+t]=a.positions[e*3+t],o[e*20+4+t]=a.normals[e*3+t];let s=e.primitives.map((e,t)=>{let n=e.material,r=n.side??(n.settings[2]===2?`back`:n.settings[2]>=.5?`double`:`front`);return{node:e.node,vertices:o,indices:e.indices instanceof Uint32Array?e.indices:Uint32Array.from(e.indices),doubleSided:r===`double`,side:r,matrix:new Float32Array(e.node.matrix),primitiveIndex:t}});return this.posed={key:t,mesh:e,list:s},s}}}requireMesh(){if(!this.mesh)throw new i(`state`,`Skin is not attached; create it with Skin.attach(mesh, skeleton, joints, weights)`);return this.mesh}static attach(e,t,r,a){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let o=new n(t,r,a),s=e?.primitives?.[0]?.vertices;if(!s||e.primitives.some(e=>e.vertices!==s))throw TypeError(`Skin needs a mesh whose primitives share one vertex array; use createMesh`);if(s.length/20!==o.count)throw RangeError(`Skin has ${o.count} vertices but the mesh has ${s.length/20}; match them`);if(e.disposed)throw new i(`disposed`,`Skin mesh is disposed; attach the skin to a live mesh`);if(e.primitives.some(e=>e.deformed))throw new i(`attached`,`Mesh is already deformed by another plugin; dispose that one first`);return o.mesh=e,e.root.engine.use(o),o}setup(t){let n=this.mesh;if(!n||this.disposed)throw new i(`state`,`Skin is not attached; create it with Skin.attach(mesh, skeleton, joints, weights)`);if(n.disposed)throw new i(`disposed`,`Skin mesh is disposed; attach the skin to a live mesh`);let a=t.gpu;if(!a)throw new i(`unsupported`,`Skin needs WebGPU; create the engine with the webgpu backend; see https://margoengine.com/errors#webgpu`);let o=m.get(a)??a.createComputePipeline({layout:`auto`,compute:{module:a.createShaderModule({code:r}),entryPoint:`main`}});m.set(a,o);let s=[],c=n.primitives[0].vertices,l=(e,t=GPUBufferUsage.STORAGE)=>{let n=a.createBuffer({size:Math.max(16,e),usage:t|GPUBufferUsage.COPY_DST});return s.push(n),n};if(Math.max(c.byteLength,this.count*32,this.skeleton.count*64)>Math.min(a.limits.maxStorageBufferBindingSize,a.limits.maxBufferSize))throw RangeError(`Skin buffers exceed the device storage limit; use fewer vertices or bones`);this.unsubscribe??=n.onDispose(()=>this.dispose());let u=l(c.byteLength),d=l(c.byteLength,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC),f=l(this.skeleton.count*64),p=l(this.count*32),h=l(16,GPUBufferUsage.UNIFORM),g=[u,d,l(48),l(16),f,p,h];a.queue.writeBuffer(h,0,new Uint32Array([this.count,0,this.skeleton.count,0])),this.gpu={buffers:s,source:u,output:d,bones:f,influences:p,pipeline:o,vertices:void 0,palette:new Float32Array(this.skeleton.count*16),group:a.createBindGroup({layout:o.getBindGroupLayout(0),entries:g.map((e,t)=>({binding:t,resource:{buffer:e}}))})},this.uploaded=-1,this.dirtyFrom=0,this.dirtyTo=this.count;for(let t of n.primitives)t.deformed=d,e(t,this.scenePose);n.prepareDeformation=this.prepare}registerPasses(e){e.add({name:this.name,order:-10,execute:e=>this.deform(e)})}deform(e){let t=this.gpu,n=this.mesh;if(e.backend!==`webgpu`||!t||!n||n.disposed)return;let r=e.device.queue,a=n.primitives[0].vertices,o=!1;if(t.vertices!==a){if(a.length!==this.count*20)throw new i(`state`,`Skin mesh vertex count changed; create a new Skin for the new geometry`);r.writeBuffer(t.source,0,a),t.vertices=a,o=!0}if(this.uploaded!==this.skeleton.revision&&(t.palette.set(this.skeleton.skinMatrices),r.writeBuffer(t.bones,0,t.palette),this.uploaded=this.skeleton.revision,o=!0),this.dirtyFrom<this.dirtyTo&&(r.writeBuffer(t.influences,this.dirtyFrom*32,this.ids.subarray(this.dirtyFrom*8,this.dirtyTo*8)),this.dirtyFrom=this.count,this.dirtyTo=0,o=!0),!o)return;let s=e.encoder.beginComputePass();try{s.setPipeline(t.pipeline),s.setBindGroup(0,t.group),s.dispatchWorkgroups(Math.ceil(this.count/64))}finally{s.end()}}release(){let e=this.mesh,n=this.gpu;if(e&&n){e.prepareDeformation===this.prepare&&(e.prepareDeformation=void 0);for(let r of e.primitives)r.deformed===n.output&&(r.deformed=void 0),t(r,this.scenePose);for(let e of n.buffers)e.destroy();this.gpu=void 0}}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.release(),this.unsubscribe?.(),this.unsubscribe=void 0,this.mesh?.root.engine.sceneOf(this)?.removePlugin(this.name))}[Symbol.dispose??Symbol()](){this.dispose()}},_=/* @__PURE__ */ new Float64Array(4),v=[`discrete`,`linear`,`easeIn`,`easeOut`,`easeInOut`,`cubicSpline`],y=(e,t)=>e===`discrete`?0:e===`easeIn`?t*t*t:e===`easeOut`?1-(1-t)**3:e===`easeInOut`?t<.5?4*t*t*t:1-(2-2*t)**3/2:t;function b(e,t,n,r){let i=new Float64Array(t.length),a=new Float64Array(t.length*n),o=t.some(e=>e?.interpolation===`cubicSpline`)?new Float64Array(t.length*n*2):void 0,s=t.map((t,s)=>{let u=t?.time,d=t?.interpolation??`linear`;if(typeof u!=`number`||!Number.isFinite(u)||u<0||s>0&&u<=i[s-1])throw RangeError(`${e} key ${s} time ${u} is invalid; use increasing seconds >= 0`);if(!v.includes(d))throw TypeError(`${e} key ${s} interpolation ${d} is invalid; use one of ${v.join(`, `)}`);let f=l(t.value,n,`${e} key ${s} value`);if(!r)a.set(f,s*n);else if(f[0]||f[1]||f[2]||f[3])a.set(c(f,_),s*n);else throw RangeError(`${e} key ${s} is a zero quaternion; pass a unit quaternion`);return o&&(t.inTangent!==void 0&&o.set(l(t.inTangent,n,`${e} key ${s} inTangent`),s*n*2),t.outTangent!==void 0&&o.set(l(t.outTangent,n,`${e} key ${s} outTangent`),s*n*2+n)),i[s]=u,d});return o?{times:i,values:a,interpolations:s,tangents:o}:{times:i,values:a,interpolations:s}}var x=[`x`,`y`,`z`,`w`],S=[`r`,`g`,`b`,`a`],C=e=>Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView);function w(e,t,n,r){let i=t.split(`.`);if(i.some(e=>!e))throw TypeError(`${r} property path '${t}' has an empty segment; use names joined by dots`);let a=e;for(let e=0;e<i.length-1;e++){let n=a[i[e]];if(!n||typeof n!=`object`)throw RangeError(`${r} property path '${t}' stops at '${i.slice(0,e+1).join(`.`)}', which is ${n===null?`null`:typeof n}; check the path names an object`);a=n}let o=i[i.length-1];if(!(o in a))throw RangeError(`${r} property path '${t}' has no '${o}' on its object; check the spelling`);let s=a[o],c=e=>/* @__PURE__ */ TypeError(`${r} property '${t}' ${e}, which ${n} number${n>1?`s`:``} per key cannot drive; key a matching size or pass set`);if(typeof s==`number`||typeof s==`boolean`){if(n!==1)throw c(`is a ${typeof s}`);return typeof s==`number`?e=>a[o]=e[0]:e=>a[o]=e[0]>=.5}if(C(s)){if(s.length<n)throw c(`holds ${s.length} numbers`);if(a[o]!==s){let e=Array(n).fill(0);return t=>{for(let r=0;r<n;r++)e[r]=t[r];a[o]=e}}let e=s;return t=>{for(let r=0;r<n;r++)e[r]=t[r]}}if(s&&typeof s==`object`){let e=s,t=typeof e.r==`number`?S:x;for(let r=0;r<n;r++)if(typeof e[t[r]]!=`number`)throw c(`has no number field '${t[r]}'`);if(n===3&&t===x&&typeof e.set==`function`){let t=e.set;return n=>t.call(e,n[0],n[1],n[2])}return r=>{for(let i=0;i<n;i++)e[t[i]]=r[i]}}throw c(`is ${s===null?`null`:typeof s}, not a number, array or vector object`)}function T(e,t,n){if(typeof e==`number`||typeof e==`boolean`)n[0]=+e;else if(C(e))for(let r=0;r<t;r++)n[r]=e[r];else{let r=e,i=typeof r?.r==`number`?S:x;for(let e=0;e<t;e++)n[e]=r?.[i[e]]}return n}var E=[1,2,3,4].map(e=>new Float64Array(e)),D={number:[1],vector:[2,3,4],color:[3,4],quaternion:[4]};function O(e,t){let{target:n,property:r,get:i,set:a,keys:o,blend:s}=e;if(r===void 0==(a===void 0))throw TypeError(`${t} needs either a property path or a set accessor; pass exactly one`);if(r!==void 0&&(typeof r!=`string`||!r))throw TypeError(`${t} property must be a nonempty dot path such as 'material.roughness'`);if(a!==void 0&&typeof a!=`function`)throw TypeError(`${t} set must be a function`);if(i!==void 0&&typeof i!=`function`)throw TypeError(`${t} get must be a function`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`${t} name must be a string`);if(s!==void 0&&s!==`delta`&&s!==`weighted`)throw TypeError(`${t} blend ${s} is invalid; use delta or weighted`);if(!Array.isArray(o)||!o.length)throw TypeError(`${t} needs a nonempty keys array`);let c=Number(o[0]?.value?.length),l=e.type??(c===1?`number`:`vector`),u=D[l];if(!u)throw TypeError(`${t} type ${l} is invalid; use number, vector, color or quaternion`);if(!u.includes(c))throw RangeError(`${t} ${l} keys need ${u.join(` or `)} numbers each; pass that many in every key`);let d=e.name??r??`set`,f=b(t,o,c,l===`quaternion`),p=E[c-1],m=a?e=>{for(let t=0;t<c;t++)p[t]=e[t];a(p)}:w(n,r,c,t),h=(e=new Float64Array(c))=>{if(i)return T(i(),c,e);if(r===void 0)throw TypeError(`Property track ${d} has no get accessor; pass get to read it`);let t=n;for(let e of r.split(`.`))t=t[e];return T(t,c,e)};return{target:n,...r===void 0?{}:{property:r},name:d,type:l,size:c,...f,...s===void 0?{}:{blend:s},write:m,read:h}}function k(e){if(!e||!Array.isArray(e.tracks))throw TypeError(`Keyframe clip needs a tracks array`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`Keyframe clip name must be a string`);let t=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=[],a=[];e.tracks.forEach((e,n)=>{let o=`Keyframe track ${n}`,s=e?.target;if(s!==null&&(typeof s==`object`||typeof s==`function`)){let t=e,n=O(t,o),i=t.set??t.property,c=r.get(s)??/* @__PURE__ */ new Set;if(c.has(i))throw TypeError(`${o} repeats property ${n.name}; merge the keys`);r.set(s,c.add(i)),a.push(n);return}if(typeof s!=`string`||!s)throw TypeError(`${o} needs a nonempty string target, or an object target with a property`);let{path:c,keys:l,blend:u}=e;if(c!==`translation`&&c!==`rotation`&&c!==`scale`&&c!==`weights`)throw TypeError(`${o} path ${c} is invalid; use translation, rotation, scale or weights`);if(u!==void 0&&u!==`delta`&&u!==`weighted`)throw TypeError(`${o} blend ${u} is invalid; use delta or weighted`);if(t.has(s+`:`+c))throw TypeError(`${o} repeats ${s} ${c}; merge the keys`);if(t.add(s+`:`+c),!Array.isArray(l)||!l.length)throw TypeError(`${o} needs a nonempty keys array`);let d=c===`rotation`?4:c===`weights`?Number(l[0]?.value?.length):3;if(!(Number.isInteger(d)&&d>0))throw TypeError(`${o} weights keys need one number per morph target; pass a nonempty array`);let f=b(o,l,d,c===`rotation`);i.push({target:s,path:c,...f,...u===void 0?{}:{blend:u}})});let o=Math.max(0,...[...i,...a].map(e=>e.times[e.times.length-1])),s=n(e.markers??[]);if(s.some(e=>e.time>o))throw RangeError(`Keyframe clip marker is past the last key; move it inside the clip or add a key there`);return{name:e.name??``,duration:o,tracks:i,properties:a,markers:s}}function A(e,t,n){if(typeof t!=`number`||!Number.isFinite(t))throw RangeError(`Keyframe sample time ${t} is invalid; pass finite seconds`);let{times:r,values:i}=e,a=`path`in e?e.path!==`rotation`:e.type!==`quaternion`,o=a?i.length/r.length:4,s=r.length-1;if(n!==void 0&&!(n instanceof Float64Array&&n.length>=o))throw TypeError(`Keyframe sample target must be a Float64Array of at least ${o} numbers`);n??=new Float64Array(o);let l=0;if(t>=r[s])l=s;else if(t>r[0])for(let e=s;l+1<e;){let n=l+e>>1;r[n]<=t?l=n:e=n}let u=l===s||t<=r[l]?0:y(e.interpolations[l],(t-r[l])/(r[l+1]-r[l])),d=l*o,f=Math.min(l+1,s)*o;if(u>0&&u<1&&e.interpolations[l]===`cubicSpline`){let t=r[l+1]-r[l],s=u,p=s*s,m=p*s,h=e.tangents,g=l*o*2+o,_=(l+1)*o*2;for(let e=0;e<o;e++)n[e]=(2*m-3*p+1)*i[d+e]+(m-2*p+s)*t*h[g+e]+(-2*m+3*p)*i[f+e]+(m-p)*t*h[_+e];return a?n:(n[0]||n[1]||n[2]||n[3]||n.set(i.subarray(d,d+4)),c(n,n))}if(e.blend===`weighted`){if(u===0||u===1)return n.set(i.subarray(u?f:d,(u?f:d)+o)),n;if(a){for(let e=0;e<o;e++){let t=i[d+e],r=i[f+e],a=(1-u)*t+u*r;n[e]=Number.isFinite(a)?a:a>0?Math.max(t,r):Math.min(t,r)}return n}}else if(a||u===0||u===1){for(let e=0;e<o;e++)n[e]=u===1?i[f+e]:i[d+e]+(i[f+e]-i[d+e])*u;return n}let p=0;for(let e=0;e<4;e++)p+=i[d+e]*i[f+e];let m=p<0?-1:1,h=Math.acos(Math.min(1,Math.abs(p))),g=Math.sin(h),_=g>1e-6?Math.sin((1-u)*h)/g:1-u,v=(g>1e-6?Math.sin(u*h)/g:u)*m;for(let e=0;e<4;e++)n[e]=i[d+e]*_+i[f+e]*v;return c(n,n)}var j=/* @__PURE__ */ new Float64Array(4),M=(e,t)=>{let n=new Float64Array(t);return{value:n,pose:{[e]:n}}},N={translation:M(`translation`,3),rotation:M(`rotation`,4),scale:M(`scale`,3)},P=/* @__PURE__ */ new WeakMap;function F(e,t){let n=e.tracks,r=P.get(n);r||P.set(n,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return(!i||i.length!==n.length)&&(i=Int32Array.from(n,e=>e.path===`weights`?-1:t.index(e.target)),r.set(t,i)),i}function I(e,t,n){let r=typeof t==`number`?void 0:t,i=typeof t==`number`?t:n;if(r!==void 0&&!(r instanceof p)&&(!r||typeof r.setMorph!=`function`||!Array.isArray(r.model?.nodes)))throw TypeError(`applyKeyframeClip needs a Skeleton or an Animation; pass a skeleton or Animation.attach(model)`);let a=e?.properties??[];for(let e=0;e<a.length;e++)a[e].write(A(a[e],i,j));if(r===void 0){if(typeof i!=`number`||!Number.isFinite(i))throw RangeError(`Keyframe clip time ${i} is invalid; pass finite seconds`);return}if(r instanceof p){let t=e.tracks,n=F(e,r);for(let e=0;e<t.length;e++){let a=n[e],o=t[e];if(a<0)continue;let s=N[o.path];A(o,i,s.value),r.setPose(a,s.pose)}return}let{nodes:o,primitives:s}=r.model,c=/* @__PURE__ */ new Map;for(let e=o.length-1;e>=0;e--)typeof o[e].name==`string`&&c.set(o[e].name,e);for(let t of e.tracks){let e=c.get(t.target)??-1;if(e<0)continue;let n=A(t,i),a=o[e];if(t.path===`weights`){let i=s.find(t=>t.nodeIndex===e)?.weights.length??0;if(i!==n.length)throw RangeError(`Keyframe track ${t.target} weights has ${n.length} values but the node has ${i} morph targets; key one weight per target`);for(let t=0;t<i;t++)r.setMorph(e,t,n[t])}else t.path===`translation`?a.setPosition(n):t.path===`scale`?a.setScale(n):a.setQuaternion(n)}}function L(e,t,{loop:n=!1,timeScale:r=1}={}){if(![e,t,r].every(Number.isFinite)||e<0||t<0)throw RangeError(`Segment time needs finite elapsed and duration >= 0 and a finite timeScale`);let i=e*Math.abs(r),a=n&&t>0?i%t:Math.min(i,t);return r<0?t-a:a}function R(e){let t=new Float32Array([e]);return new Uint32Array(t.buffer)[0]--,t[0]}var z=e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`Keyframe bake fps ${e} is invalid; pass frames per second > 0`)};function B(e,t){z(t);let{times:n,interpolations:r}=e,i=new Set(r.slice(0,-1)),a=i.size===0||i.size===1&&(i.has(`discrete`)||i.has(`linear`)),o=[],s=[],c=(t,n=t)=>{let r=Math.fround(t);return o.length&&r<=o[o.length-1]?!1:(o.push(r),s.push(...A(e,n)),!0)};for(let i=0;i<n.length;i++){if(!c(n[i]))throw RangeError(`Keyframe track ${`path`in e?e.target+` `+e.path:e.name} keys are closer than Float32 time precision; space keys further apart`);if(a||i===n.length-1||r[i]===`linear`)continue;let o=Math.fround(n[i+1]);if(r[i]===`discrete`)c(R(o),n[i]);else for(let e=Math.floor(n[i]*t)+1;e/t<n[i+1];e++)Math.fround(e/t)<o&&c(e/t,Math.fround(e/t))}if(`path`in e?e.path===`rotation`:e.type===`quaternion`){for(let e=4;e<s.length;e+=4)if(s[e]*s[e-4]+s[e+1]*s[e-3]+s[e+2]*s[e-2]+s[e+3]*s[e-1]<0)for(let t=0;t<4;t++)s[e+t]=-s[e+t]}return{interpolation:a&&i.has(`discrete`)?`STEP`:`LINEAR`,times:Float32Array.from(o),values:Float32Array.from(s)}}function V(e,t,n){if(z(t),typeof n!=`function`)throw TypeError(`Keyframe bake needs a resolve(target) function`);let r=[];for(let i of e.tracks){let e=n(i.target);e!==void 0&&r.push({node:e,path:i.path,...B(i,t)})}return{name:e.name,channels:r}}export{A as a,g as c,k as i,V as n,L as o,B as r,p as s,I as t};
|