@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
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
2
|
+
import { type ClipMarker } from './sampling.js';
|
|
3
|
+
import { Skeleton } from './skin.js';
|
|
4
|
+
/**
|
|
5
|
+
* How a key moves to the next key: hold then jump, straight, a cubic ease in, out, or in and out, or `'cubicSpline'`: a
|
|
6
|
+
* Hermite spline through both keys with this key's `outTangent` and the next key's `inTangent` (glTF CUBICSPLINE).
|
|
7
|
+
*/
|
|
8
|
+
export type KeyInterpolation = 'discrete' | 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | 'cubicSpline';
|
|
9
|
+
/**
|
|
10
|
+
* The arithmetic {@link sampleKeyframes} blends two keys with, at eased factor f between key values a and b.
|
|
11
|
+
* - `'delta'` (the default): `a + (b - a) * f`. f = 0 still computes; when b - a overflows (keys near ±1.8e308 of
|
|
12
|
+
* opposite sign) the sample is NaN.
|
|
13
|
+
* - `'weighted'`: a held sample (f = 0 or 1, including before the first key, after the last and through discrete
|
|
14
|
+
* segments) copies the key's value before any arithmetic; between keys translation and scale are
|
|
15
|
+
* `(1 - f) * a + f * b`, which stays finite for all finite keys. Rotations slerp as in `'delta'`.
|
|
16
|
+
*/
|
|
17
|
+
export type KeyframeBlend = 'delta' | 'weighted';
|
|
18
|
+
/** The property a keyframe track animates: a bone's or node's transform, or a mesh node's morph target weights. */
|
|
19
|
+
export type KeyframePath = 'translation' | 'rotation' | 'scale' | 'weights';
|
|
20
|
+
/** One key of a keyframe track. */
|
|
21
|
+
export interface Keyframe {
|
|
22
|
+
/** Seconds, >= 0, strictly increasing within a track. */
|
|
23
|
+
time: number;
|
|
24
|
+
/**
|
|
25
|
+
* [x, y, z] for translation and scale, a quaternion [x, y, z, w] for rotation (normalised on input), and one weight
|
|
26
|
+
* per morph target for weights (the same count in every key, not normalised).
|
|
27
|
+
*/
|
|
28
|
+
value: readonly number[];
|
|
29
|
+
/** Shapes the time from this key to the next one (rotations slerp by the eased factor). Default 'linear'. */
|
|
30
|
+
interpolation?: KeyInterpolation;
|
|
31
|
+
/**
|
|
32
|
+
* For `'cubicSpline'` segments: the slope arriving at this key, in value units per second, one number per value
|
|
33
|
+
* component (default zeros). Read when the previous key is `'cubicSpline'`.
|
|
34
|
+
*/
|
|
35
|
+
inTangent?: readonly number[];
|
|
36
|
+
/** For a `'cubicSpline'` key: the slope leaving this key, in value units per second (default zeros). */
|
|
37
|
+
outTangent?: readonly number[];
|
|
38
|
+
}
|
|
39
|
+
/** Keys for one property of one bone or node. */
|
|
40
|
+
export interface KeyframeTrackData {
|
|
41
|
+
/** Stable id of the animated bone (its name) or of the caller's own node; for weights, the mesh node's name. */
|
|
42
|
+
target: string;
|
|
43
|
+
path: KeyframePath;
|
|
44
|
+
keys: readonly Keyframe[];
|
|
45
|
+
/** How samples between and at keys are computed; default `'delta'`. See {@link KeyframeBlend}. */
|
|
46
|
+
blend?: KeyframeBlend;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* What a {@link PropertyTrackData} value means: `'number'` (one number), `'vector'` (2 to 4 numbers blended per
|
|
50
|
+
* component), `'color'` (linear RGB or RGBA, blended per component in linear space; convert sRGB keys first) or
|
|
51
|
+
* `'quaternion'` ([x, y, z, w], normalised on input and slerped like rotations).
|
|
52
|
+
*/
|
|
53
|
+
export type PropertyValueType = 'number' | 'vector' | 'color' | 'quaternion';
|
|
54
|
+
/**
|
|
55
|
+
* Keys for any numeric, vector, colour or quaternion property of any object. Name the property with `property`, a dot
|
|
56
|
+
* path from `target` (`'material.roughness'`, `'position'`, `'lights.0.color'`), or pass `set` (and optionally
|
|
57
|
+
* `get`) accessors. A path is resolved once, when the clip is created, to a setter: a number property is assigned; a
|
|
58
|
+
* boolean property gets `value >= 0.5`; an array or typed array (a material's live colour) is written in place, or
|
|
59
|
+
* assigned when its getter returns a new array on every read; an `{x, y, z, w}` or `{r, g, b, a}` object (a mesh's
|
|
60
|
+
* `position`) is written field by field, through its `set(x, y, z)` when it has one. Replacing an object along the path
|
|
61
|
+
* later leaves the track driving the old one: create the clip again.
|
|
62
|
+
*/
|
|
63
|
+
export interface PropertyTrackData {
|
|
64
|
+
/** The object the property path starts from; with `set`, any value the accessors close over (used in labels). */
|
|
65
|
+
target: object;
|
|
66
|
+
/** Dot path from `target` to the property. Leave it out when passing `set`. */
|
|
67
|
+
property?: string;
|
|
68
|
+
/** Reads the current value (a number or 1-4 numbers), for {@link PropertyKeyframeTrack.read}. */
|
|
69
|
+
get?: () => number | ArrayLike<number>;
|
|
70
|
+
/** Writes a sampled value; the array is reused between calls, so copy it to keep it. */
|
|
71
|
+
set?: (value: Float64Array) => void;
|
|
72
|
+
/** Value type; default `'number'` for one-number keys and `'vector'` for longer ones. */
|
|
73
|
+
type?: PropertyValueType;
|
|
74
|
+
/** Label for errors and duplicate checks; default the property path, or `'set'`. */
|
|
75
|
+
name?: string;
|
|
76
|
+
/** 1 to 4 numbers per key (4 for quaternions, 3 or 4 for colours), the same count in every key. */
|
|
77
|
+
keys: readonly Keyframe[];
|
|
78
|
+
/** How samples between and at keys are computed; default `'delta'`. See {@link KeyframeBlend}. */
|
|
79
|
+
blend?: KeyframeBlend;
|
|
80
|
+
}
|
|
81
|
+
/** Raw clip input for {@link createKeyframeClip}: transform and weights tracks, and property tracks. */
|
|
82
|
+
export interface KeyframeClipData {
|
|
83
|
+
name?: string;
|
|
84
|
+
tracks: readonly (KeyframeTrackData | PropertyTrackData)[];
|
|
85
|
+
/** Named moments (footsteps, hits) in seconds, each within the clip's duration. Play them with `ClipMarkers` from `@margoengine/animation/sampling`. */
|
|
86
|
+
markers?: readonly ClipMarker[];
|
|
87
|
+
}
|
|
88
|
+
/** A validated track: key times, 3 or 4 values per key (weights: one per morph target), and each key's interpolation. */
|
|
89
|
+
export interface KeyframeTrack {
|
|
90
|
+
readonly target: string;
|
|
91
|
+
readonly path: KeyframePath;
|
|
92
|
+
readonly times: Float64Array;
|
|
93
|
+
readonly values: Float64Array;
|
|
94
|
+
readonly interpolations: readonly KeyInterpolation[];
|
|
95
|
+
/** Set when the track data chose a blend; undefined means `'delta'`. */
|
|
96
|
+
readonly blend?: KeyframeBlend;
|
|
97
|
+
/** Set when a key is `'cubicSpline'`: per key, its in tangent then its out tangent (2 x width numbers). */
|
|
98
|
+
readonly tangents?: Float64Array;
|
|
99
|
+
}
|
|
100
|
+
/** A validated property track: keys as on {@link KeyframeTrack} plus the binding its path or accessors resolved to. */
|
|
101
|
+
export interface PropertyKeyframeTrack {
|
|
102
|
+
readonly target: object;
|
|
103
|
+
/** The dot path, or undefined for an accessor track. */
|
|
104
|
+
readonly property?: string;
|
|
105
|
+
/** The label used in errors: the data's `name`, else the path, else `'set'`. */
|
|
106
|
+
readonly name: string;
|
|
107
|
+
readonly type: PropertyValueType;
|
|
108
|
+
/** Numbers per key, 1 to 4. */
|
|
109
|
+
readonly size: number;
|
|
110
|
+
readonly times: Float64Array;
|
|
111
|
+
readonly values: Float64Array;
|
|
112
|
+
readonly interpolations: readonly KeyInterpolation[];
|
|
113
|
+
readonly blend?: KeyframeBlend;
|
|
114
|
+
readonly tangents?: Float64Array;
|
|
115
|
+
/** Writes `size` numbers through the resolved binding (what {@link applyKeyframeClip} calls per frame). */
|
|
116
|
+
write(value: ArrayLike<number>): void;
|
|
117
|
+
/** The property's current value; throws TypeError for an accessor track without `get`. */
|
|
118
|
+
read(out?: Float64Array): Float64Array;
|
|
119
|
+
}
|
|
120
|
+
/** A validated clip; `duration` is its last key time. */
|
|
121
|
+
export interface KeyframeClip {
|
|
122
|
+
readonly name: string;
|
|
123
|
+
readonly duration: number;
|
|
124
|
+
readonly tracks: readonly KeyframeTrack[];
|
|
125
|
+
/** Property tracks, in data order (absent on clips built by hand before property tracks existed). */
|
|
126
|
+
readonly properties?: readonly PropertyKeyframeTrack[];
|
|
127
|
+
/** The clip's markers sorted by time (empty when none were given; absent on clips built by hand). */
|
|
128
|
+
readonly markers?: readonly ClipMarker[];
|
|
129
|
+
}
|
|
130
|
+
/** One glTF animation channel from {@link bakeKeyframeClip}: the shape of exporters' `AnimationChannelData`. */
|
|
131
|
+
export interface BakedChannel<N> {
|
|
132
|
+
node: N;
|
|
133
|
+
path: KeyframePath;
|
|
134
|
+
interpolation: 'STEP' | 'LINEAR';
|
|
135
|
+
times: Float32Array;
|
|
136
|
+
values: Float32Array;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Validates raw keys into a clip. Transform and weights tracks (a string `target` and a `path`) go to `tracks`;
|
|
140
|
+
* property tracks ({@link PropertyTrackData}: an object `target` with a `property` path or a `set` accessor) are bound
|
|
141
|
+
* once and go to `properties`. Throws TypeError for bad shapes, a repeated target+path or object+property, or a
|
|
142
|
+
* property path that ends on a value it cannot write, and RangeError for bad numbers or a path that does not resolve.
|
|
143
|
+
*/
|
|
144
|
+
export declare function createKeyframeClip(data: KeyframeClipData): KeyframeClip;
|
|
145
|
+
/**
|
|
146
|
+
* A track's value at `time` seconds: the first key's before it, the last key's after it, else the two surrounding keys
|
|
147
|
+
* blended by the earlier key's interpolation (rotations and quaternion properties by shortest-path slerp) with the
|
|
148
|
+
* track's {@link KeyframeBlend} arithmetic. A `'cubicSpline'` segment is the glTF CUBICSPLINE Hermite curve (tangents scaled
|
|
149
|
+
* by the segment's duration; quaternions normalised after). Deterministic for any frame rate. Property tracks sample
|
|
150
|
+
* the same way.
|
|
151
|
+
*/
|
|
152
|
+
export declare function sampleKeyframes(track: KeyframeTrack | PropertyKeyframeTrack, time: number, out?: Float64Array): Float64Array;
|
|
153
|
+
/**
|
|
154
|
+
* What {@link applyKeyframeClip} drives on a glTF PBR model: an `Animation` (`Animation.attach(model)`) fits, so morph
|
|
155
|
+
* weights go through its `setMorph`.
|
|
156
|
+
*/
|
|
157
|
+
export interface KeyframeModelTarget {
|
|
158
|
+
readonly model: PBRModel;
|
|
159
|
+
setMorph(node: number, target: number, weight: number): void;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Poses `target` at `time`. On a `Skeleton`, every translation, rotation or scale track whose target names one of its
|
|
163
|
+
* bones sets that bone's property (weights tracks are skipped: bones have no morphs). On a glTF PBR model's
|
|
164
|
+
* `Animation`, tracks name model nodes (the first node with that name): transform tracks set the node's local
|
|
165
|
+
* transform and weights tracks set every morph weight through `setMorph`. Pause the Animation's own clip
|
|
166
|
+
* (`animation.playing = false`) while a code clip drives the model, or the two overwrite each other. Every property
|
|
167
|
+
* track is written through its binding first, with or without a target; `applyKeyframeClip(clip, time)` writes only
|
|
168
|
+
* those. Allocates nothing per call for property tracks.
|
|
169
|
+
*/
|
|
170
|
+
export declare function applyKeyframeClip(clip: KeyframeClip, time: number): void;
|
|
171
|
+
export declare function applyKeyframeClip(clip: KeyframeClip, target: Skeleton | KeyframeModelTarget, time: number): void;
|
|
172
|
+
/**
|
|
173
|
+
* Clip time for a segment that has run `elapsed` seconds: scaled by `timeScale` (negative plays from the end in
|
|
174
|
+
* reverse), wrapped by `loop`, else held at the ends of `[0, duration]`.
|
|
175
|
+
*/
|
|
176
|
+
export declare function segmentTime(elapsed: number, duration: number, { loop, timeScale }?: {
|
|
177
|
+
loop?: boolean;
|
|
178
|
+
timeScale?: number;
|
|
179
|
+
}): number;
|
|
180
|
+
/** One baked glTF sampler from {@link bakeKeyframeTrack}: Float32 key times and values. */
|
|
181
|
+
export interface BakedSampler {
|
|
182
|
+
interpolation: 'STEP' | 'LINEAR';
|
|
183
|
+
times: Float32Array;
|
|
184
|
+
values: Float32Array;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* One track, transform or property, as a glTF sampler, by the rules of {@link bakeKeyframeClip}: only discrete keys
|
|
188
|
+
* become STEP and only linear keys LINEAR, exact everywhere; other tracks are LINEAR at the keys plus every `1 / fps`
|
|
189
|
+
* second inside eased and cubic segments, each value exactly what {@link sampleKeyframes} returns there. Rotations and
|
|
190
|
+
* quaternion properties flip sign where needed so neighbouring keys lie in one hemisphere.
|
|
191
|
+
*/
|
|
192
|
+
export declare function bakeKeyframeTrack(track: KeyframeTrack | PropertyKeyframeTrack, fps: number): BakedSampler;
|
|
193
|
+
/**
|
|
194
|
+
* glTF samplers for a clip, ready for exporters' `AnimationData` (`{name, channels}`) once `resolve` maps each track
|
|
195
|
+
* target to its `ExportNode`; tracks it maps to undefined are left out. A track of only discrete keys becomes STEP at
|
|
196
|
+
* its keys and one of only linear keys becomes LINEAR at its keys, both exact everywhere; any other track is LINEAR at
|
|
197
|
+
* its keys plus every `1 / fps` second inside eased and cubic segments, exact at those times, and a discrete segment
|
|
198
|
+
* inside it holds until one Float32 step before the next key. Property tracks have no glTF node path and are left out;
|
|
199
|
+
* bake them one at a time with {@link bakeKeyframeTrack}.
|
|
200
|
+
*/
|
|
201
|
+
export declare function bakeKeyframeClip<N>(clip: KeyframeClip, fps: number, resolve: (target: string) => N | undefined): {
|
|
202
|
+
name: string;
|
|
203
|
+
channels: BakedChannel<N>[];
|
|
204
|
+
};
|
package/dist/lod.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
2
|
+
import type { Engine, EnginePlugin } from '@margoengine/core/extension';
|
|
3
|
+
import type { Animation } from './index.js';
|
|
4
|
+
/** One detail level. A copy takes the last tier whose `distance` it has reached. */
|
|
5
|
+
export interface AnimationLODTier {
|
|
6
|
+
/** World units from the camera at which this tier starts, >= 0. Tiers are given nearest first; the first is 0. */
|
|
7
|
+
distance: number;
|
|
8
|
+
/** Frames between updates: 1 is every frame, 4 every fourth. An integer >= 1. */
|
|
9
|
+
interval: number;
|
|
10
|
+
/** Deepest node level still animated, counted from the scene roots (0). Deeper nodes hold. Default: all. */
|
|
11
|
+
depth?: number;
|
|
12
|
+
}
|
|
13
|
+
/** Options for {@link AnimationLOD}. */
|
|
14
|
+
export interface AnimationLODOptions {
|
|
15
|
+
/** Detail levels, nearest first. Default {@link defaultLODTiers}. */
|
|
16
|
+
tiers?: readonly AnimationLODTier[];
|
|
17
|
+
/** Used while a copy is off screen, at any distance. Default `{distance: 0, interval: 16, depth: 1}`. */
|
|
18
|
+
hidden?: AnimationLODTier;
|
|
19
|
+
}
|
|
20
|
+
/** One copy's options for {@link AnimationLOD.add}. */
|
|
21
|
+
export interface AnimationLODMember {
|
|
22
|
+
/** Radius of the sphere around the model root tested against the view, in world units. Default 2. */
|
|
23
|
+
radius?: number;
|
|
24
|
+
}
|
|
25
|
+
/** What one {@link AnimationLOD.update} did. */
|
|
26
|
+
export interface AnimationLODStats {
|
|
27
|
+
/** Copies posed this frame. */
|
|
28
|
+
updated: number;
|
|
29
|
+
/** Copies left as they were this frame. */
|
|
30
|
+
skipped: number;
|
|
31
|
+
/** Copies off screen. */
|
|
32
|
+
hidden: number;
|
|
33
|
+
}
|
|
34
|
+
/** Every frame up close, every second frame from 15 units, every fourth and only four levels deep from 40. */
|
|
35
|
+
export declare const defaultLODTiers: readonly AnimationLODTier[];
|
|
36
|
+
/**
|
|
37
|
+
* Takes over the playback of many `Animation`s and updates each as often as its distance and visibility call for:
|
|
38
|
+
* near copies every frame, far ones less often and with only their upper bones, off-screen ones rarely. Skipped time is
|
|
39
|
+
* kept, so a copy that is updated again lands exactly where it would have been. A copy's clip, speed and loop still
|
|
40
|
+
* come from its `Animation`.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* const lod = AnimationLOD.attach(stage.engine);
|
|
45
|
+
* for (const animation of crowd) lod.add(animation, {radius: 1.5});
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare class AnimationLOD implements EnginePlugin {
|
|
49
|
+
readonly name: string;
|
|
50
|
+
/** What the last update did. */
|
|
51
|
+
readonly stats: AnimationLODStats;
|
|
52
|
+
private readonly tiers;
|
|
53
|
+
private readonly hidden;
|
|
54
|
+
private readonly members;
|
|
55
|
+
private readonly quaternion;
|
|
56
|
+
private engine?;
|
|
57
|
+
private frame;
|
|
58
|
+
private next;
|
|
59
|
+
private disposed;
|
|
60
|
+
private elapsed;
|
|
61
|
+
/** Seconds this LOD has advanced its copies by. A fresh LOD reads 0. */
|
|
62
|
+
get time(): number;
|
|
63
|
+
/** Same as `engine.use(new AnimationLOD(...))`; returns it. */
|
|
64
|
+
static attach(engine: EngineKernel, options?: AnimationLODOptions): AnimationLOD;
|
|
65
|
+
constructor({ tiers, hidden }?: AnimationLODOptions);
|
|
66
|
+
/** Copies under this LOD. */
|
|
67
|
+
get count(): number;
|
|
68
|
+
/** Takes over a copy's playback from its current time; `remove` hands it back. */
|
|
69
|
+
add(animation: Animation, { radius }?: AnimationLODMember): this;
|
|
70
|
+
/** Hands a copy back to its `Animation`, fully posed at the time it has reached. */
|
|
71
|
+
remove(animation: Animation): boolean;
|
|
72
|
+
/** The tier a copy is on after the last update, or undefined if it is not under this LOD. */
|
|
73
|
+
tierOf(animation: Animation): AnimationLODTier | undefined;
|
|
74
|
+
setup(engine: Engine): void;
|
|
75
|
+
onPreUpdate(delta: number): void;
|
|
76
|
+
/** Advances every copy by `delta` seconds, posing those whose turn it is. */
|
|
77
|
+
update(delta: number): void;
|
|
78
|
+
/**
|
|
79
|
+
* Advances every copy's clock by `delta` seconds and picks its tier and turn from the camera, posing nothing: the
|
|
80
|
+
* CPU part of `update`, which a seek from `@margoengine/cutscene/seek` replays (the same turns as a continuous run
|
|
81
|
+
* when the camera is where it was); the next update poses the copies whose turn came, at the time they reached.
|
|
82
|
+
*/
|
|
83
|
+
advanceTime(delta: number): void;
|
|
84
|
+
private pose;
|
|
85
|
+
dispose(): void;
|
|
86
|
+
[Symbol.dispose]: () => void;
|
|
87
|
+
}
|
package/dist/lod.js
ADDED
|
@@ -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{o as e}from"./sampling-DjDWYqt2.js";import{MargoError as t}from"@margoengine/math/errors";var n=Object.freeze([Object.freeze({distance:0,interval:1}),Object.freeze({distance:15,interval:2}),Object.freeze({distance:40,interval:4,depth:4})]);function r(e,t){if(!Number.isFinite(e?.distance)||e.distance<0||!Number.isInteger(e.interval)||e.interval<1||e.depth!==void 0&&!(Number.isInteger(e.depth)&&e.depth>=0))throw RangeError(`${t} is invalid; use a distance >= 0, an integer interval >= 1 and an integer depth >= 0`)}function i(e){let t=e.model.asset.doc.nodes??[],n=new Int32Array(t.length),r=e=>t[e]?.children??[],i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)for(let t of r(e))i[t]=1;let a=[];for(let e=0;e<t.length;e++)i[e]||a.push(e);for(;a.length;){let e=a.pop();for(let t of r(e))n[t]=n[e]+1,a.push(t)}return n}var a=0,o=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);get time(){return this.elapsed}static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new o(t);return e.use(n),n}constructor({tiers:e=n,hidden:t={distance:0,interval:16,depth:1}}={}){if(this.name=`animation-lod:`+a++,this.stats={updated:0,skipped:0,hidden:0},this.members=/* @__PURE__ */ new Map,this.quaternion=[0,0,0,1],this.frame=0,this.next=0,this.disposed=!1,this.elapsed=0,!Array.isArray(e)||!e.length)throw TypeError(`AnimationLOD tiers must be a non-empty array`);e.forEach((t,n)=>{if(r(t,`AnimationLOD tier ${n}`),n?t.distance<=e[n-1].distance:t.distance!==0)throw RangeError(`AnimationLOD tiers must start at distance 0 and increase`)}),r(t,`AnimationLOD hidden tier`),this.tiers=e,this.hidden=t}get count(){return this.members.size}add(e,{radius:n=2}={}){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new one`);if(!Number.isFinite(n)||n<0)throw RangeError(`AnimationLOD radius must be a finite number >= 0`);let r=this.members.get(e);return r?(r.radius=n,this):(this.members.set(e,{animation:e,radius:n,phase:this.next++,owed:0,due:!1,time:e.time,playing:e.playing,tier:this.tiers[0],levels:i(e)}),e.playing=!1,this)}remove(e){let t=this.members.get(e);return t?(this.members.delete(e),!e.disposed&&!e.model.disposed&&(e.seek(t.time+t.owed*(e.options.speed??1)),e.playing=t.playing),!0):!1}tierOf(e){return this.members.get(e)?.tier}setup(e){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new controller before attaching`);this.engine=e}onPreUpdate(e){this.update(e)}update(e){this.advanceTime(e);for(let e of this.members.values())e.due&&(e.due=!1,this.pose(e,e.tier))}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);this.elapsed+=e;let t=this.engine?.camera,n=this.stats,r=this.frame++;n.updated=n.skipped=n.hidden=0;for(let i of this.members.values()){let{animation:a}=i;if(a.disposed||a.model.disposed){this.members.delete(a);continue}let o=a.model.root.matrix,s=o[12],c=o[13],l=o[14],u=this.tiers[0],d=!0;if(t){let e=t.position,n=Math.hypot(s-e[0],c-e[1],l-e[2]),r=t.planes;for(let e of this.tiers)n>=e.distance&&(u=e);for(let e=0;d&&e<24;e+=4)d=r[e]*s+r[e+1]*c+r[e+2]*l+r[e+3]>=-i.radius}d||(u=this.hidden,n.hidden++),i.tier=u,i.owed+=e,(r+i.phase)%u.interval?n.skipped++:(i.time+=i.owed*(a.options.speed??1),i.owed=0,i.due=!0,n.updated++)}}pose({animation:t,time:n,levels:r},i){if(i.depth===void 0){t.seek(n);return}let a=t.clips[t.clip];if(!a)return;let o=(t.options.loop??!0)&&a.duration>0?n%a.duration:Math.min(n,a.duration),s=t.model.nodes;t.time=n;for(let n of a.tracks){if(n.path!==`weights`&&r[n.node]>i.depth)continue;let a=e(n.times,n.values,n.width,o,n.interpolation,n.path===`rotation`,n.sample),c=s[n.node];if(n.path===`translation`)c.setPosition(a);else if(n.path===`scale`)c.setScale(a);else if(n.path===`rotation`){for(let e=0;e<4;e++)this.quaternion[e]=a[e];c.setQuaternion(this.quaternion)}else for(let e of t.model.primitives)e.nodeIndex===n.node&&e.weights.set(a)}}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.members.keys()])this.remove(e);this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as AnimationLOD,n as defaultLODTiers};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { PBRModel } from '@margoengine/gltf/pbr-model';
|
|
2
|
+
import { type AnimationDefinition } from './gltf.js';
|
|
3
|
+
type Property = 'offset' | 'scale';
|
|
4
|
+
interface MaterialTrack {
|
|
5
|
+
material: number;
|
|
6
|
+
property: Property;
|
|
7
|
+
times: Float32Array;
|
|
8
|
+
values: Float32Array;
|
|
9
|
+
}
|
|
10
|
+
/** @internal Validate only the fixed material pointer subset; leave ordinary node parsing to Animation. */
|
|
11
|
+
export declare function materialTracks(model: PBRModel, def: AnimationDefinition): {
|
|
12
|
+
tracks: MaterialTrack[];
|
|
13
|
+
nodeChannels: unknown[];
|
|
14
|
+
duration: number;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Create a fixed-target STEP texture-transform player for an original glTF clip index (default 0).
|
|
18
|
+
* seek uses finite nonnegative seconds, clamps by default, or wraps at the selected clip duration when loop is true.
|
|
19
|
+
* A zero-duration single-key clip always holds its key. Construction does not seek; dispose releases ownership,
|
|
20
|
+
* leaves the displayed sample intact and is safe to repeat. The model disposes its player automatically.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createMaterialAnimation(model: PBRModel, options?: {
|
|
23
|
+
clip?: number;
|
|
24
|
+
loop?: boolean;
|
|
25
|
+
}): {
|
|
26
|
+
seek(seconds: number): void;
|
|
27
|
+
dispose(): void;
|
|
28
|
+
};
|
|
29
|
+
export {};
|
package/dist/mixer.d.ts
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import { Animation, type KeyframeClip } from '@margoengine/animation';
|
|
3
|
+
import type { Engine, EnginePlugin } from '@margoengine/core/extension';
|
|
4
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
5
|
+
import type { DiscreteClip, BoundDiscreteTrack, DiscreteValue } from './discrete-tracks.js';
|
|
6
|
+
/** Play once, clamping at the directional endpoint. */
|
|
7
|
+
export declare const LoopOnce = 2200;
|
|
8
|
+
/** Repeat from the opposite endpoint. Default loop mode. */
|
|
9
|
+
export declare const LoopRepeat = 2201;
|
|
10
|
+
/** Alternate forward and backward traversals. */
|
|
11
|
+
export declare const LoopPingPong = 2202;
|
|
12
|
+
/** Weighted replacement, with the original property filling weight below one. */
|
|
13
|
+
export declare const NormalAnimationBlendMode = 2500;
|
|
14
|
+
/** Add translation/property deltas, multiply scale deltas and compose quaternion deltas. */
|
|
15
|
+
export declare const AdditiveAnimationBlendMode = 2501;
|
|
16
|
+
/** Supported action loop modes. */
|
|
17
|
+
export type ActionLoop = typeof LoopOnce | typeof LoopRepeat | typeof LoopPingPong;
|
|
18
|
+
/** A parsed glTF clip or a code-authored keyframe clip. */
|
|
19
|
+
export type ActionClip = Animation['clips'][number] | KeyframeClip | DiscreteClip;
|
|
20
|
+
/** A model, existing Animation, Skeleton, or object hosting bound property tracks. */
|
|
21
|
+
export type MixerRoot = object;
|
|
22
|
+
type Binding = {
|
|
23
|
+
base: Float64Array;
|
|
24
|
+
value: Float64Array;
|
|
25
|
+
total: number;
|
|
26
|
+
quaternion: boolean;
|
|
27
|
+
scale: boolean;
|
|
28
|
+
applied: boolean;
|
|
29
|
+
read(): ArrayLike<number>;
|
|
30
|
+
write(value: Float64Array): void;
|
|
31
|
+
};
|
|
32
|
+
type Channel = {
|
|
33
|
+
binding: Binding;
|
|
34
|
+
sample(time: number): ArrayLike<number>;
|
|
35
|
+
};
|
|
36
|
+
type DiscreteBinding = {
|
|
37
|
+
base: DiscreteValue;
|
|
38
|
+
value: DiscreteValue;
|
|
39
|
+
total: number;
|
|
40
|
+
winner: number;
|
|
41
|
+
applied: boolean;
|
|
42
|
+
channel: BoundDiscreteTrack;
|
|
43
|
+
};
|
|
44
|
+
type DiscreteChannel = {
|
|
45
|
+
binding: DiscreteBinding;
|
|
46
|
+
sample(time: number): DiscreteValue;
|
|
47
|
+
};
|
|
48
|
+
/** One cached clip playback, with an independent clock, weight and scheduled fades/warps. */
|
|
49
|
+
export declare class AnimationAction {
|
|
50
|
+
private readonly mixer;
|
|
51
|
+
private readonly clip;
|
|
52
|
+
private readonly root;
|
|
53
|
+
readonly blendMode: number;
|
|
54
|
+
private readonly channels;
|
|
55
|
+
private readonly discrete;
|
|
56
|
+
/** Local cycle time in seconds. Default 0. */
|
|
57
|
+
time: number;
|
|
58
|
+
/** Signed clip seconds per mixer second. Default 1. */
|
|
59
|
+
timeScale: number;
|
|
60
|
+
/** Contribution before a fade multiplier. Default 1. */
|
|
61
|
+
weight: number;
|
|
62
|
+
/** False mutes the action and stops its clock. Default true. */
|
|
63
|
+
enabled: boolean;
|
|
64
|
+
/** Freeze the clip clock while retaining its pose. Default false. */
|
|
65
|
+
paused: boolean;
|
|
66
|
+
/** Hold the last pose after finite playback. Default false (disable at completion). */
|
|
67
|
+
clampWhenFinished: boolean;
|
|
68
|
+
/** LoopRepeat by default. */
|
|
69
|
+
loop: ActionLoop;
|
|
70
|
+
/** Total traversals, Infinity by default; ignored by LoopOnce. */
|
|
71
|
+
repetitions: number;
|
|
72
|
+
private scheduled;
|
|
73
|
+
private loops;
|
|
74
|
+
private fade?;
|
|
75
|
+
private speed?;
|
|
76
|
+
private start?;
|
|
77
|
+
/** What the last clock step left for the blend: the clip time to sample and its weight (0: no contribution). */
|
|
78
|
+
private sampled;
|
|
79
|
+
private contribution;
|
|
80
|
+
/** @internal Actions are cached by AnimationMixer.clipAction. */
|
|
81
|
+
constructor(mixer: AnimationMixer, clip: ActionClip, root: MixerRoot, blendMode?: number, channels?: Channel[], discrete?: DiscreteChannel[]);
|
|
82
|
+
/** Start/resume without resetting the clock. */
|
|
83
|
+
play(): this;
|
|
84
|
+
/** Stop, restore original properties on the next mixer update, and reset. */
|
|
85
|
+
stop(): this;
|
|
86
|
+
/** Rewind, enable, unpause and clear envelopes. */
|
|
87
|
+
reset(): this;
|
|
88
|
+
/** Schedule a mixer-time start without changing the local clock. */
|
|
89
|
+
startAt(time: number): this;
|
|
90
|
+
/** Whether play() scheduled this action. */
|
|
91
|
+
isScheduled(): boolean;
|
|
92
|
+
/** Whether the action clock can currently advance. */
|
|
93
|
+
isRunning(): boolean;
|
|
94
|
+
/** Clip this action samples. */
|
|
95
|
+
getClip(): ActionClip;
|
|
96
|
+
/** Owning mixer. */
|
|
97
|
+
getMixer(): AnimationMixer;
|
|
98
|
+
/** Root this action affects. */
|
|
99
|
+
getRoot(): MixerRoot;
|
|
100
|
+
/** Current weight including enabled and fading. */
|
|
101
|
+
getEffectiveWeight(): number;
|
|
102
|
+
/** Current rate including pause and warping. */
|
|
103
|
+
getEffectiveTimeScale(): number;
|
|
104
|
+
private fadeFactor;
|
|
105
|
+
private rate;
|
|
106
|
+
/** Set contribution and cancel fading. */
|
|
107
|
+
setEffectiveWeight(weight: number): this;
|
|
108
|
+
/** Set rate and cancel warping. Negative rates run backwards. */
|
|
109
|
+
setEffectiveTimeScale(scale: number): this;
|
|
110
|
+
/** Set a positive wall-time duration for one traversal. */
|
|
111
|
+
setDuration(seconds: number): this;
|
|
112
|
+
/** Copy another action's clock/rate and cancel warping. */
|
|
113
|
+
syncWith(action: AnimationAction): this;
|
|
114
|
+
/** Select a mode and total traversal count. Default repetitions Infinity. */
|
|
115
|
+
setLoop(mode: ActionLoop, repetitions?: number): this;
|
|
116
|
+
private envelope;
|
|
117
|
+
/** Multiply weight by a ramp from zero to one. */
|
|
118
|
+
fadeIn(duration: number): this;
|
|
119
|
+
/** Multiply weight by a ramp from one to zero. */
|
|
120
|
+
fadeOut(duration: number): this;
|
|
121
|
+
/** Cancel the scheduled fade, retaining base weight. */
|
|
122
|
+
stopFading(): this;
|
|
123
|
+
/** Schedule absolute signed rates over mixer seconds. */
|
|
124
|
+
warp(from: number, to: number, duration: number): this;
|
|
125
|
+
/** Slow to a stop. */
|
|
126
|
+
halt(duration: number): this;
|
|
127
|
+
/** Cancel scheduled warping. */
|
|
128
|
+
stopWarping(): this;
|
|
129
|
+
/** Fade this action out and the destination in, optionally matching cycle rates during the transition. */
|
|
130
|
+
crossFadeTo(action: AnimationAction, duration: number, warp?: boolean): this;
|
|
131
|
+
/** Fade from another action into this one. */
|
|
132
|
+
crossFadeFrom(action: AnimationAction, duration: number, warp?: boolean): this;
|
|
133
|
+
/**
|
|
134
|
+
* @internal One step of the action clock (start time, warp and fade ends, loops), keeping the clip time and weight
|
|
135
|
+
* it reaches for {@link contribute}. The mixer's `advanceTime` runs it for every action.
|
|
136
|
+
*/
|
|
137
|
+
step(delta: number): void;
|
|
138
|
+
/** @internal Adds the channels at the clip time of the last {@link step} to the mixer, at its weight. */
|
|
139
|
+
contribute(): void;
|
|
140
|
+
/** @internal Binding ownership for cache eviction. */
|
|
141
|
+
uses(binding: Binding): boolean;
|
|
142
|
+
/** @internal Categorical binding ownership for activation and cache eviction. */
|
|
143
|
+
usesDiscrete(binding: DiscreteBinding): boolean;
|
|
144
|
+
/** @internal Reset cycle bookkeeping for absolute seeks. */
|
|
145
|
+
rewind(): void;
|
|
146
|
+
private finish;
|
|
147
|
+
}
|
|
148
|
+
/** Independent clip actions on one or more roots. Call update(delta) or register as an engine plugin. */
|
|
149
|
+
export declare class AnimationMixer implements EnginePlugin {
|
|
150
|
+
private readonly root;
|
|
151
|
+
/** Creates and registers a mixer for a root; disposing it removes its engine registration. */
|
|
152
|
+
static attach(engine: EngineKernel, root: MixerRoot): AnimationMixer;
|
|
153
|
+
/** Unique plugin identity. */
|
|
154
|
+
readonly name: string;
|
|
155
|
+
/** Global seconds. Default 0. */
|
|
156
|
+
time: number;
|
|
157
|
+
/** Global signed rate. Default 1. */
|
|
158
|
+
timeScale: number;
|
|
159
|
+
private readonly actions;
|
|
160
|
+
private readonly players;
|
|
161
|
+
private readonly owned;
|
|
162
|
+
private readonly bindings;
|
|
163
|
+
private readonly discreteBindings;
|
|
164
|
+
private engine?;
|
|
165
|
+
private disposed;
|
|
166
|
+
private readonly additive;
|
|
167
|
+
/** Construct over a model, existing Animation or Skeleton. Existing Animation playback is paused. */
|
|
168
|
+
constructor(root: MixerRoot);
|
|
169
|
+
/** @internal Guard all new work after disposal. */
|
|
170
|
+
assertLive(): void;
|
|
171
|
+
/** @internal A disposed model/player cannot start another action. */
|
|
172
|
+
assertRootLive(root: MixerRoot): void;
|
|
173
|
+
private rootAlive;
|
|
174
|
+
/** @internal Capture original values when a property's first action starts. */
|
|
175
|
+
activate(bindings: readonly Binding[]): void;
|
|
176
|
+
/** @internal Restore original values when its last action stops. */
|
|
177
|
+
deactivate(bindings: readonly Binding[]): void;
|
|
178
|
+
/** @internal Capture categorical originals on first activation. */
|
|
179
|
+
activateDiscrete(bindings: readonly DiscreteBinding[]): void;
|
|
180
|
+
/** @internal Restore categorical originals on last deactivation. */
|
|
181
|
+
deactivateDiscrete(bindings: readonly DiscreteBinding[]): void;
|
|
182
|
+
private player;
|
|
183
|
+
private resolve;
|
|
184
|
+
/** Return the cached action for this clip/root/blend mode, creating its bindings once. */
|
|
185
|
+
clipAction(clip: ActionClip | string | number, root?: object, blendMode?: number): AnimationAction;
|
|
186
|
+
/** Existing cached action or null. */
|
|
187
|
+
existingAction(clip: ActionClip | string | number, root?: object): AnimationAction | null;
|
|
188
|
+
/** Default animation root. */
|
|
189
|
+
getRoot(): MixerRoot;
|
|
190
|
+
/** Advance independent action clocks, then blend once per affected property. */
|
|
191
|
+
update(delta: number): this;
|
|
192
|
+
/**
|
|
193
|
+
* Moves the mixer clock by `delta` seconds times `timeScale` and steps every action's clock (start times, fades,
|
|
194
|
+
* warps, loops), writing no property: the CPU part of `update`, which a seek from `@margoengine/cutscene/seek`
|
|
195
|
+
* replays. The next update blends and writes the properties at the times reached.
|
|
196
|
+
*/
|
|
197
|
+
advanceTime(delta: number): void;
|
|
198
|
+
/** Blends every action's last step once per affected property and writes it. */
|
|
199
|
+
private blend;
|
|
200
|
+
/** Seek global playback from the beginning, scaling by timeScale. */
|
|
201
|
+
setTime(time: number): this;
|
|
202
|
+
/** Stop and rewind all actions, restoring captured original properties. */
|
|
203
|
+
stopAllAction(): this;
|
|
204
|
+
/** Remove cached actions for a clip/root. Stop them first. */
|
|
205
|
+
uncacheAction(clip: ActionClip | string | number, root?: object): void;
|
|
206
|
+
/** Remove all actions using a clip. */
|
|
207
|
+
uncacheClip(clip: ActionClip): void;
|
|
208
|
+
/** Stop and remove actions using a root. */
|
|
209
|
+
uncacheRoot(root: MixerRoot): void;
|
|
210
|
+
/** Engine plugin setup; no GPU resources of its own. */
|
|
211
|
+
setup(engine: Engine): void;
|
|
212
|
+
/** Engine plugin clock hook. */
|
|
213
|
+
onPreUpdate(delta: number): void;
|
|
214
|
+
/** Restore originals, detach by identity and release only Animations this mixer created. */
|
|
215
|
+
dispose(): void;
|
|
216
|
+
[Symbol.dispose]: () => void;
|
|
217
|
+
/** @internal Shared property accumulation, with deferred additive composition. */
|
|
218
|
+
accumulate(b: Binding, value: ArrayLike<number>, weight: number, mode: number): void;
|
|
219
|
+
private binding;
|
|
220
|
+
private bind;
|
|
221
|
+
private property;
|
|
222
|
+
private bindDiscrete;
|
|
223
|
+
/** @internal Categorical winner selection never averages booleans or string indices. */
|
|
224
|
+
accumulateDiscrete(binding: DiscreteBinding, value: DiscreteValue, weight: number): void;
|
|
225
|
+
}
|
|
226
|
+
export {};
|
package/dist/mixer.js
ADDED
|
@@ -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}from"./errors-t1ewumJS.js";import{MargoError as t}from"@margoengine/math/errors";import{Animation as n,Skeleton as r,sampleKeyframes as i}from"@margoengine/animation";import{sampleTrackInto as a}from"@margoengine/animation/sampling";var o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=2200,c=2201,l=2202,u=2500,d=2501,f=e=>`kind`in e&&e.kind===`discrete`,p=(e,t,n=-1/0)=>{if(!Number.isFinite(e)||e<n)throw o(`Invalid ${t}; pass a finite number >= ${n}`);return e},m=(e,t)=>e.from+(e.to-e.from)*Math.max(0,Math.min(1,(t-e.start)/e.duration));function h(e,t,n,r){let i=0;for(let n=0;n<4;n++)i+=e[n]*t[n];let a=i<0?-1:1;i=Math.min(1,Math.abs(i));let o=1-n,s=n;if(i<.9995){let e=Math.acos(i),t=Math.sin(e);o=Math.sin((1-n)*e)/t,s=Math.sin(n*e)/t}for(let n=0;n<4;n++)r[n]=e[n]*o+t[n]*s*a;let c=Math.hypot(...r);for(let e=0;e<4;e++)r[e]/=c}var g=class{constructor(e,t,n,r=u,i=[],a=[]){this.mixer=e,this.clip=t,this.root=n,this.blendMode=r,this.channels=i,this.discrete=a,this.time=0,this.timeScale=1,this.weight=1,this.enabled=!0,this.paused=!1,this.clampWhenFinished=!1,this.loop=c,this.repetitions=1/0,this.scheduled=!1,this.loops=0,this.sampled=0,this.contribution=0}play(){return this.mixer.assertLive(),this.mixer.assertRootLive(this.root),this.scheduled||this.mixer.activate(this.channels.map(e=>e.binding)),this.scheduled||this.mixer.activateDiscrete(this.discrete.map(e=>e.binding)),this.scheduled=!0,this}stop(){return this.scheduled=!1,this.mixer.deactivate(this.channels.map(e=>e.binding)),this.mixer.deactivateDiscrete(this.discrete.map(e=>e.binding)),this.reset()}reset(){return this.time=this.loops=0,this.enabled=!0,this.paused=!1,this.fade=this.speed=void 0,this.start=void 0,this}startAt(e){return this.start=p(e,`start time`),this}isScheduled(){return this.scheduled}isRunning(){return this.scheduled&&this.enabled&&!this.paused&&this.timeScale!==0&&(this.start===void 0||this.mixer.time>=this.start)}getClip(){return this.clip}getMixer(){return this.mixer}getRoot(){return this.root}getEffectiveWeight(){return this.enabled?this.weight*this.fadeFactor():0}getEffectiveTimeScale(){return this.paused?0:this.rate()}fadeFactor(){let e=this.fade;return e?e.duration?m(e,this.mixer.time):e.to:1}rate(){let e=this.speed;return e?e.duration?m(e,this.mixer.time):e.to:this.timeScale}setEffectiveWeight(e){return this.weight=p(e,`weight`,0),this.fade=void 0,this}setEffectiveTimeScale(e){return this.timeScale=p(e,`timeScale`),this.speed=void 0,this}setDuration(e){if(!(p(e,`duration`,0)>0))throw o(`Duration must be positive; pass seconds > 0`);return this.setEffectiveTimeScale(this.clip.duration/e)}syncWith(e){return this.time=e.time,this.setEffectiveTimeScale(e.timeScale)}setLoop(e,t=1/0){if(![2200,2201,2202].includes(e)||t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw o(`Invalid action loop; pass a loop mode and a positive integer count or Infinity`);return this.loop=e,this.repetitions=t,this}envelope(e,t,n){return p(n,`fade/warp duration`,0),{from:e,to:t,duration:n,start:this.mixer.time}}fadeIn(e){return this.fade=this.envelope(0,1,e),this}fadeOut(e){return this.fade=this.envelope(1,0,e),this}stopFading(){return this.fade=void 0,this}warp(e,t,n){return this.speed=this.envelope(p(e,`warp start`),p(t,`warp end`),n),this}halt(e){return this.warp(this.getEffectiveTimeScale(),0,e)}stopWarping(){return this.speed=void 0,this}crossFadeTo(e,t,n=!1){if(e.mixer!==this.mixer||e===this)throw o(`Crossfade needs a different action from this mixer; use mixer.clipAction`);if(p(t,`crossfade duration`,0),n&&(!(this.clip.duration>0)||!(e.clip.duration>0)))throw o(`Warp needs positive clip durations; omit warp for static clips`);if(this.fadeOut(t),e.fadeIn(t),n){let n=this.clip.duration/e.clip.duration;this.warp(1,n,t),e.warp(1/n,1,t)}return this}crossFadeFrom(e,t,n=!1){return e.crossFadeTo(this,t,n),this}step(e){if(this.contribution=0,!this.scheduled||!this.enabled)return;if(p(this.time,`action time`),p(this.timeScale,`timeScale`),p(this.weight,`weight`,0),this.start!==void 0){if(this.mixer.time<this.start)return;e=Math.min(e,this.mixer.time-this.start),this.start=void 0}let t=this.rate();if(this.speed){let e=this.speed;this.mixer.time>=e.start+e.duration&&(this.timeScale=t,this.speed=void 0,t===0&&(this.paused=!0))}let n=this.fadeFactor();if(this.fade){let e=this.fade;this.mixer.time>=e.start+e.duration&&(this.fade=void 0,e.to===0&&(this.enabled=!1))}let r=this.enabled?this.weight*n:0,i=this.clip.duration,a=this.time;if(!this.paused&&e*t!==0){let n=p(this.time+e*t,`advanced action time`);if(this.loop===2200||i===0)this.time=Math.max(0,Math.min(i,n)),(n>=i||n<0)&&(i>0||this.loop===2200||this.repetitions!==1/0)&&this.finish();else{let e=Math.floor(n/i);this.loops+Math.abs(e)>=this.repetitions?(this.time=n<0?0:i,this.loops=this.repetitions-1,this.finish()):(this.time=(n%i+i)%i,this.loops+=Math.abs(e))}a=this.time}this.loop===2202&&this.loops%2&&(a=i-a),this.enabled||(r=0),this.sampled=a,this.contribution=r}contribute(){let e=this.sampled,t=this.contribution;if(t>0){for(let n of this.channels)this.mixer.accumulate(n.binding,n.sample(e),t,this.blendMode);for(let n of this.discrete)this.mixer.accumulateDiscrete(n.binding,n.sample(e),t)}}uses(e){return this.channels.some(t=>t.binding===e)}usesDiscrete(e){return this.discrete.some(t=>t.binding===e)}rewind(){this.time=this.loops=0}finish(){this.clampWhenFinished?this.paused=!0:this.enabled=!1}},_=class e{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(t,n){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let r=new e(n);try{return t.use(r),r}catch(e){throw r.dispose(),e}}constructor(e){this.root=e,this.time=0,this.timeScale=1,this.actions=[],this.players=/* @__PURE__ */ new Map,this.owned=/* @__PURE__ */ new Set,this.bindings=/* @__PURE__ */ new Map,this.discreteBindings=/* @__PURE__ */ new Map,this.disposed=!1,this.additive=/* @__PURE__ */ new Map,this.name=`animation-mixer:`+v++,this.player(e)}assertLive(){if(this.disposed)throw new t(`disposed`,`AnimationMixer is disposed; create a new mixer; see https://margoengine.com/errors#disposed`)}assertRootLive(e){let r=this.players.get(e);if(r instanceof n){if(r.model.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);r.captureState()}}rootAlive(e){let t=this.players.get(e);return!(t instanceof n)||!t.model.disposed}activate(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.uses(t))||t.base.set(Array.from(t.read()))}deactivate(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.uses(t))&&(this.actions.some(e=>e.uses(t)&&this.rootAlive(e.getRoot()))&&t.write(t.base),t.applied=!1)}activateDiscrete(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))||(t.base=t.channel.read())}deactivateDiscrete(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))&&(this.actions.some(e=>e.usesDiscrete(t)&&this.rootAlive(e.getRoot()))&&t.channel.write(t.base),t.applied=!1)}player(e){if(this.players.has(e))return this.players.get(e);let i=this.players.get(e);if(!i){if(!e||typeof e!=`object`)throw o(`Invalid mixer root; pass an object, model, Skeleton or Animation`);if(e instanceof r||e instanceof n)i=e;else if(Array.isArray(e.nodes)&&e.root?.scene){let r=e;if(r.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);i=new n(r),r.root.scene.use(i)}i instanceof n&&(i.playing=!1,i!==e&&this.owned.add(i)),this.players.set(e,i)}return i}resolve(e,t){let r=this.player(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;if(!i||!Number.isFinite(i.duration)||i.duration<0||!Array.isArray(i.tracks))throw o(`Unknown mixer clip; use an Animation clip or createKeyframeClip`);return i}clipAction(e,t=this.root,n=u){if(this.assertLive(),![2500,2501].includes(n))throw o(`Invalid blend mode; choose NormalAnimationBlendMode or AdditiveAnimationBlendMode`);let r=this.resolve(e,t);if(this.assertRootLive(t),f(r)&&n===2501)throw o(`Categorical tracks have no additive arithmetic; use NormalAnimationBlendMode`);let i=this.actions.find(e=>e.getClip()===r&&e.getRoot()===t&&e.blendMode===n);return i||(i=new g(this,r,t,n,this.bind(r,t),this.bindDiscrete(r)),this.actions.push(i)),i}existingAction(e,t=this.root){let r=this.players.get(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;return i?this.actions.find(e=>e.getClip()===i&&e.getRoot()===t)??null:null}getRoot(){return this.root}update(e){return this.advanceTime(e),this.blend(),this}advanceTime(e){this.assertLive(),p(e,`mixer delta`),p(this.timeScale,`mixer timeScale`);let t=e*this.timeScale;p(this.time+t,`mixer time`),this.time+=t;let r=this.actions.filter(e=>{let t=this.players.get(e.getRoot());return t instanceof n&&t.model.disposed});for(let e of r)this.actions.splice(this.actions.indexOf(e),1);for(let[e,t]of this.bindings){for(let[e,n]of t)r.some(e=>e.uses(n))&&!this.actions.some(e=>e.uses(n))&&t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)r.some(e=>e.usesDiscrete(n))&&!this.actions.some(e=>e.usesDiscrete(n))&&t.delete(e);t.size||this.discreteBindings.delete(e)}for(let e of this.actions)e.step(t)}blend(){this.additive.clear();for(let e of this.discreteBindings.values())for(let t of e.values())t.total=0,t.winner=-1/0,t.value=t.base;for(let e of this.bindings.values())for(let t of e.values())t.total=0,t.value.fill(0);for(let e of this.actions)e.contribute();for(let e of this.bindings.values())for(let t of e.values()){let e=t.total>0||this.additive.has(t);if(e||t.applied){if(t.total===0)t.value.set(t.base);else if(t.quaternion)t.total<1&&h(t.base,t.value,t.total,t.value);else for(let e=0;e<t.value.length;e++)t.value[e]=t.value[e]/Math.max(1,t.total)+t.base[e]*Math.max(0,1-t.total);for(let e of this.additive.get(t)??[])if(t.quaternion){let n=/* @__PURE__ */ new Float64Array(4);h([0,0,0,1],e.value,e.weight,n);let[r,i,a,o]=t.value,[s,c,l,u]=n;t.value.set([o*s+r*u+i*l-a*c,o*c-r*l+i*u+a*s,o*l+r*c-i*s+a*u,o*u-r*s-i*c-a*l])}else for(let n=0;n<t.value.length;n++)t.value[n]=t.scale?t.value[n]*(1+(e.value[n]-1)*e.weight):t.value[n]+e.value[n]*e.weight;t.write(t.value),t.applied=e}}for(let e of this.discreteBindings.values())for(let t of e.values()){let e=t.total>0;(e||t.applied)&&(t.channel.write(!e||Math.max(0,1-t.total)>t.winner?t.base:t.value),t.applied=e)}}setTime(e){p(e,`mixer seek`),this.time=0;for(let e of this.actions)e.rewind();return this.update(e)}stopAllAction(){for(let e of this.actions)e.stop();return this.update(0)}uncacheAction(e,t=this.root){let n=this.resolve(e,t);for(let e=this.actions.length-1;e>=0;e--)this.actions[e].getClip()===n&&this.actions[e].getRoot()===t&&(this.actions[e].stop(),this.actions.splice(e,1));this.update(0);for(let[e,t]of this.bindings){for(let[e,n]of t)this.actions.some(e=>e.uses(n))||t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)this.actions.some(e=>e.usesDiscrete(n))||t.delete(e);t.size||this.discreteBindings.delete(e)}}uncacheClip(e){for(let t of this.players.keys())this.uncacheAction(e,t)}uncacheRoot(e){for(let t of[...this.actions])t.getRoot()===e&&this.uncacheAction(t.getClip(),e);this.update(0);let t=this.players.get(e);t instanceof n&&this.owned.delete(t)&&t.dispose(),this.players.delete(e)}setup(e){this.assertLive(),this.engine=e}onPreUpdate(e){this.update(e)}dispose(){if(!this.disposed){this.stopAllAction(),this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name);for(let e of this.owned)e.dispose();this.owned.clear(),this.actions.length=0,this.players.clear(),this.bindings.clear(),this.discreteBindings.clear(),this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}accumulate(e,t,n,r){if(r===2501){let r=this.additive.get(e);r||this.additive.set(e,r=[]),r.push({value:Float64Array.from(t),weight:n});return}let i=e.total+n;if(e.quaternion)e.total===0?e.value.set(Array.from(t)):h(e.value,t,n/i,e.value);else for(let r=0;r<e.value.length;r++)e.value[r]+=t[r]*n;e.total=i}binding(e,t,n,r,i=!1,a=!1,o=()=>n){let s=this.bindings.get(e);s||this.bindings.set(e,s=/* @__PURE__ */ new Map);let c=s.get(t);return c||(c={base:Float64Array.from(n),value:new Float64Array(n.length),total:0,write:r,quaternion:i,scale:a,applied:!1,read:o},s.set(t,c)),c}bind(e,t){if(f(e))return[];let s=this.player(t),c=[],l=e.tracks[0]&&`target`in e.tracks[0]||`properties`in e;for(let t of e.tracks){let e=t.path,l;if(s instanceof r){if(!(`target`in t)||e===`weights`)continue;let n=s.index(t.target);if(n<0)continue;let r=s.getPose(n),i=e;l=this.binding(s,n+`:`+e,r[i],e=>s.setPose(n,{[i]:e}),e===`rotation`,e===`scale`,()=>s.getPose(n)[i])}else if(s instanceof n){let n=`node`in t?t.node:s.model.nodes.findIndex(e=>e.name===t.target);if(n<0)continue;let r=s.model.nodes[n];if(e===`weights`){let t=s.model.primitives.find(e=>e.nodeIndex===n);if(!t)continue;l=this.binding(r,e,t.weights,e=>{for(let t=0;t<e.length;t++)s.setMorph(n,t,e[t])})}else{let t=r.engine.store.transforms,n=r.id,i=e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]];l=this.binding(r,e,i,t=>{e===`translation`?r.setPosition(t):e===`scale`?r.setScale(t):r.setQuaternion(Array.from(t))},e===`rotation`,e===`scale`,()=>e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]])}}else throw o(`Transform tracks need a Skeleton or Animation root; use bound property tracks on plain objects`);if(`node`in t){let n=new Float32Array(t.width);c.push({binding:l,sample:r=>a(t.times,t.values,t.width,r,t.interpolation,e===`rotation`,n)})}else{let e=new Float64Array(t.values.length/t.times.length);c.push({binding:l,sample:n=>i(t,n,e)})}}let u=l?e.properties:`bind`in e&&e.bind?(e.bound??=e.bind()).properties:void 0;for(let e of u??[])this.property(e,c);return c}property(e,t){let n=this.binding(e.target,`property:`+(e.property??e.name),e.read(),t=>e.write(t),e.type===`quaternion`,!1,()=>e.read()),r=new Float64Array(e.size);t.push({binding:n,sample:t=>i(e,t,r)})}bindDiscrete(e){return f(e)?e.tracks.map(e=>{let t=this.discreteBindings.get(e.target);t||this.discreteBindings.set(e.target,t=/* @__PURE__ */ new Map);let n=t.get(e.property);if(!n){let r=e.read();n={base:r,value:r,total:0,winner:-1/0,applied:!1,channel:e},t.set(e.property,n)}else if(typeof n.base!=typeof e.read())throw o(`Categorical binding types disagree; use the same value type for one property`);return{binding:n,sample:t=>e.sample(t)}}):[]}accumulateDiscrete(e,t,n){if(typeof t!=`boolean`&&typeof t!=`string`||typeof t!=typeof e.base)throw o(`Categorical channel changed value type; return the original boolean or string type`);e.total+=n,n>=e.winner&&(e.winner=n,e.value=t)}},v=0;export{d as AdditiveAnimationBlendMode,g as AnimationAction,_ as AnimationMixer,s as LoopOnce,l as LoopPingPong,c as LoopRepeat,u as NormalAnimationBlendMode};
|