3D engine that AI agents drive
Add Hermite curves and deterministic animation mixing
Nguyen Xuan An69592432e950
diff --git a/docs/animation-curves.md b/docs/animation-curves.mdnew file mode 100644index 00000000..5e333b75--- /dev/null+++ b/docs/animation-curves.md@@ -0,0 +1,71 @@+# Animation curves++`createAnimationClip` accepts `LINEAR`, `STEP`, `SMOOTH` and `CUBICSPLINE` tracks.+Clips own immutable copies of their keyframes, values and tangents.+`sampleAnimationClip` returns independent scalar values or arrays.++```js+const clip = createAnimationClip({+ duration: 2,+ tracks: [{+ target: 'part',+ property: 'translation',+ interpolation: 'CUBICSPLINE',+ keyframes: [+ { time: 0, value: [0, 0, 0], inTangent: [0, 0, 0], outTangent: [4, 0, 0] },+ { time: 2, value: [2, 0, 0], inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ ],+ }],+});+```++## Tangent contract++Spline tracks need at least two keyframes.+Each keyframe must contain finite `inTangent` and `outTangent` values with the same shape as its value.+Scalar properties use numbers. Translation and scale use three components. Rotation uses four components in `[x, y, z, w]` order.++Tangents express component changes per second. Quaternion tangents are component derivatives, not angular velocities.++The spline uses the starting keyframe's outgoing tangent and the ending keyframe's incoming tangent.+The Hermite equation multiplies those derivatives by the segment duration.+Quaternion curves interpolate their components, then normalize the result, without changing endpoint signs.+These interpolation rules follow [glTF Appendix C](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#appendix-c-animation-sampler-interpolation-modes).++Keyframe rotation values retain the existing normalization behavior. Tangents retain their supplied magnitude.+`LINEAR` and `SMOOTH` rotations retain shortest-arc spherical interpolation.+`STEP` holds the preceding keyframe. Endpoints clamp, and looping wraps negative times and exact clip boundaries.++## Output constraints++Spline overshoot clamps emission to zero or greater and metallic to `[0, 1]`.+It clamps roughness to `[1e-8, 1]` and scale components to `1e-8` or greater.+These constraints protect 67js material and positive-scale domains. They can flatten a curve near its limits.+Translation and generic `value` tracks keep their finite overshoot.++Nonfinite spline output and zero interpolated quaternions throw `RangeError`.+The player also rejects matrices that exceed the finite Float32 range.+A failed `apply()` leaves bound matrices and material properties unchanged.++## Playback buffers++`createAnimationPlayer` compiles target bindings and sampling buffers once.+Each `apply(time)` reuses transform arrays and composed matrix buffers.+It performs binary searches independently, so arbitrary seek order produces the same result.+Matrix identities and initial untracked transform components remain stable.++The player creates one shallow material copy for each target with material tracks during binding.+Additional players bound to the same target reuse that isolated material.+Animated targets therefore retain independent material properties even when their original material was shared or frozen.+Material identities remain stable during playback. Nested texture references stay shared.+Transform-only targets retain their original material objects.++## API design choice++| Shape | Example | Consequence |+| --- | --- | --- |+| Tangents in keyframes | `{ time, value, inTangent, outTangent }` | Supports JSON round trips, input validation and glTF derivative data. |+| Separate curve callback | `curve(time, output)` | Supports procedural curves but requires executable code and caller-managed state. |++Explicit tangent data keeps the existing track model and permits deterministic sampling without external callback state.+This unit does not add a mixer, skeletal animation, morph targets or glTF importer changes.diff --git a/docs/animation-mixer.md b/docs/animation-mixer.mdnew file mode 100644index 00000000..5d94daca--- /dev/null+++ b/docs/animation-mixer.md@@ -0,0 +1,94 @@+# Animation mixer++`createAnimationMixer(parts)` captures the initial local transforms and material values of named parts.+`clipAction(clip)` binds a clip from `createAnimationClip` and returns a reusable action.+Repeated calls with the same clip object return the same action.+`apply(time)` evaluates the complete scene at an absolute time in seconds and returns `parts`.++```js+import { createAnimationMixer } from '67js';++const mixer = createAnimationMixer(parts);+const walk = mixer.clipAction(walkClip).play({ at: 0 });+const gesture = mixer.clipAction(gestureClip);+mixer.crossFade(walk, gesture, { at: 2, duration: 0.5 });+mixer.apply(2.25);+mixer.apply(1);+```++## Action controls++| Method | Behavior |+| --- | --- |+| `play({ at, offset = 0, timeScale = 1, weight = 1 })` | Starts or restarts playback at `at`, with the given local offset and speed. |+| `stop(at)` | Stops contributing from `at` onward. Earlier times retain their recorded playback. |+| `fadeTo(weight, { at, duration })` | Interpolates from the effective weight at `at` to the target weight. |+| `getState(time)` | Returns `phase`, `playing`, `weight` and the unwrapped `localTime`. |+| `crossFade(from, to, { at, duration })` | Fades the source to zero and the destination to one. |++Omitted `at` and state-query times default to the last successful `apply()` time, initially zero.+Every action requires nondecreasing authored control times. Controls can share a timestamp, and the last control wins.+A new fade interrupts a previous fade continuously from its effective weight at the interruption time.+`crossFade` automatically starts a stopped destination at local time zero.+An already playing destination retains its playback origin, offset and speed.++Weights must be finite numbers within `[0, 1]`.+Fade duration must produce a finite end time strictly after its start.+Offsets and speeds must be finite. Negative speed reverses playback, and zero speed holds a local pose.+The source clip controls looping and endpoint clamping.++Action phases are `scheduled`, `playing`, `fading` and `stopped`.+A completed fade to zero keeps the action playing with zero weight.+Zero-weight actions skip curve evaluation. `stop()` records an explicit stopped state.++## Mixing rules++Mixing operates independently on each target property.+Clips that omit a property contribute no weight to that property.+When the total weight is below one, the captured base pose supplies the remaining weight.+When the total exceeds one, clip contributions normalize by their total weight.+Translation, scale and material properties use weighted linear interpolation.++Rotation uses incremental shortest-arc spherical interpolation in action registration order, followed by normalization.+Quaternion antipodes represent the same rotation and therefore blend without cancellation.+Three or more rotations can produce different results with different registration orders.+The weighting and rotation rules follow the installed Three.js `PropertyMixer` implementation.+Regression tests compare scalar and quaternion output against the installed Three.js mixer.++Scale and roughness remain at least `1e-8`.+Metallic and roughness remain at most one. Metallic and emission remain nonnegative.+These constraints can flatten curves near their domain limits.++## Seek and scene ownership++Playback retains control timelines and never consumes fade events during evaluation.+Backward and forward seeks therefore produce the same result for the same timeline and time.+Command authoring and playback seeking have separate ordering rules.+Controls allocate timeline records. Repeated `apply()` calls reuse compiled curve, mixing and matrix buffers.++Matrix identities remain stable. Untracked transform components retain their captured base values.+When all transform contributions stop, the mixer restores the captured matrix exactly.++Material tracks receive one shallow material copy per target during registration.+Players and mixers reuse the same isolated material when they bind the same target.+Material identities remain stable during playback, while nested texture references stay shared.+Parts without registered tracks retain their existing scene objects.++All samples and composed matrices must pass validation before the mixer writes scene properties.+Nonfinite output, invalid quaternions and Float32 matrix overflow throw without changing scene properties or the last successful mixer time.+Mixer matrices must be affine transforms with positive scale and no shear.+Tracked material properties must start in their valid domains. Missing emission defaults to zero.+The mixer owns registered properties during playback, so external writes do not change its captured base pose.++## API design choice++| Shape | Evaluation | Tradeoff |+| --- | --- | --- |+| Mutable action state with `update(delta)` | Advances clocks and consumes transitions. | Fits render loops, but arbitrary seeks need reconstruction of prior transitions. |+| Retained control timeline with `apply(time)` | Selects a state snapshot and evaluates its envelope. | Preserves seek history, with memory proportional to authored controls. |++Retained timelines support deterministic film sampling and interrupted fades without depending on previous evaluation calls.+The mixer uses `compileAnimationSampler` from the curve module, so interpolation math has one implementation.++Additive blending remains an open gap because it needs an explicit reference pose and quaternion delta convention.+This module does not add skeletal skinning, morph targets, hierarchy propagation, root motion extraction, transition warping or animation events.diff --git a/src/animation-mixer.js b/src/animation-mixer.jsnew file mode 100644index 00000000..528aab26--- /dev/null+++ b/src/animation-mixer.js@@ -0,0 +1,295 @@+import { mat4, quat } from 'gl-matrix';+import { compileAnimationSampler, retainAnimationMaterial } from './animation.js';++const MATERIAL_PROPERTIES = new Set(['emission', 'metallic', 'roughness']);+const MINIMUM_POSITIVE_VALUE = 1e-8;++function finiteTime(time) {+ if (!Number.isFinite(time)) throw new TypeError('Mixer times must be finite.');+ return time;+}++function validWeight(weight) {+ if (!Number.isFinite(weight) || weight < 0 || weight > 1) throw new RangeError('Action weights must be finite and within [0, 1].');+ return weight;+}++function capturedBinding(part) {+ if (!(part.matrix instanceof Float32Array) || part.matrix.length !== 16 || !part.matrix.every(Number.isFinite)) {+ throw new TypeError('Mixer parts need finite Float32Array matrices.');+ }+ if (part.matrix[3] !== 0 || part.matrix[7] !== 0 || part.matrix[11] !== 0 || part.matrix[15] !== 1) {+ throw new RangeError('Mixer matrices must be affine transforms.');+ }+ const originalMatrix = mat4.clone(part.matrix);+ const translation = mat4.getTranslation(new Float64Array(3), originalMatrix);+ const scale = mat4.getScaling(new Float64Array(3), originalMatrix);+ if (scale.some(component => component < Math.fround(MINIMUM_POSITIVE_VALUE))) throw new RangeError('Mixer matrices need nonzero positive scale.');+ const rotationMatrix = mat4.clone(originalMatrix);+ for (let column = 0; column < 3; column++) {+ for (let row = 0; row < 3; row++) rotationMatrix[column * 4 + row] /= scale[column];+ }+ if (mat4.determinant(rotationMatrix) < 0.9999) throw new RangeError('Mixer matrices cannot contain shear or reflected scale.');+ const rotation = quat.normalize(new Float64Array(4), mat4.getRotation(new Float64Array(4), rotationMatrix));+ return {+ part,+ originalMatrix,+ matrix: mat4.create(),+ base: { translation, rotation, scale, material: { ...part.material } },+ translation: new Float64Array(translation),+ rotation: new Float64Array(rotation),+ scale: new Float64Array(scale),+ properties: new Map(),+ material: null,+ hasTransform: false,+ transformWeight: 0,+ };+}++function propertyBinding(binding, property) {+ const materialProperty = MATERIAL_PROPERTIES.has(property);+ let base;+ let output;+ if (materialProperty) {+ const value = binding.base.material[property] ?? (property === 'emission' ? 0 : NaN);+ if (!Number.isFinite(value) || value < 0 || property === 'metallic' && value > 1 || property === 'roughness' && (value <= 0 || value > 1)) {+ throw new RangeError(`Mixer base ${property} must stay within its material range.`);+ }+ base = new Float64Array([value]);+ output = new Float64Array(1);+ } else {+ base = binding.base[property];+ if (!base) throw new RangeError(`Unsupported mixer property: ${property}`);+ output = binding[property];+ }+ return { binding, property, base, output, materialProperty, weight: 0 };+}++function timelineState(action, time) {+ const timeline = action.timeline;+ let lower = -1;+ let upper = timeline.length;+ while (upper - lower > 1) {+ const middle = Math.floor((lower + upper) / 2);+ if (timeline[middle].at <= time) lower = middle;+ else upper = middle;+ }+ return lower < 0 ? action.initial : timeline[lower];+}++function effectiveWeight(state, time) {+ if (!state.playing) return 0;+ if (time >= state.fadeEnd) return state.toWeight;+ if (time <= state.at) return state.fromWeight;+ const progress = (time - state.at) / (state.fadeEnd - state.at);+ return state.fromWeight * (1 - progress) + state.toWeight * progress;+}++function controlState(action, at) {+ finiteTime(at);+ const timeline = action.timeline;+ if (timeline.length && at < timeline[timeline.length - 1].at) {+ throw new RangeError('Schedule action controls in nondecreasing time order.');+ }+ return timelineState(action, at);+}++function playState(action, { at = 0, offset = 0, timeScale = 1, weight = 1 } = {}) {+ controlState(action, at);+ finiteTime(offset);+ if (!Number.isFinite(timeScale)) throw new TypeError('Action timeScale must be finite.');+ validWeight(weight);+ return { at, playing: true, origin: at, offset, timeScale, fromWeight: weight, toWeight: weight, fadeEnd: at };+}++function fadeState(action, weight, at, duration, previous = controlState(action, at)) {+ validWeight(weight);+ if (!Number.isFinite(duration) || duration <= 0 || !Number.isFinite(at + duration) || at + duration <= at) {+ throw new RangeError('Fade duration must produce a finite end time after its start.');+ }+ if (!previous.playing) throw new RangeError('Play the action before scheduling its fade.');+ return { ...previous, at, fromWeight: effectiveWeight(previous, at), toWeight: weight, fadeEnd: at + duration };+}++function accumulate(property, sample, weight) {+ const combinedWeight = property.weight + weight;+ if (property.weight === 0) property.output.set(sample);+ else {+ const progress = weight / combinedWeight;+ if (property.property === 'rotation') quat.slerp(property.output, property.output, sample, progress);+ else {+ for (let axis = 0; axis < property.output.length; axis++) {+ property.output[axis] = property.output[axis] * (1 - progress) + sample[axis] * progress;+ }+ }+ }+ property.weight = combinedWeight;+}++function finishProperty(property) {+ const output = property.output;+ if (property.weight < 1 && property.weight > 0) {+ if (property.property === 'rotation') quat.slerp(output, property.base, output, property.weight);+ else {+ for (let axis = 0; axis < output.length; axis++) {+ output[axis] = output[axis] * property.weight + property.base[axis] * (1 - property.weight);+ }+ }+ }+ for (let axis = 0; axis < output.length; axis++) {+ if (!Number.isFinite(output[axis])) throw new RangeError('Mixed animation output must be finite.');+ if (property.property === 'scale' || property.property === 'roughness') output[axis] = Math.max(MINIMUM_POSITIVE_VALUE, output[axis]);+ if (property.property === 'emission') output[axis] = Math.max(0, output[axis]);+ if (property.property === 'metallic') output[axis] = Math.max(0, output[axis]);+ if (property.property === 'metallic' || property.property === 'roughness') output[axis] = Math.min(1, output[axis]);+ }+ if (property.property === 'rotation') {+ const length = Math.hypot(output[0], output[1], output[2], output[3]);+ if (!Number.isFinite(length) || length === 0) throw new RangeError('Mixed rotation must be a finite nonzero quaternion.');+ for (let axis = 0; axis < 4; axis++) output[axis] /= length;+ }+ if (!property.materialProperty) property.binding.transformWeight += property.weight;+}++/** Retains base poses and absolute-time control timelines for independent seeks. */+export function createAnimationMixer(parts) {+ if (!Array.isArray(parts)) throw new TypeError('Mixer parts must be an array.');+ const namedBindings = new Map();+ const bindings = [];+ for (const part of parts) {+ if (!part || typeof part.name !== 'string' || !part.name.trim()) throw new TypeError('Mixer parts need names.');+ if (namedBindings.has(part.name)) throw new RangeError(`Duplicate mixer part name: ${part.name}`);+ const binding = capturedBinding(part);+ namedBindings.set(part.name, binding);+ bindings.push(binding);+ }+ const properties = [];+ const actions = [];+ const clipActions = new Map();+ const actionRecords = new Map();+ let mixerTime = 0;++ function clipAction(clip) {+ if (clipActions.has(clip)) return clipActions.get(clip);+ const sampler = compileAnimationSampler(clip);+ const entries = [];+ const pending = [];+ for (const track of sampler.tracks) {+ const binding = namedBindings.get(track.target);+ if (!binding) throw new RangeError(`Mixer target was not found: ${track.target}`);+ if (track.property === 'value') throw new RangeError('Value tracks cannot bind to mixer parts.');+ const property = binding.properties.get(track.property) ?? propertyBinding(binding, track.property);+ if (!binding.properties.has(track.property)) pending.push(property);+ entries.push({ property, sample: track.output });+ }+ const action = {+ sampler,+ entries,+ timeline: [],+ initial: { at: -Infinity, playing: false, origin: 0, offset: 0, timeScale: 1, fromWeight: 0, toWeight: 0, fadeEnd: -Infinity },+ };+ const publicAction = Object.freeze({+ clip,+ play({ at = mixerTime, offset = 0, timeScale = 1, weight = 1 } = {}) {+ action.timeline.push(playState(action, { at, offset, timeScale, weight }));+ return publicAction;+ },+ stop(at = mixerTime) {+ const previous = controlState(action, at);+ action.timeline.push({ ...previous, at, playing: false, fromWeight: 0, toWeight: 0, fadeEnd: at });+ return publicAction;+ },+ fadeTo(weight, { at = mixerTime, duration } = {}) {+ action.timeline.push(fadeState(action, weight, at, duration));+ return publicAction;+ },+ getState(time = mixerTime) {+ finiteTime(time);+ const state = timelineState(action, time);+ let phase = 'stopped';+ if (state.playing) phase = time < state.fadeEnd ? 'fading' : 'playing';+ if (state === action.initial && action.timeline.length && action.timeline[0].playing) phase = 'scheduled';+ return {+ phase,+ playing: state.playing,+ weight: effectiveWeight(state, time),+ localTime: state.playing ? (time - state.origin) * state.timeScale + state.offset : null,+ };+ },+ });+ // Registration validates every target before publishing bindings or material copies.+ for (const property of pending) {+ const binding = property.binding;+ binding.properties.set(property.property, property);+ properties.push(property);+ if (property.materialProperty) {+ if (!binding.material) {+ binding.material = retainAnimationMaterial(binding.part);+ }+ } else binding.hasTransform = true;+ }+ actions.push(action);+ clipActions.set(clip, publicAction);+ actionRecords.set(publicAction, action);+ return publicAction;+ }++ const mixer = {+ clipAction,+ get time() { return mixerTime; },+ crossFade(from, to, { at = mixerTime, duration } = {}) {+ const source = actionRecords.get(from);+ const destination = actionRecords.get(to);+ if (!source || !destination || source === destination) throw new RangeError('Crossfade needs two distinct actions from this mixer.');+ const sourceState = fadeState(source, 0, at, duration);+ const previous = controlState(destination, at);+ const destinationStart = previous.playing ? previous : playState(destination, { at, weight: 0 });+ const destinationState = fadeState(destination, 1, at, duration, destinationStart);+ source.timeline.push(sourceState);+ destination.timeline.push(destinationState);+ return mixer;+ },+ apply(time) {+ finiteTime(time);+ for (let index = 0; index < properties.length; index++) {+ const property = properties[index];+ property.output.set(property.base);+ property.weight = 0;+ }+ for (let index = 0; index < bindings.length; index++) bindings[index].transformWeight = 0;+ for (let index = 0; index < actions.length; index++) {+ const action = actions[index];+ const state = timelineState(action, time);+ const weight = effectiveWeight(state, time);+ if (weight === 0) continue;+ action.sampler.sample((time - state.origin) * state.timeScale + state.offset);+ for (let trackIndex = 0; trackIndex < action.entries.length; trackIndex++) {+ const entry = action.entries[trackIndex];+ accumulate(entry.property, entry.sample, weight);+ }+ }+ for (let index = 0; index < properties.length; index++) finishProperty(properties[index]);+ for (let index = 0; index < bindings.length; index++) {+ const binding = bindings[index];+ if (!binding.hasTransform) continue;+ if (binding.transformWeight === 0) binding.matrix.set(binding.originalMatrix);+ else mat4.fromRotationTranslationScale(binding.matrix, binding.rotation, binding.translation, binding.scale);+ for (let component = 0; component < 16; component++) {+ if (!Number.isFinite(binding.matrix[component])) throw new RangeError('Mixed matrix exceeds the finite Float32 range.');+ }+ }+ // Scene writes and mixer time change only after every output passes validation.+ for (let index = 0; index < properties.length; index++) {+ const property = properties[index];+ if (property.materialProperty) property.binding.material[property.property] = property.output[0];+ }+ for (let index = 0; index < bindings.length; index++) {+ const binding = bindings[index];+ if (binding.hasTransform) binding.part.matrix.set(binding.matrix);+ }+ mixerTime = time;+ return parts;+ },+ };+ return mixer;+}diff --git a/src/animation.js b/src/animation.jsindex 5ada5cb4..22d4acd1 100644--- a/src/animation.js+++ b/src/animation.js@@ -1,7 +1,31 @@import { mat4, quat } from 'gl-matrix';const PROPERTY_SIZES = { translation: 3, rotation: 4, scale: 3, value: 1, emission: 1, metallic: 1, roughness: 1 };-const INTERPOLATIONS = new Set(['LINEAR', 'STEP', 'SMOOTH']);+const INTERPOLATIONS = new Set(['LINEAR', 'STEP', 'SMOOTH', 'CUBICSPLINE']);+const MATERIAL_PROPERTIES = new Set(['emission', 'metallic', 'roughness']);+const MINIMUM_POSITIVE_VALUE = 1e-8;+const isolatedMaterials = new WeakMap();++/** Share one isolated target material across source-internal animation bindings. */+export function retainAnimationMaterial(part, candidate = { ...part.material }) {+ const retained = isolatedMaterials.get(part);+ const material = retained && retained === part.material ? retained : candidate;+ part.material = material;+ isolatedMaterials.set(part, material);+ return material;+}++function normalizedTangent(property, tangent) {+ const size = PROPERTY_SIZES[property];+ if (size === 1) {+ if (!Number.isFinite(tangent)) throw new TypeError('Spline tangents must be finite numbers.');+ return tangent;+ }+ if ((!Array.isArray(tangent) && !ArrayBuffer.isView(tangent)) || tangent.length !== size || !Array.from(tangent).every(Number.isFinite)) {+ throw new TypeError(`${property} tangents need ${size} finite values.`);+ }+ return Object.freeze(Array.from(tangent));+}function normalizedValue(property, value) {const size = PROPERTY_SIZES[property];@@ -19,7 +43,7 @@ function normalizedValue(property, value) {const result = Array.from(value);if (property === 'rotation') {const length = Math.hypot(...result);- if (length < 1e-8) throw new RangeError('Rotation keyframes cannot be zero quaternions.');+ if (!Number.isFinite(length) || length < 1e-8) throw new RangeError('Rotation keyframes need a finite nonzero quaternion length.');return Object.freeze(result.map(component => component / length));}if (property === 'scale' && result.some(component => component <= 0)) throw new RangeError('Scale keyframes must stay positive.');@@ -40,11 +64,17 @@ export function createAnimationClip({ duration, loop = false, tracks = [] } = {}const interpolation = track.interpolation ?? 'LINEAR';if (!INTERPOLATIONS.has(interpolation)) throw new RangeError(`Unknown interpolation: ${interpolation}`);if (!Array.isArray(track.keyframes) || !track.keyframes.length) throw new RangeError('Tracks need at least one keyframe.');+ if (interpolation === 'CUBICSPLINE' && track.keyframes.length < 2) throw new RangeError('Spline tracks need at least two keyframes.');const keyframes = track.keyframes.map(keyframe => {if (!keyframe || !Number.isFinite(keyframe.time) || keyframe.time < 0 || keyframe.time > duration) {throw new RangeError('Keyframe times must be within the clip duration.');}- return Object.freeze({ time: keyframe.time, value: normalizedValue(track.property, keyframe.value) });+ const compiledKeyframe = { time: keyframe.time, value: normalizedValue(track.property, keyframe.value) };+ if (interpolation === 'CUBICSPLINE') {+ compiledKeyframe.inTangent = normalizedTangent(track.property, keyframe.inTangent);+ compiledKeyframe.outTangent = normalizedTangent(track.property, keyframe.outTangent);+ }+ return Object.freeze(compiledKeyframe);}).sort((first, second) => first.time - second.time);for (let index = 1; index < keyframes.length; index++) {if (keyframes[index].time === keyframes[index - 1].time) throw new RangeError('Keyframe times must be distinct.');@@ -54,13 +84,27 @@ export function createAnimationClip({ duration, loop = false, tracks = [] } = {}return Object.freeze({ duration, loop, tracks: Object.freeze(compiled) });}-function sampleTrack(track, time) {+function constrainSample(property, value) {+ if (!Number.isFinite(value)) throw new RangeError('Animation output must be finite. Reduce the values or tangents.');+ if (property === 'scale') return Math.max(MINIMUM_POSITIVE_VALUE, value);+ if (property === 'emission') return Math.max(0, value);+ if (property === 'metallic') return Math.max(0, Math.min(1, value));+ if (property === 'roughness') return Math.max(MINIMUM_POSITIVE_VALUE, Math.min(1, value));+ return value;+}++function copySample(output, value) {+ if (typeof value === 'number') output[0] = value;+ else output.set(value);+ return output;+}++function sampleTrackInto(track, time, output) {const keyframes = track.keyframes;const first = keyframes[0];const last = keyframes[keyframes.length - 1];- const copy = value => typeof value === 'number' ? value : [...value];- if (time <= first.time) return copy(first.value);- if (time >= last.time) return copy(last.value);+ if (time <= first.time) return copySample(output, first.value);+ if (time >= last.time) return copySample(output, last.value);let lower = 0;let upper = keyframes.length - 1;while (upper - lower > 1) {@@ -70,18 +114,75 @@ function sampleTrack(track, time) {}const start = keyframes[lower];const end = keyframes[upper];- if (track.interpolation === 'STEP') return copy(start.value);- let progress = (time - start.time) / (end.time - start.time);+ if (time === start.time || track.interpolation === 'STEP') return copySample(output, start.value);+ const interval = end.time - start.time;+ let progress = (time - start.time) / interval;+ if (track.interpolation === 'CUBICSPLINE') {+ const squared = progress * progress;+ const cubed = squared * progress;+ const startWeight = 2 * cubed - 3 * squared + 1;+ const endWeight = -2 * cubed + 3 * squared;+ const outgoingWeight = (cubed - 2 * squared + progress) * interval;+ const incomingWeight = (cubed - squared) * interval;+ for (let axis = 0; axis < output.length; axis++) {+ const scalar = output.length === 1;+ const startValue = scalar ? start.value : start.value[axis];+ const endValue = scalar ? end.value : end.value[axis];+ const outgoing = scalar ? start.outTangent : start.outTangent[axis];+ const incoming = scalar ? end.inTangent : end.inTangent[axis];+ output[axis] = constrainSample(track.property,+ startWeight * startValue + outgoingWeight * outgoing + endWeight * endValue + incomingWeight * incoming);+ }+ if (track.property === 'rotation') {+ const length = Math.hypot(output[0], output[1], output[2], output[3]);+ if (!Number.isFinite(length) || length === 0) throw new RangeError('Spline produced an invalid quaternion. Adjust the rotation tangents.');+ for (let axis = 0; axis < 4; axis++) output[axis] /= length;+ }+ return output;+ }if (track.interpolation === 'SMOOTH') progress = progress * progress * (3 - 2 * progress);- if (track.property === 'rotation') return Array.from(quat.slerp(quat.create(), start.value, end.value, progress));- if (typeof start.value === 'number') return start.value + (end.value - start.value) * progress;- return start.value.map((value, axis) => value + (end.value[axis] - value) * progress);+ if (track.property === 'rotation') return quat.slerp(output, start.value, end.value, progress);+ for (let axis = 0; axis < output.length; axis++) {+ const startValue = output.length === 1 ? start.value : start.value[axis];+ const endValue = output.length === 1 ? end.value : end.value[axis];+ output[axis] = startValue + (endValue - startValue) * progress;+ }+ return output;}-export function sampleAnimationClip(clip, time) {+function normalizedTime(clip, time) {if (!Number.isFinite(time)) throw new TypeError('Animation time must be finite.');- const clipTime = clip.loop ? ((time % clip.duration) + clip.duration) % clip.duration : Math.max(0, Math.min(clip.duration, time));- return clip.tracks.map(track => ({ target: track.target, property: track.property, value: sampleTrack(track, clipTime) }));+ if (!clip.loop) return Math.max(0, Math.min(clip.duration, time));+ const remainder = time % clip.duration;+ return remainder < 0 ? remainder + clip.duration : remainder;+}++export function sampleAnimationClip(clip, time) {+ const clipTime = normalizedTime(clip, time);+ return clip.tracks.map(track => {+ const output = sampleTrackInto(track, clipTime, new Float64Array(PROPERTY_SIZES[track.property]));+ const value = output.length === 1 ? output[0] : Array.from(output);+ return { target: track.target, property: track.property, value };+ });+}++/** Internal compiled sampler for retained mixer buffers; not a package entry point. */+export function compileAnimationSampler(clip) {+ const tracks = clip.tracks.map(track => ({+ target: track.target,+ property: track.property,+ output: new Float64Array(PROPERTY_SIZES[track.property]),+ }));+ return {+ tracks,+ sample(time) {+ const clipTime = normalizedTime(clip, time);+ for (let index = 0; index < tracks.length; index++) {+ sampleTrackInto(clip.tracks[index], clipTime, tracks[index].output);+ }+ return tracks;+ },+ };}/** Bind once before playback. Matrix identities and untracked initial components stay stable. */@@ -92,6 +193,7 @@ export function createAnimationPlayer(clip, parts) {namedParts.set(part.name, part);}const bindings = new Map();+ const compiledTracks = [];for (const track of clip.tracks) {const part = namedParts.get(track.target);if (!part) throw new RangeError(`Animation target was not found: ${track.target}`);@@ -100,34 +202,54 @@ export function createAnimationPlayer(clip, parts) {if (!(part.matrix instanceof Float32Array) || part.matrix.length !== 16 || !Array.from(part.matrix).every(Number.isFinite)) {throw new TypeError('Animated parts need a finite Float32Array matrix.');}- const translation = mat4.getTranslation(new Float32Array(3), part.matrix);- const scale = mat4.getScaling(new Float32Array(3), part.matrix);- if (Array.from(scale).some(value => value < 1e-8)) throw new RangeError('Animated matrices must have nonzero scale.');+ const translation = mat4.getTranslation(new Float64Array(3), part.matrix);+ const scale = mat4.getScaling(new Float64Array(3), part.matrix);+ if (Array.from(scale).some(value => value < Math.fround(MINIMUM_POSITIVE_VALUE))) throw new RangeError('Animated matrices must have nonzero scale.');const rotationMatrix = mat4.clone(part.matrix);for (let column = 0; column < 3; column++) {for (let row = 0; row < 3; row++) rotationMatrix[column * 4 + row] /= scale[column];}if (mat4.determinant(rotationMatrix) < 0.9999) throw new RangeError('Animated matrices must use rotation and positive scale without shear.');- const rotation = quat.normalize(quat.create(), mat4.getRotation(quat.create(), rotationMatrix));- bindings.set(track.target, { part, translation, scale, rotation });+ const rotation = quat.normalize(new Float64Array(4), mat4.getRotation(new Float64Array(4), rotationMatrix));+ bindings.set(track.target, { part, translation, scale, rotation, matrix: mat4.create(), hasTransform: false, material: null });+ }+ const binding = bindings.get(track.target);+ const materialTrack = MATERIAL_PROPERTIES.has(track.property);+ if (materialTrack && !binding.material) {+ const retained = isolatedMaterials.get(part);+ binding.material = retained && retained === part.material ? retained : { ...part.material };+ }+ if (!materialTrack) binding.hasTransform = true;+ const output = materialTrack ? new Float64Array(1) : binding[track.property];+ compiledTracks.push({ track, binding, output, materialTrack });+ }+ const compiledBindings = Array.from(bindings.values());+ for (const binding of compiledBindings) {+ if (binding.material) {+ binding.material = retainAnimationMaterial(binding.part, binding.material);}}return {clip,apply(time) {- const sampled = sampleAnimationClip(clip, time);- const transforms = new Map();- for (const value of sampled) {- const binding = bindings.get(value.target);- if (['emission', 'metallic', 'roughness'].includes(value.property)) {- binding.part.material = { ...binding.part.material, [value.property]: value.value };- } else {- if (!transforms.has(value.target)) transforms.set(value.target, { ...binding });- transforms.get(value.target)[value.property] = value.value;+ const clipTime = normalizedTime(clip, time);+ for (const compiled of compiledTracks) {+ sampleTrackInto(compiled.track, clipTime, compiled.output);+ }+ for (const binding of compiledBindings) {+ if (binding.hasTransform) {+ mat4.fromRotationTranslationScale(binding.matrix, binding.rotation, binding.translation, binding.scale);+ for (let index = 0; index < 16; index++) {+ if (!Number.isFinite(binding.matrix[index])) throw new RangeError('Animated matrix exceeds the finite float range. Reduce the transform values.');+ }}}- for (const transform of transforms.values()) {- mat4.fromRotationTranslationScale(transform.part.matrix, transform.rotation, transform.translation, transform.scale);+ // Commit only after every sample and composed matrix is valid.+ for (const compiled of compiledTracks) {+ if (compiled.materialTrack) compiled.binding.material[compiled.track.property] = compiled.output[0];+ }+ for (const binding of compiledBindings) {+ if (binding.hasTransform) binding.part.matrix.set(binding.matrix);}return parts;},diff --git a/src/index.js b/src/index.jsindex 53b14718..0c622bdf 100644--- a/src/index.js+++ b/src/index.js@@ -4,6 +4,7 @@ export const VERSION = packageMetadata.version;export { Renderer67 } from './renderer.js';export { box, cylinder, sphere, torus } from './geometry.js';export { exportGlb } from './export.js';+export { createAnimationMixer } from './animation-mixer.js';export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';export { assemblyOffset } from './assembly.js';diff --git a/src/motion.js b/src/motion.jsindex bfc88269..a69af950 100644--- a/src/motion.js+++ b/src/motion.js@@ -50,9 +50,11 @@ export function createMotionScene() {for (let tooth = 0; tooth < 20; tooth++) {const angle = tooth / 20 * Math.PI * 2;const name = add(`Rotor ${layer} tooth ${tooth}`, 'plate', [Math.cos(angle) * 0.73, height, Math.sin(angle) * 0.73], [0.16, 0.085, 0.13], layer % 2 ? steel : gold, [0, -angle * 180 / Math.PI, 0]);- tracks.push({ target: name, property: 'translation', keyframes: Array.from({ length: 17 }, (_, index) => {+ tracks.push({ target: name, property: 'translation', interpolation: 'CUBICSPLINE', keyframes: Array.from({ length: 17 }, (_, index) => {const rotationAngle = angle + index / 16 * Math.PI * 2 * (layer % 2 ? -1 : 1);- return { time: index / 16 * MOTION_DURATION, value: [Math.cos(rotationAngle) * 0.73, height, Math.sin(rotationAngle) * 0.73] };+ const speed = Math.PI * 2 / MOTION_DURATION * (layer % 2 ? -1 : 1);+ const tangent = [-Math.sin(rotationAngle) * 0.73 * speed, 0, Math.cos(rotationAngle) * 0.73 * speed];+ return { time: index / 16 * MOTION_DURATION, value: [Math.cos(rotationAngle) * 0.73, height, Math.sin(rotationAngle) * 0.73], inTangent: tangent, outTangent: tangent };}) });tracks.push({ target: name, property: 'rotation', keyframes: Array.from({ length: 17 }, (_, index) => ({ time: index / 16 * MOTION_DURATION, value: rotation([0, 1, 0], -angle - index / 16 * Math.PI * 2 * (layer % 2 ? -1 : 1)) })) });}@@ -70,11 +72,18 @@ export function createMotionScene() {for (let pod = 0; pod < 8; pod++) {const angle = pod / 8 * Math.PI * 2;const name = add(`Orbit pod ${pod}`, 'bead', [Math.cos(angle) * 1.8, 0.2, Math.sin(angle) * 1.8], [0.115, 0.115, 0.115], pod % 2 ? glow : amber);- tracks.push({ target: name, property: 'translation', interpolation: 'LINEAR', keyframes: Array.from({ length: 97 }, (_, index) => {- const progress = index / 96;+ tracks.push({ target: name, property: 'translation', interpolation: 'CUBICSPLINE', keyframes: Array.from({ length: 25 }, (_, index) => {+ const progress = index / 24;const orbit = angle + progress * Math.PI * 2;const radius = 1.8 + Math.sin(progress * Math.PI * 2) * 0.2;- return { time: progress * MOTION_DURATION, value: [Math.cos(orbit) * radius, 0.25 + Math.sin(orbit * 2) * 0.65, Math.sin(orbit) * radius] };+ const speed = Math.PI * 2 / MOTION_DURATION;+ const radialSpeed = Math.cos(progress * Math.PI * 2) * 0.2 * speed;+ const tangent = [+ Math.cos(orbit) * radialSpeed - Math.sin(orbit) * radius * speed,+ Math.cos(orbit * 2) * 1.3 * speed,+ Math.sin(orbit) * radialSpeed + Math.cos(orbit) * radius * speed,+ ];+ return { time: progress * MOTION_DURATION, value: [Math.cos(orbit) * radius, 0.25 + Math.sin(orbit * 2) * 0.65, Math.sin(orbit) * radius], inTangent: tangent, outTangent: tangent };}) });}for (let index = 0; index < 16; index++) {diff --git a/tests/animation-mixer.test.js b/tests/animation-mixer.test.jsnew file mode 100644index 00000000..8dd9bac7--- /dev/null+++ b/tests/animation-mixer.test.js@@ -0,0 +1,348 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { mat4, quat } from 'gl-matrix';+import { AnimationClip, AnimationMixer, NumberKeyframeTrack, Object3D, QuaternionKeyframeTrack } from 'three';+import { createAnimationClip, createAnimationPlayer } from '../src/animation.js';+import { createAnimationMixer } from '../src/animation-mixer.js';++function constantClip(target, property, value) {+ return createAnimationClip({ duration: 2, tracks: [{ target, property, keyframes: [{ time: 0, value }] }] });+}++test('players and mixers retain the same isolated material across bindings', () => {+ const target = part('part');+ const player = createAnimationPlayer(constantClip('part', 'emission', 2), [target]);+ const material = target.material;+ const mixer = createAnimationMixer([target]);+ mixer.clipAction(constantClip('part', 'roughness', 0.8)).play();+ mixer.apply(1);+ player.apply(1);+ assert.equal(target.material, material);+ assert.equal(target.material.emission, 2);+ assert.equal(target.material.roughness, 0.8);+});++test('clamped spline scale poses can bind another player or mixer after Float32 rounding', () => {+ const target = part('part');+ const clip = createAnimationClip({ duration: 2, tracks: [{+ target: 'part', property: 'scale', interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: [1, 1, 1], inTangent: [0, 0, 0], outTangent: [-20, 0, 0] },+ { time: 2, value: [1, 1, 1], inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ ],+ }] });+ const mixer = createAnimationMixer([target]);+ mixer.clipAction(clip).play();+ mixer.apply(1);+ assert.equal(target.matrix[0], Math.fround(1e-8));+ assert.doesNotThrow(() => createAnimationMixer([target]));+ assert.doesNotThrow(() => createAnimationPlayer(clip, [target]));+});++function part(name, translation = [0, 0, 0], scale = [1, 1, 1], material = { emission: 0, metallic: 0.2, roughness: 0.5 }) {+ return { name, matrix: mat4.fromRotationTranslationScale(mat4.create(), [0, 0, 0, 1], translation, scale), material };+}++function rotation(angles) {+ return Array.from(quat.fromEuler(new Float64Array(4), ...angles));+}++function close(actual, expected, tolerance = 1e-5) {+ assert.ok(Math.abs(actual - expected) < tolerance, `${actual} differs from ${expected}`);+}++function sceneSnapshot(parts) {+ return parts.map(current => ({ matrix: Array.from(current.matrix), material: { ...current.material } }));+}++test('overlapping walk, head and gesture clips blend per property with captured base pose', () => {+ const parts = [part('body', [1, 2, 3], [2, 3, 4]), part('foot'), part('head'), part('hand')];+ const walk = createAnimationClip({ duration: 2, tracks: [+ { target: 'body', property: 'translation', keyframes: [{ time: 0, value: [0, 2, 3] }, { time: 2, value: [4, 2, 3] }] },+ { target: 'foot', property: 'rotation', keyframes: [{ time: 0, value: rotation([90, 0, 0]) }] },+ ] });+ const head = constantClip('head', 'rotation', rotation([0, 60, 0]));+ const gesture = createAnimationClip({ duration: 2, tracks: [+ { target: 'body', property: 'translation', keyframes: [{ time: 0, value: [6, 2, 3] }] },+ { target: 'hand', property: 'rotation', keyframes: [{ time: 0, value: rotation([0, 0, 90]) }] },+ { target: 'hand', property: 'emission', keyframes: [{ time: 0, value: 4 }] },+ ] });+ const mixer = createAnimationMixer(parts);+ mixer.clipAction(walk).play({ weight: 0.75 });+ mixer.clipAction(head).play({ weight: 0.5 });+ mixer.clipAction(gesture).play({ weight: 0.25 });+ assert.equal(mixer.apply(1), parts);+ close(parts[0].matrix[12], 3);+ assert.deepEqual(Array.from(parts[0].matrix.slice(13, 15)), [2, 3]);+ assert.deepEqual(Array.from(mat4.getScaling(new Float64Array(3), parts[0].matrix)), [2, 3, 4]);+ close(parts[1].matrix[5], Math.cos(67.5 * Math.PI / 180));+ close(parts[2].matrix[0], Math.cos(Math.PI / 6));+ close(parts[3].matrix[0], Math.cos(Math.PI / 8));+ assert.equal(parts[3].material.emission, 1);+});++test('weights above a total of one normalize and match installed Three PropertyMixer semantics', () => {+ const current = part('body', [10, 0, 0]);+ const mixer = createAnimationMixer([current]);+ mixer.clipAction(constantClip('body', 'translation', [2, 0, 0])).play({ weight: 1 });+ mixer.clipAction(constantClip('body', 'translation', [6, 0, 0])).play({ weight: 0.5 });+ mixer.apply(1);+ close(current.matrix[12], 10 / 3);++ const reference = new Object3D();+ reference.position.x = 10;+ const referenceMixer = new AnimationMixer(reference);+ referenceMixer.clipAction(new AnimationClip('first', 2, [new NumberKeyframeTrack('.position[x]', [0], [2])])).setEffectiveWeight(1).play();+ referenceMixer.clipAction(new AnimationClip('second', 2, [new NumberKeyframeTrack('.position[x]', [0], [6])])).setEffectiveWeight(0.5).play();+ referenceMixer.setTime(1);+ close(current.matrix[12], reference.position.x);+});++test('shortest-arc quaternion mixing handles antipodes and matches Three for two actions', () => {+ const current = part('head');+ const firstRotation = rotation([0, 40, 0]);+ const antipode = firstRotation.map(component => -component);+ const mixer = createAnimationMixer([current]);+ const first = mixer.clipAction(constantClip('head', 'rotation', firstRotation)).play({ weight: 0.5 });+ const second = mixer.clipAction(constantClip('head', 'rotation', antipode)).play({ weight: 0.5 });+ mixer.apply(1);+ const expected = mat4.fromQuat(mat4.create(), firstRotation);+ for (let index = 0; index < 16; index++) close(current.matrix[index], expected[index]);+ close(Math.hypot(...mat4.getRotation(new Float64Array(4), current.matrix)), 1);++ const reference = new Object3D();+ const referenceMixer = new AnimationMixer(reference);+ for (const [index, quaternion] of [firstRotation, antipode].entries()) {+ referenceMixer.clipAction(new AnimationClip(`rotation-${index}`, 2, [new QuaternionKeyframeTrack('.quaternion', [0], quaternion)])).setEffectiveWeight(0.5).play();+ }+ referenceMixer.setTime(1);+ reference.updateMatrix();+ for (let index = 0; index < 16; index++) close(current.matrix[index], reference.matrix.elements[index]);+ first.stop(2);+ second.stop(2);+ mixer.apply(2);+ assert.deepEqual(current.matrix, mat4.create());+});++test('crossfades retain boundary continuity and replay correctly across arbitrary seeks', () => {+ const current = part('body');+ const mixer = createAnimationMixer([current]);+ const firstClip = constantClip('body', 'translation', [0, 0, 0]);+ const first = mixer.clipAction(firstClip).play();+ const second = mixer.clipAction(constantClip('body', 'translation', [10, 0, 0]));+ assert.equal(mixer.clipAction(firstClip), first);+ mixer.crossFade(first, second, { at: 2, duration: 2 });+ assert.equal(second.getState(1).phase, 'scheduled');+ assert.equal(first.getState(3).phase, 'fading');+ assert.equal(first.getState(4).weight, 0);+ assert.equal(second.getState(4).weight, 1);+ for (const [time, expected] of [[2, 0], [3, 5], [4, 10], [2 - 1e-6, 0], [2 + 1e-6, 5e-6], [4 - 1e-6, 10 - 5e-6], [4 + 1e-6, 10]]) {+ mixer.apply(time);+ close(current.matrix[12], expected);+ }+ second.stop(6);+ const saved = new Map();+ for (const time of [-1, 0, 2.5, 3, 5, 6, 100]) {+ mixer.apply(time);+ saved.set(time, sceneSnapshot([current]));+ }+ for (const time of [100, 3, -1, 6, 2.5, 5, 0, 3]) {+ mixer.apply(time);+ assert.deepEqual(sceneSnapshot([current]), saved.get(time));+ }+ assert.equal(second.getState(100).phase, 'stopped');+ assert.equal(second.getState(5).playing, true);+});++test('interrupted fades preserve earlier history and restart continuously from the scheduled weight', () => {+ const current = part('body', [2, 0, 0]);+ const mixer = createAnimationMixer([current]);+ const action = mixer.clipAction(constantClip('body', 'translation', [10, 0, 0])).play();+ action.fadeTo(0, { at: 2, duration: 2 });+ action.fadeTo(1, { at: 3, duration: 2 });+ assert.equal(action.getState(2.5).weight, 0.75);+ assert.equal(action.getState(3).weight, 0.5);+ assert.equal(action.getState(4).weight, 0.75);+ assert.equal(action.getState(5).weight, 1);+ for (const time of [5, 3, 2.5, 4, 2.5]) {+ mixer.apply(time);+ close(current.matrix[12], 2 + 8 * action.getState(time).weight);+ }+ mixer.apply(3 - 1e-7);+ const before = current.matrix[12];+ mixer.apply(3 + 1e-7);+ close(current.matrix[12], before);+});++test('play, stop and replay use explicit origins, offsets and signed time scales', () => {+ const current = part('body');+ const clip = createAnimationClip({ duration: 2, loop: true, tracks: [{ target: 'body', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 2, value: [2, 0, 0] }] }] });+ const mixer = createAnimationMixer([current]);+ const action = mixer.clipAction(clip).play({ at: 3, offset: 1.5, timeScale: -1 });+ action.stop(5);+ action.play({ at: 6, offset: 0.5, timeScale: 0 });+ for (const [time, expected] of [[2, 0], [3, 1.5], [4, 0.5], [5, 0], [10, 0.5], [4, 0.5]]) {+ mixer.apply(time);+ close(current.matrix[12], expected);+ }+ mixer.apply(12);+ action.play();+ assert.equal(action.getState(12).localTime, 0);+ assert.equal(mixer.time, 12);+});++test('material blending isolates shared frozen materials and retains identities', () => {+ const shared = Object.freeze({ emission: 2, metallic: 0.3, roughness: 0.6, map: {} });+ const parts = [part('first', [0, 0, 0], [1, 1, 1], shared), part('second', [0, 0, 0], [1, 1, 1], shared), part('untracked', [0, 0, 0], [1, 1, 1], shared)];+ const mixer = createAnimationMixer(parts);+ const first = mixer.clipAction(constantClip('first', 'emission', 10)).play({ weight: 0.5 });+ mixer.clipAction(constantClip('second', 'emission', 4)).play();+ const matrices = parts.map(current => current.matrix);+ const materials = parts.map(current => current.material);+ assert.notEqual(materials[0], materials[1]);+ assert.notEqual(materials[0], shared);+ assert.equal(materials[2], shared);+ for (const time of [0, 1, 0.5]) {+ mixer.apply(time);+ assert.equal(parts[0].material.emission, 6);+ assert.equal(parts[1].material.emission, 4);+ for (let index = 0; index < parts.length; index++) {+ assert.equal(parts[index].matrix, matrices[index]);+ assert.equal(parts[index].material, materials[index]);+ assert.equal(parts[index].material.map, shared.map);+ }+ }+ first.stop(2);+ mixer.apply(2);+ assert.equal(parts[0].material.emission, 2);+ assert.equal(shared.emission, 2);+});++test('invalid control commands do not corrupt action timelines or partial crossfades', () => {+ const current = part('body');+ const mixer = createAnimationMixer([current]);+ const first = mixer.clipAction(constantClip('body', 'translation', [2, 0, 0])).play();+ const second = mixer.clipAction(constantClip('body', 'translation', [10, 0, 0]));+ for (const weight of [-1, 1.1, Infinity, NaN, '1']) {+ assert.throws(() => first.play({ at: 1, weight }), RangeError);+ assert.throws(() => first.fadeTo(weight, { at: 1, duration: 1 }), RangeError);+ }+ for (const duration of [0, -1, Infinity, NaN]) {+ assert.throws(() => mixer.crossFade(first, second, { at: 1, duration }), RangeError);+ }+ assert.equal(first.getState(2).weight, 1);+ assert.equal(second.getState(2).playing, false);+ assert.throws(() => first.fadeTo(0, { at: 1e308, duration: 1 }), RangeError);+ assert.throws(() => first.play({ at: Infinity }), TypeError);+ assert.throws(() => first.play({ timeScale: NaN }), TypeError);+ assert.throws(() => first.play({ offset: Infinity }), TypeError);+ second.play({ at: 10 });+ assert.throws(() => mixer.crossFade(first, second, { at: 2, duration: 2 }), /nondecreasing/);+ assert.equal(first.getState(3).weight, 1);+ assert.throws(() => mixer.crossFade(first, first, { at: 2, duration: 2 }), RangeError);+ assert.throws(() => mixer.crossFade(first, {}, { at: 2, duration: 2 }), RangeError);+ first.stop(4);+ assert.throws(() => first.fadeTo(1, { at: 5, duration: 1 }), /Play/);+ assert.throws(() => first.play({ at: 3 }), /nondecreasing/);+ assert.throws(() => mixer.apply(NaN), TypeError);+});++test('spline domains stay positive and zero-weight invalid curves do not run', () => {+ const current = part('body');+ const clip = createAnimationClip({ duration: 2, tracks: [+ { target: 'body', property: 'scale', interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: [1, 1, 1], inTangent: [0, 0, 0], outTangent: [-20, 0, 0] },+ { time: 2, value: [1, 1, 1], inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ ] },+ { target: 'body', property: 'roughness', interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: 0.5, inTangent: 0, outTangent: -20 },+ { time: 2, value: 0.5, inTangent: 0, outTangent: 0 },+ ] },+ ] });+ const mixer = createAnimationMixer([current]);+ mixer.clipAction(clip).play();+ mixer.apply(1);+ assert.ok(current.matrix[0] > 0);+ assert.equal(current.material.roughness, 1e-8);+ const invalidRotation = createAnimationClip({ duration: 2, tracks: [{ target: 'body', property: 'rotation', interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: [0, 0, 0, 1], inTangent: [0, 0, 0, 0], outTangent: [0, 0, 0, 0] },+ { time: 2, value: [0, 0, 0, -1], inTangent: [0, 0, 0, 0], outTangent: [0, 0, 0, 0] },+ ] }] });+ const invalidAction = mixer.clipAction(invalidRotation).play({ weight: 0 });+ assert.doesNotThrow(() => mixer.apply(1));+ const expected = sceneSnapshot([current]);+ invalidAction.play({ at: 1, offset: 1, weight: 1 });+ assert.throws(() => mixer.apply(1), /invalid quaternion/);+ assert.deepEqual(sceneSnapshot([current]), expected);+ assert.equal(mixer.time, 1);+});++test('invalid samples leave every matrix, material and last successful time unchanged', () => {+ const parts = [part('first'), part('second')];+ const mixer = createAnimationMixer(parts);+ const valid = mixer.clipAction(createAnimationClip({ duration: 2, tracks: [+ { target: 'first', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 2, value: [2, 0, 0] }] },+ { target: 'first', property: 'emission', keyframes: [{ time: 0, value: 0 }, { time: 2, value: 2 }] },+ ] })).play();+ mixer.apply(0.5);+ const expected = sceneSnapshot(parts);+ const invalid = mixer.clipAction(createAnimationClip({ duration: 2, tracks: [{ target: 'second', property: 'translation', keyframes: [+ { time: 0, value: [0, 0, 0] }, { time: 2, value: [1e100, 0, 0] },+ ] }] })).play();+ assert.throws(() => mixer.apply(1), /finite Float32/);+ assert.deepEqual(sceneSnapshot(parts), expected);+ assert.equal(mixer.time, 0.5);+ invalid.stop(1);+ mixer.apply(1);+ assert.equal(parts[0].matrix[12], 1);+ assert.equal(parts[0].material.emission, 1);+ assert.equal(valid.getState(1).weight, 1);+});++test('retained transform buffers survive hundreds of seeks without replacement', () => {+ const current = part('body');+ const mixer = createAnimationMixer([current]);+ const first = mixer.clipAction(constantClip('body', 'translation', [2, 0, 0])).play();+ const second = mixer.clipAction(constantClip('body', 'translation', [6, 0, 0]));+ mixer.crossFade(first, second, { at: 0, duration: 10 });+ const originalCompose = mat4.fromRotationTranslationScale;+ let retained;+ let calls = 0;+ mat4.fromRotationTranslationScale = (output, rotationValue, translation, scale) => {+ if (!retained) retained = [output, rotationValue, translation, scale];+ else {+ assert.equal(output, retained[0]);+ assert.equal(rotationValue, retained[1]);+ assert.equal(translation, retained[2]);+ assert.equal(scale, retained[3]);+ }+ calls++;+ return originalCompose(output, rotationValue, translation, scale);+ };+ try {+ for (let frame = 0; frame < 200; frame++) mixer.apply((frame * 17 % 100) / 10);+ } finally {+ mat4.fromRotationTranslationScale = originalCompose;+ }+ assert.equal(calls, 200);+});++test('invalid bindings fail without publishing partially registered material copies', () => {+ const current = part('body');+ const material = current.material;+ const mixer = createAnimationMixer([current]);+ const invalidClip = createAnimationClip({ duration: 2, tracks: [+ { target: 'body', property: 'emission', keyframes: [{ time: 0, value: 1 }] },+ { target: 'missing', property: 'emission', keyframes: [{ time: 0, value: 1 }] },+ ] });+ assert.throws(() => mixer.clipAction(invalidClip), /not found/);+ assert.equal(current.material, material);+ assert.throws(() => mixer.clipAction(constantClip('body', 'value', 1)), /Value tracks/);+ assert.throws(() => createAnimationMixer([current, current]), /Duplicate/);+ assert.throws(() => createAnimationMixer([{ name: 'body', matrix: mat4.create().fill(NaN) }]), TypeError);+ const projective = part('projective');+ projective.matrix[3] = 1;+ assert.throws(() => createAnimationMixer([projective]), /affine/);+ const shear = part('shear');+ shear.matrix[4] = 0.5;+ assert.throws(() => createAnimationMixer([shear]), /shear/);+});diff --git a/tests/animation.test.js b/tests/animation.test.jsindex ce2514b5..9399f4d9 100644--- a/tests/animation.test.js+++ b/tests/animation.test.js@@ -112,3 +112,232 @@ test('invalid tracks, values and bindings fail explicitly', () => {assert.throws(() => sampleAnimationClip(valueClip(), Infinity), TypeError);assert.throws(() => createAnimationPlayer(createAnimationClip({ duration: 1, tracks: [track] }), []), RangeError);});++test('orbital showcase preserves speed across keyframe boundaries with fewer spline keys', () => {+ const scene = createMotionScene();+ const track = scene.clip.tracks.find(track => track.target === 'Orbit pod 0');+ assert.equal(track.keyframes.length, 25);+ const position = time => sampleAnimationClip(scene.clip, time).find(sample => sample.target === 'Orbit pod 0').value;+ const step = 1e-4;+ for (let time = 0.5; time < scene.duration; time += 0.5) {+ const before = position(time - step);+ const center = position(time);+ const after = position(time + step);+ for (let axis = 0; axis < 3; axis++) {+ const incomingSpeed = (center[axis] - before[axis]) / step;+ const outgoingSpeed = (after[axis] - center[axis]) / step;+ assert.ok(Math.abs(incomingSpeed - outgoingSpeed) < 0.001);+ }+ }+ const start = position(0);+ const end = position(scene.duration);+ for (let axis = 0; axis < 3; axis++) assertClose(start[axis], end[axis], 1e-12);+});++function splineTrack(property, startValue, endValue, outgoing, incoming, duration = 2, target = 'part') {+ const zero = typeof startValue === 'number' ? 0 : startValue.map(() => 0);+ return {+ target,+ property,+ interpolation: 'CUBICSPLINE',+ keyframes: [+ { time: 0, value: startValue, inTangent: zero, outTangent: outgoing },+ { time: duration, value: endValue, inTangent: incoming, outTangent: zero },+ ],+ };+}++function assertClose(actual, expected, tolerance = 1e-6) {+ assert.ok(Math.abs(actual - expected) < tolerance, `${actual} differs from ${expected}`);+}++test('CUBICSPLINE uses per-second tangents for scalar and vector Hermite curves', () => {+ const scalar = createAnimationClip({ duration: 2, tracks: [splineTrack('value', 0, 2, 4, 0)] });+ assert.equal(sampleAnimationClip(scalar, 0.5)[0].value, 1.4375);+ assert.equal(sampleAnimationClip(scalar, 1)[0].value, 2);+ assert.equal(sampleAnimationClip(scalar, 2)[0].value, 2);+ const vector = createAnimationClip({ duration: 2, tracks: [splineTrack('translation', [0, 2, -2], [2, 4, 2], [4, 0, -4], [0, 4, 0])] });+ assert.deepEqual(sampleAnimationClip(vector, 1)[0].value, [2, 2, -1]);+ const longer = createAnimationClip({ duration: 4, tracks: [splineTrack('value', 0, 2, 4, 0, 4)] });+ assert.equal(sampleAnimationClip(longer, 2)[0].value, 3);+});++test('spline quaternion components use Hermite tangents then normalize without a shortest-arc sign flip', () => {+ const clip = createAnimationClip({ duration: 2, tracks: [splineTrack('rotation', [0, 0, 0, 1], [0, 1, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0])] });+ const midpoint = sampleAnimationClip(clip, 1)[0].value;+ assertClose(midpoint[1], 2 / Math.sqrt(5));+ assertClose(midpoint[3], 1 / Math.sqrt(5));+ assertClose(Math.hypot(...midpoint), 1);+ const signed = createAnimationClip({ duration: 2, tracks: [splineTrack('rotation', [0, 0, 0, 1], [0, -Math.SQRT1_2, 0, -Math.SQRT1_2], [0, 0, 0, 0], [0, 0, 0, 0])] });+ assert.ok(sampleAnimationClip(signed, 1)[0].value[1] < -0.9);+ const invalid = createAnimationClip({ duration: 2, tracks: [splineTrack('rotation', [0, 0, 0, 1], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0])] });+ assert.throws(() => sampleAnimationClip(invalid, 1), /invalid quaternion/);+});++test('spline input values, tangents and sampled arrays remain isolated', () => {+ const track = splineTrack('translation', [0, 0, 0], [2, 2, 2], [4, 0, 0], [0, 0, 0]);+ track.keyframes[0].outTangent = new Float32Array(track.keyframes[0].outTangent);+ const clip = createAnimationClip({ duration: 2, tracks: [track] });+ track.keyframes[0].outTangent[0] = 100;+ track.keyframes[1].value[0] = 100;+ track.keyframes.reverse();+ const sampled = sampleAnimationClip(clip, 1)[0].value;+ assert.deepEqual(sampled, [2, 1, 1]);+ sampled[0] = 100;+ assert.deepEqual(sampleAnimationClip(clip, 1)[0].value, [2, 1, 1]);+ assert.ok(Object.isFrozen(clip.tracks[0].keyframes[0].outTangent));+ const restored = createAnimationClip(JSON.parse(JSON.stringify(clip)));+ assert.deepEqual(sampleAnimationClip(restored, 1), sampleAnimationClip(clip, 1));+});++test('malformed spline tangents and undersized spline tracks fail at compilation', () => {+ for (const property of ['value', 'translation', 'rotation']) {+ const value = property === 'value' ? 1 : property === 'rotation' ? [0, 0, 0, 1] : [0, 0, 0];+ const zero = typeof value === 'number' ? 0 : value.map(() => 0);+ for (const malformed of [undefined, null, NaN, Infinity, [0], [0, 0, NaN], [0, 0, 0, Infinity]]) {+ for (const tangentName of ['inTangent', 'outTangent']) {+ const track = splineTrack(property, value, value, zero, zero);+ track.keyframes[0][tangentName] = malformed;+ assert.throws(() => createAnimationClip({ duration: 2, tracks: [track] }), TypeError);+ }+ }+ const track = splineTrack(property, value, value, zero, zero);+ track.keyframes.pop();+ assert.throws(() => createAnimationClip({ duration: 2, tracks: [track] }), /at least two/);+ }+});++test('spline overshoot stays in positive scale and valid material domains', () => {+ const clip = createAnimationClip({ duration: 2, tracks: [+ splineTrack('scale', [1, 1, 1], [1, 1, 1], [-20, 0, 0], [0, 0, 0]),+ splineTrack('emission', 1, 1, -20, 0),+ splineTrack('metallic', 0.5, 0.5, 20, 0),+ splineTrack('roughness', 0.5, 0.5, -20, 0),+ ] });+ const sampled = sampleAnimationClip(clip, 1);+ assert.deepEqual(sampled.map(track => track.value), [[1e-8, 1, 1], 0, 1, 1e-8]);+ const part = { name: 'part', matrix: mat4.create(), material: {} };+ createAnimationPlayer(clip, [part]).apply(1);+ assert.ok(part.matrix[0] > 0);+ assert.equal(part.material.roughness, 1e-8);+ const upperRoughness = createAnimationClip({ duration: 2, tracks: [splineTrack('roughness', 0.5, 0.5, 20, 0)] });+ assert.equal(sampleAnimationClip(upperRoughness, 1)[0].value, 1);+ const lowerMetallic = createAnimationClip({ duration: 2, tracks: [splineTrack('metallic', 0.5, 0.5, -20, 0)] });+ assert.equal(sampleAnimationClip(lowerMetallic, 1)[0].value, 0);+});++test('compiled playback isolates shared materials and seeks deterministically with stable identities', () => {+ const shared = Object.freeze({ emission: 0, metallic: 0.5, roughness: 0.5, map: {} });+ const parts = ['first', 'second', 'untracked'].map(name => ({ name, matrix: mat4.create(), material: shared }));+ const clip = createAnimationClip({ duration: 2, loop: true, tracks: [+ splineTrack('translation', [0, 0, 0], [2, 4, 6], [4, 0, 0], [0, 0, 0], 2, 'first'),+ { ...splineTrack('emission', 0, 2, 4, 0), target: 'first' },+ { ...splineTrack('emission', 0, 4, 0, 0), target: 'second' },+ ] });+ const player = createAnimationPlayer(clip, parts);+ const matrices = parts.map(part => part.matrix);+ const materials = parts.map(part => part.material);+ assert.notEqual(materials[0], shared);+ assert.notEqual(materials[0], materials[1]);+ assert.equal(materials[2], shared);+ player.apply(0.5);+ const expected = Array.from(parts[0].matrix);+ const emission = parts[0].material.emission;+ for (const time of [1.9, -1, 2, 1, -3, 0.5]) player.apply(time);+ assert.deepEqual(Array.from(parts[0].matrix), expected);+ assert.equal(parts[0].material.emission, emission);+ assert.equal(shared.emission, 0);+ for (let index = 0; index < parts.length; index++) {+ assert.equal(parts[index].matrix, matrices[index]);+ assert.equal(parts[index].material, materials[index]);+ assert.equal(parts[index].material.map, shared.map);+ }+});++test('multiple players share an isolated target material without detaching earlier bindings', () => {+ const shared = Object.freeze({ emission: 0, roughness: 0.5 });+ const part = { name: 'part', matrix: mat4.create(), material: shared };+ const emission = createAnimationPlayer(createAnimationClip({ duration: 2, tracks: [{+ target: 'part', property: 'emission', keyframes: [{ time: 0, value: 0 }, { time: 2, value: 2 }],+ }] }), [part]);+ const material = part.material;+ const roughness = createAnimationPlayer(createAnimationClip({ duration: 2, tracks: [{+ target: 'part', property: 'roughness', keyframes: [{ time: 0, value: 0.5 }, { time: 2, value: 1 }],+ }] }), [part]);+ for (const time of [1, 2, 0, 1]) {+ emission.apply(time);+ roughness.apply(time);+ assert.equal(part.material, material);+ assert.equal(part.material.emission, time);+ assert.equal(part.material.roughness, 0.5 + time / 4);+ }+ assert.equal(shared.emission, 0);+ assert.equal(shared.roughness, 0.5);+});++test('apply reuses the same transform inputs and composed matrix buffers', () => {+ const clip = createAnimationClip({ duration: 2, tracks: [+ splineTrack('translation', [0, 0, 0], [2, 4, 6], [0, 0, 0], [0, 0, 0]),+ splineTrack('rotation', [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]),+ splineTrack('scale', [1, 1, 1], [2, 2, 2], [0, 0, 0], [0, 0, 0]),+ ] });+ const part = { name: 'part', matrix: mat4.create(), material: {} };+ const player = createAnimationPlayer(clip, [part]);+ const originalCompose = mat4.fromRotationTranslationScale;+ let firstBuffers;+ let calls = 0;+ mat4.fromRotationTranslationScale = (output, rotation, translation, scale) => {+ if (!firstBuffers) firstBuffers = [output, rotation, translation, scale];+ else {+ assert.equal(output, firstBuffers[0]);+ assert.equal(rotation, firstBuffers[1]);+ assert.equal(translation, firstBuffers[2]);+ assert.equal(scale, firstBuffers[3]);+ }+ calls++;+ return originalCompose(output, rotation, translation, scale);+ };+ try {+ for (let frame = 0; frame < 100; frame++) player.apply((frame % 20) / 10);+ } finally {+ mat4.fromRotationTranslationScale = originalCompose;+ }+ assert.equal(calls, 100);+});++test('invalid sampled outputs leave all bound matrices and material properties unchanged', () => {+ const part = { name: 'part', matrix: mat4.create(), material: { emission: 0 } };+ const zeroRotation = createAnimationClip({ duration: 2, tracks: [+ splineTrack('translation', [0, 0, 0], [2, 0, 0], [0, 0, 0], [0, 0, 0]),+ splineTrack('emission', 0, 2, 0, 0),+ splineTrack('rotation', [0, 0, 0, 1], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0]),+ ] });+ const player = createAnimationPlayer(zeroRotation, [part]);+ const expected = Array.from(part.matrix);+ assert.throws(() => player.apply(1), /invalid quaternion/);+ assert.deepEqual(Array.from(part.matrix), expected);+ assert.equal(part.material.emission, 0);+ player.apply(0);+ assert.deepEqual(Array.from(part.matrix), expected);+ assert.throws(() => player.apply(NaN), TypeError);+ const overflow = createAnimationClip({ duration: 100, tracks: [splineTrack('value', 0, 1, 1e308, 0, 100)] });+ assert.throws(() => sampleAnimationClip(overflow, 50), /finite/);+ const matrixOverflow = createAnimationClip({ duration: 2, tracks: [splineTrack('translation', [0, 0, 0], [1e100, 0, 0], [0, 0, 0], [0, 0, 0])] });+ const overflowPlayer = createAnimationPlayer(matrixOverflow, [part]);+ assert.throws(() => overflowPlayer.apply(1), /finite float range/);+ assert.deepEqual(Array.from(part.matrix), expected);+});++test('spline rotation playback matches public sampling for large finite tangent magnitudes', () => {+ const clip = createAnimationClip({ duration: 2, tracks: [splineTrack('rotation', [0, 0, 0, 1], [0, 1, 0, 0], [0, 1e100, 0, 0], [0, 0, 0, 0])] });+ const part = { name: 'part', matrix: mat4.create(), material: {} };+ const player = createAnimationPlayer(clip, [part]);+ for (const time of [0.5, 1.5, 1, 0, 2]) {+ const sampled = sampleAnimationClip(clip, time)[0].value;+ const expected = mat4.fromRotationTranslationScale(mat4.create(), sampled, [0, 0, 0], [1, 1, 1]);+ player.apply(time);+ assert.deepEqual(part.matrix, expected);+ }+ const invalid = splineTrack('rotation', [1e308, 1e308, 1e308, 1e308], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]);+ assert.throws(() => createAnimationClip({ duration: 2, tracks: [invalid] }), /finite nonzero/);+});